file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
// Dependency file: @openzeppelin/contracts/token/ERC20/IERC20.sol // 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); } // Dependency file: @openzeppelin/contracts/introspection/IERC165.sol // pragma solidity ^0.6.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); } // Dependency file: @openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol // pragma solidity ^0.6.0; // import "@openzeppelin/contracts/introspection/IERC165.sol"; /** * _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); } // Dependency file: @openzeppelin/contracts/introspection/ERC165.sol // pragma solidity ^0.6.0; // import "@openzeppelin/contracts/introspection/IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ 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 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; } } // Dependency file: @openzeppelin/contracts/token/ERC1155/ERC1155Receiver.sol // pragma solidity ^0.6.0; // import "@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol"; // import "@openzeppelin/contracts/introspection/ERC165.sol"; /** * @dev _Available since v3.1._ */ abstract contract ERC1155Receiver is ERC165, IERC1155Receiver { constructor() public { _registerInterface( ERC1155Receiver(0).onERC1155Received.selector ^ ERC1155Receiver(0).onERC1155BatchReceived.selector ); } } // Dependency file: @openzeppelin/contracts/math/SafeMath.sol // 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; } } // Dependency file: @openzeppelin/contracts/utils/Address.sol // 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); } } } } // Dependency file: @openzeppelin/contracts/token/ERC20/SafeERC20.sol // pragma solidity ^0.6.0; // import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // import "@openzeppelin/contracts/math/SafeMath.sol"; // import "@openzeppelin/contracts/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 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"); } } } // Dependency file: @openzeppelin/contracts/utils/EnumerableMap.sol // pragma solidity ^0.6.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 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) { return _get(map, key, "EnumerableMap: nonexistent key"); } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. */ 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(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(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(uint256(_get(map._inner, bytes32(key)))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint256(_get(map._inner, bytes32(key), errorMessage))); } } // Dependency file: @openzeppelin/contracts/utils/ReentrancyGuard.sol // pragma solidity ^0.6.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]. */ 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 () internal { _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; } } // Dependency file: @openzeppelin/contracts/GSN/Context.sol // 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; } } // Dependency file: @openzeppelin/contracts/access/Ownable.sol // pragma solidity ^0.6.0; // import "@openzeppelin/contracts/GSN/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. */ 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; } } // Dependency file: contracts/interfaces/IAlpaToken.sol // pragma solidity 0.6.12; // import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // import "@openzeppelin/contracts/access/Ownable.sol"; interface IAlpaToken is IERC20 { function mint(address _to, uint256 _amount) external; } // Dependency file: contracts/interfaces/IAlpaSupplier.sol // pragma solidity 0.6.12; interface IAlpaSupplier { /** * @dev mint and distribute ALPA to caller * NOTE: caller must be approved consumer */ function distribute(uint256 _since) external returns (uint256); /** * @dev returns number of ALPA _consumer is expected to recieved at current block */ function preview(address _consumer, uint256 _since) external view returns (uint256); } // Dependency file: @openzeppelin/contracts/token/ERC1155/IERC1155.sol // pragma solidity ^0.6.2; // import "@openzeppelin/contracts/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; } // Dependency file: contracts/interfaces/ICryptoAlpaca.sol // pragma solidity =0.6.12; // import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; interface ICryptoAlpaca is IERC1155 { function getAlpaca(uint256 _id) external view returns ( uint256 id, bool isReady, uint256 cooldownEndBlock, uint256 birthTime, uint256 matronId, uint256 sireId, uint256 hatchingCost, uint256 hatchingCostMultiplier, uint256 hatchCostMultiplierEndBlock, uint256 generation, uint256 gene, uint256 energy, uint256 state ); function hasPermissionToBreedAsSire(address _addr, uint256 _id) external view returns (bool); function grandPermissionToBreed(address _addr, uint256 _sireId) external; function clearPermissionToBreed(uint256 _alpacaId) external; function hatch(uint256 _matronId, uint256 _sireId) external payable returns (uint256); function crack(uint256 _id) external; } // Dependency file: contracts/interfaces/ICryptoAlpacaEnergyListener.sol // pragma solidity 0.6.12; // import "@openzeppelin/contracts/introspection/IERC165.sol"; interface ICryptoAlpacaEnergyListener is IERC165 { /** @dev Handles the Alpaca energy change callback. @param id The id of the Alpaca which the energy changed @param oldEnergy The ID of the token being transferred @param newEnergy The amount of tokens being transferred */ function onCryptoAlpacaEnergyChanged( uint256 id, uint256 oldEnergy, uint256 newEnergy ) external; } // Dependency file: contracts/interfaces/CryptoAlpacaEnergyListener.sol // pragma solidity 0.6.12; // import "@openzeppelin/contracts/introspection/ERC165.sol"; // import "contracts/interfaces/ICryptoAlpacaEnergyListener.sol"; abstract contract CryptoAlpacaEnergyListener is ERC165, ICryptoAlpacaEnergyListener { constructor() public { _registerInterface( CryptoAlpacaEnergyListener(0).onCryptoAlpacaEnergyChanged.selector ); } } // Root file: contracts/AlpacaFarm/AlpacaFarm.sol pragma solidity 0.6.12; // import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // import "@openzeppelin/contracts/token/ERC1155/ERC1155Receiver.sol"; // import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; // import "@openzeppelin/contracts/utils/EnumerableMap.sol"; // import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; // import "@openzeppelin/contracts/math/SafeMath.sol"; // import "@openzeppelin/contracts/access/Ownable.sol"; // import "contracts/interfaces/IAlpaToken.sol"; // import "contracts/interfaces/IAlpaSupplier.sol"; // import "contracts/interfaces/ICryptoAlpaca.sol"; // import "contracts/interfaces/CryptoAlpacaEnergyListener.sol"; // Alpaca Farm manages your LP and takes good care of you alpaca! contract AlpacaFarm is Ownable, ReentrancyGuard, ERC1155Receiver, CryptoAlpacaEnergyListener { using SafeMath for uint256; using SafeERC20 for IERC20; using EnumerableMap for EnumerableMap.UintToAddressMap; /* ========== EVENTS ========== */ event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 amount); /* ========== STRUCT ========== */ // Info of each user. struct UserInfo { // How many LP tokens the user has provided. uint256 amount; // Reward debt. What has been paid so far uint256 rewardDebt; // alpaca user transfered to AlpacaFarm to manage the LP assets uint256 alpacaID; // alpaca's energy uint256 alpacaEnergy; } // Info of each pool. struct PoolInfo { // Address of LP token contract. IERC20 lpToken; // Last block number that ALPAs distribution occurs. uint256 lastRewardBlock; // Accumulated ALPAs per share. Share is determined by LP deposit and total alpaca's energy uint256 accAlpaPerShare; // Accumulated Share uint256 accShare; } /* ========== STATES ========== */ // The ALPA ERC20 token IAlpaToken public alpa; // Crypto alpaca contract ICryptoAlpaca public cryptoAlpaca; // Alpa Supplier IAlpaSupplier public supplier; // Energy if user does not have any alpaca transfered to AlpacaFarm to manage the LP assets uint256 public constant EMPTY_ALPACA_ENERGY = 1; // farm pool info PoolInfo public poolInfo; // Info of each user that stakes LP tokens. mapping(address => UserInfo) public userInfo; // map that keep tracks of the alpaca's original owner so contract knows where to send back when // users swapped or retrieved their alpacas EnumerableMap.UintToAddressMap private alpacaOriginalOwner; uint256 public constant SAFE_MULTIPLIER = 1e16; /* ========== CONSTRUCTOR ========== */ constructor( IAlpaToken _alpa, ICryptoAlpaca _cryptoAlpaca, IAlpaSupplier _supplier, IERC20 lpToken ) public { alpa = _alpa; cryptoAlpaca = _cryptoAlpaca; supplier = _supplier; poolInfo = PoolInfo({ lpToken: lpToken, lastRewardBlock: block.number, accAlpaPerShare: 0, accShare: 0 }); } /* ========== PUBLIC ========== */ /** * @dev View `_user` pending ALPAs */ function pendingAlpa(address _user) external view returns (uint256) { UserInfo storage user = userInfo[_user]; uint256 accAlpaPerShare = poolInfo.accAlpaPerShare; uint256 lpSupply = poolInfo.lpToken.balanceOf(address(this)); if (block.number > poolInfo.lastRewardBlock && lpSupply != 0) { uint256 total = supplier.preview( address(this), poolInfo.lastRewardBlock ); accAlpaPerShare = accAlpaPerShare.add( total.mul(SAFE_MULTIPLIER).div(poolInfo.accShare) ); } return user .amount .mul(_safeUserAlpacaEnergy(user)) .mul(accAlpaPerShare) .div(SAFE_MULTIPLIER) .sub(user.rewardDebt); } /** * @dev Update reward variables of the given pool to be up-to-date. */ function updatePool() public { if (block.number <= poolInfo.lastRewardBlock) { return; } uint256 lpSupply = poolInfo.lpToken.balanceOf(address(this)); if (lpSupply == 0) { poolInfo.lastRewardBlock = block.number; return; } uint256 reward = supplier.distribute(poolInfo.lastRewardBlock); poolInfo.accAlpaPerShare = poolInfo.accAlpaPerShare.add( reward.mul(SAFE_MULTIPLIER).div(poolInfo.accShare) ); poolInfo.lastRewardBlock = block.number; } /** * @dev Retrieve caller's Alpaca. */ function retrieve() public nonReentrant { address sender = _msgSender(); UserInfo storage user = userInfo[sender]; require(user.alpacaID != 0, "AlpacaFarm: you do not have any alpaca"); if (user.amount > 0) { updatePool(); uint256 pending = user .amount .mul(user.alpacaEnergy) .mul(poolInfo.accAlpaPerShare) .div(SAFE_MULTIPLIER) .sub(user.rewardDebt); if (pending > 0) { _safeAlpaTransfer(msg.sender, pending); } user.rewardDebt = user .amount .mul(EMPTY_ALPACA_ENERGY) .mul(poolInfo.accAlpaPerShare) .div(SAFE_MULTIPLIER); poolInfo.accShare = poolInfo.accShare.sub( (user.alpacaEnergy.sub(1)).mul(user.amount) ); } uint256 prevAlpacaID = user.alpacaID; user.alpacaID = 0; user.alpacaEnergy = 0; // Remove alpaca id to original user mapping alpacaOriginalOwner.remove(prevAlpacaID); cryptoAlpaca.safeTransferFrom( address(this), msg.sender, prevAlpacaID, 1, "" ); } /** * @dev Deposit LP tokens to AlpacaFarm for ALPA allocation. */ function deposit(uint256 _amount) public nonReentrant { updatePool(); UserInfo storage user = userInfo[msg.sender]; if (user.amount > 0) { uint256 pending = user .amount .mul(_safeUserAlpacaEnergy(user)) .mul(poolInfo.accAlpaPerShare) .div(SAFE_MULTIPLIER) .sub(user.rewardDebt); if (pending > 0) { _safeAlpaTransfer(msg.sender, pending); } } if (_amount > 0) { poolInfo.lpToken.safeTransferFrom( address(msg.sender), address(this), _amount ); user.amount = user.amount.add(_amount); poolInfo.accShare = poolInfo.accShare.add( _safeUserAlpacaEnergy(user).mul(_amount) ); } user.rewardDebt = user .amount .mul(_safeUserAlpacaEnergy(user)) .mul(poolInfo.accAlpaPerShare) .div(SAFE_MULTIPLIER); emit Deposit(msg.sender, _amount); } /** * @dev Withdraw LP tokens from AlpacaFarm. */ function withdraw(uint256 _amount) public nonReentrant { UserInfo storage user = userInfo[msg.sender]; require(user.amount >= _amount, "AlpacaFarm: invalid amount"); updatePool(); uint256 pending = user .amount .mul(_safeUserAlpacaEnergy(user)) .mul(poolInfo.accAlpaPerShare) .div(SAFE_MULTIPLIER) .sub(user.rewardDebt); if (pending > 0) { _safeAlpaTransfer(msg.sender, pending); } if (_amount > 0) { user.amount = user.amount.sub(_amount); poolInfo.lpToken.safeTransfer(address(msg.sender), _amount); poolInfo.accShare = poolInfo.accShare.sub( _safeUserAlpacaEnergy(user).mul(_amount) ); } user.rewardDebt = user .amount .mul(_safeUserAlpacaEnergy(user)) .mul(poolInfo.accAlpaPerShare) .div(SAFE_MULTIPLIER); emit Withdraw(msg.sender, _amount); } // Withdraw without caring about rewards. // EMERGENCY ONLY. function emergencyWithdraw() public { UserInfo storage user = userInfo[msg.sender]; require(user.amount > 0, "AlpacaFarm: insufficient balance"); uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; poolInfo.lpToken.safeTransfer(address(msg.sender), amount); emit EmergencyWithdraw(msg.sender, amount); } /* ========== PRIVATE ========== */ function _safeUserAlpacaEnergy(UserInfo storage info) private view returns (uint256) { if (info.alpacaEnergy == 0) { return EMPTY_ALPACA_ENERGY; } return info.alpacaEnergy; } // Safe alpa transfer function, just in case if rounding error causes pool to not have enough ALPAs. function _safeAlpaTransfer(address _to, uint256 _amount) private { uint256 alpaBal = alpa.balanceOf(address(this)); if (_amount > alpaBal) { alpa.transfer(_to, alpaBal); } else { alpa.transfer(_to, _amount); } } /* ========== ERC1155Receiver ========== */ /** * @dev onERC1155Received implementation per IERC1155Receiver spec */ function onERC1155Received( address, address _from, uint256 _id, uint256, bytes calldata ) external override nonReentrant returns (bytes4) { require( msg.sender == address(cryptoAlpaca), "AlpacaFarm: received alpaca from unauthenticated contract" ); require(_id != 0, "AlpacaFarm: invalid alpaca"); UserInfo storage user = userInfo[_from]; // Fetch alpaca energy (, , , , , , , , , , , uint256 energy, ) = cryptoAlpaca.getAlpaca(_id); require(energy > 0, "AlpacaFarm: invalid alpaca energy"); if (user.amount > 0) { updatePool(); uint256 pending = user .amount .mul(_safeUserAlpacaEnergy(user)) .mul(poolInfo.accAlpaPerShare) .div(SAFE_MULTIPLIER) .sub(user.rewardDebt); if (pending > 0) { _safeAlpaTransfer(_from, pending); } // Update user reward debt with new energy user.rewardDebt = user .amount .mul(energy) .mul(poolInfo.accAlpaPerShare) .div(SAFE_MULTIPLIER); poolInfo.accShare = poolInfo .accShare .add(energy.mul(user.amount)) .sub(_safeUserAlpacaEnergy(user).mul(user.amount)); } // update user global uint256 prevAlpacaID = user.alpacaID; user.alpacaID = _id; user.alpacaEnergy = energy; // keep track of alpaca owner alpacaOriginalOwner.set(_id, _from); // Give original owner the right to breed cryptoAlpaca.grandPermissionToBreed(_from, _id); if (prevAlpacaID != 0) { // Transfer alpaca back to owner cryptoAlpaca.safeTransferFrom( address(this), _from, prevAlpacaID, 1, "" ); } return bytes4( keccak256( "onERC1155Received(address,address,uint256,uint256,bytes)" ) ); } /** * @dev onERC1155BatchReceived implementation per IERC1155Receiver spec * User should not send using batch. */ function onERC1155BatchReceived( address, address, uint256[] memory, uint256[] memory, bytes memory ) external override returns (bytes4) { require( false, "AlpacaFarm: only supports transfer single alpaca at a time (e.g safeTransferFrom)" ); } /* ========== ICryptoAlpacaEnergyListener ========== */ /** @dev Handles the Alpaca energy change callback. @param _id The id of the Alpaca which the energy changed @param _newEnergy The new alpaca energy it changed to */ function onCryptoAlpacaEnergyChanged( uint256 _id, uint256, uint256 _newEnergy ) external override { require( msg.sender == address(cryptoAlpaca), "AlpacaFarm: received alpaca from unauthenticated contract" ); require( alpacaOriginalOwner.contains(_id), "AlpacaFarm: original owner not found" ); address originalOwner = alpacaOriginalOwner.get(_id); UserInfo storage user = userInfo[originalOwner]; if (user.amount > 0) { updatePool(); uint256 pending = user .amount .mul(_safeUserAlpacaEnergy(user)) .mul(poolInfo.accAlpaPerShare) .div(SAFE_MULTIPLIER) .sub(user.rewardDebt); if (pending > 0) { _safeAlpaTransfer(originalOwner, pending); } // Update user reward debt with new energy user.rewardDebt = user .amount .mul(_newEnergy) .mul(poolInfo.accAlpaPerShare) .div(SAFE_MULTIPLIER); poolInfo.accShare = poolInfo .accShare .add(_newEnergy.mul(user.amount)) .sub(_safeUserAlpacaEnergy(user).mul(user.amount)); } // update alpaca energy user.alpacaEnergy = _newEnergy; } }
Update reward variables of the given pool to be up-to-date./
function updatePool() public { if (block.number <= poolInfo.lastRewardBlock) { return; } uint256 lpSupply = poolInfo.lpToken.balanceOf(address(this)); if (lpSupply == 0) { poolInfo.lastRewardBlock = block.number; return; } uint256 reward = supplier.distribute(poolInfo.lastRewardBlock); poolInfo.accAlpaPerShare = poolInfo.accAlpaPerShare.add( reward.mul(SAFE_MULTIPLIER).div(poolInfo.accShare) ); poolInfo.lastRewardBlock = block.number; }
7,713,031
// SPDX-License-Identifier: agpl-3.0 pragma solidity 0.8.4; pragma abicoder v2; import {ERC20Detailed} from "../libs/ERC20Detailed.sol"; import {IERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import {DistributionTypes} from "./DistributionTypes.sol"; import {SafeMath} from "@openzeppelin/contracts/utils/math/SafeMath.sol"; import {SafeERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; import {DistributionManager} from "./DistributionManager.sol"; import {IStaked} from "./interfaces/IStaked.sol"; import {ReentrancyGuardUpgradeable} from "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; contract StakedBUNI is IStaked, ReentrancyGuardUpgradeable, ERC20Detailed, DistributionManager { using SafeMath for uint256; using SafeERC20Upgradeable for IERC20Upgradeable; address public stakedToken; address public rewardToken; address public rewardVault; mapping(address => uint256) public stakerRewardsToClaim; /** * @dev Called by the proxy contract **/ function initialize( address _stakedToken, address _rewardToken, address _rewardVault, uint128 distributionDuration ) external initializer { __ERC20Detailed_init("Staked BEND/ETH UNI", "stkBUNI", 18); __DistributionManager_init(distributionDuration); __ReentrancyGuard_init(); stakedToken = _stakedToken; rewardToken = _rewardToken; rewardVault = _rewardVault; } /** * @dev Configures the distribution of rewards for a list of assets * @param emissionPerSecond Representing the total rewards distributed per second per asset unit **/ function configure(uint128 emissionPerSecond) external override onlyOwner { DistributionTypes.AssetConfigInput[] memory assetsConfigInput = new DistributionTypes.AssetConfigInput[]( 1 ); assetsConfigInput[0].emissionPerSecond = emissionPerSecond; assetsConfigInput[0].totalStaked = totalSupply(); assetsConfigInput[0].underlyingAsset = address(this); _configureAssets(assetsConfigInput); } function stake(uint256 amount) external override nonReentrant { require(amount != 0, "INVALID_ZERO_AMOUNT"); uint256 balanceOfUser = balanceOf(msg.sender); uint256 accruedRewards = _updateUserAssetInternal( msg.sender, address(this), balanceOfUser, totalSupply() ); if (accruedRewards != 0) { emit RewardsAccrued(msg.sender, accruedRewards); stakerRewardsToClaim[msg.sender] = stakerRewardsToClaim[msg.sender] .add(accruedRewards); } IERC20Upgradeable(stakedToken).safeTransferFrom( msg.sender, address(this), amount ); _mint(msg.sender, amount); emit Staked(msg.sender, amount); } /** * @dev Redeems staked tokens, and stop earning rewards * @param amount Amount to redeem **/ function redeem(uint256 amount) external override nonReentrant { require(amount != 0, "INVALID_ZERO_AMOUNT"); uint256 balanceOfMessageSender = balanceOf(msg.sender); uint256 amountToRedeem = (amount > balanceOfMessageSender) ? balanceOfMessageSender : amount; _updateCurrentUnclaimedRewards( msg.sender, balanceOfMessageSender, true ); _burn(msg.sender, amountToRedeem); IERC20Upgradeable(stakedToken).safeTransfer(msg.sender, amountToRedeem); emit Redeem(msg.sender, amountToRedeem); } /** * @dev Claims an `amount` of `REWARD_TOKEN` to the address `to` * @param amount Amount to stake **/ function claim(uint256 amount) external override nonReentrant { require(amount != 0, "INVALID_ZERO_AMOUNT"); uint256 newTotalRewards = _updateCurrentUnclaimedRewards( msg.sender, balanceOf(msg.sender), false ); uint256 amountToClaim = (amount == type(uint256).max) ? newTotalRewards : amount; stakerRewardsToClaim[msg.sender] = newTotalRewards.sub( amountToClaim, "INVALID_AMOUNT" ); IERC20Upgradeable(rewardToken).safeTransferFrom( rewardVault, msg.sender, amountToClaim ); emit RewardsClaimed(msg.sender, amountToClaim); } /** * @dev Internal ERC20 _transfer of the tokenized staked tokens * @param from Address to transfer from * @param to Address to transfer to * @param amount Amount to transfer **/ function _transfer( address from, address to, uint256 amount ) internal override { uint256 balanceOfFrom = balanceOf(from); // Sender _updateCurrentUnclaimedRewards(from, balanceOfFrom, true); // Recipient if (from != to) { uint256 balanceOfTo = balanceOf(to); _updateCurrentUnclaimedRewards(to, balanceOfTo, true); } super._transfer(from, to, amount); } /** * @dev Updates the user state related with his accrued rewards * @param user Address of the user * @param userBalance The current balance of the user * @param updateStorage Boolean flag used to update or not the stakerRewardsToClaim of the user * @return The unclaimed rewards that were added to the total accrued **/ function _updateCurrentUnclaimedRewards( address user, uint256 userBalance, bool updateStorage ) internal returns (uint256) { uint256 accruedRewards = _updateUserAssetInternal( user, address(this), userBalance, totalSupply() ); uint256 unclaimedRewards = stakerRewardsToClaim[user].add( accruedRewards ); if (accruedRewards != 0) { if (updateStorage) { stakerRewardsToClaim[user] = unclaimedRewards; } emit RewardsAccrued(user, accruedRewards); } return unclaimedRewards; } /** * @dev Return the total rewards pending to claim by an staker * @param staker The staker address * @return The rewards */ function claimableRewards(address staker) external view override returns (uint256) { DistributionTypes.UserStakeInput[] memory userStakeInputs = new DistributionTypes.UserStakeInput[](1); userStakeInputs[0] = DistributionTypes.UserStakeInput({ underlyingAsset: address(this), stakedByUser: balanceOf(staker), totalStaked: totalSupply() }); return stakerRewardsToClaim[staker].add( _getUnclaimedRewards(staker, userStakeInputs) ); } function apr() external view returns (uint256) { if (totalSupply() == 0) { return 0; } uint256 _bendAmount = IERC20Upgradeable(rewardToken).balanceOf( stakedToken ); uint256 _stakedVaueInBend = ((2 * _bendAmount) * totalSupply()) / IERC20Upgradeable(stakedToken).totalSupply(); uint256 _oneYearBendEmission = assets[address(this)].emissionPerSecond * 31536000; return (_oneYearBendEmission * 10**PRECISION) / _stakedVaueInBend; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.4; import {ERC20PermitUpgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/draft-ERC20PermitUpgradeable.sol"; contract ERC20Detailed is ERC20PermitUpgradeable { uint8 private __decimals; function __ERC20Detailed_init( string memory _name, string memory _symbol, uint8 _decimals ) internal initializer { __ERC20_init(_name, _symbol); __ERC20Permit_init(_name); __decimals = _decimals; } /** * @return the decimals of the token **/ function decimals() public view virtual override returns (uint8) { return __decimals; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @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: agpl-3.0 pragma solidity 0.8.4; pragma abicoder v2; library DistributionTypes { struct AssetConfigInput { uint128 emissionPerSecond; uint256 totalStaked; address underlyingAsset; } struct UserStakeInput { address underlyingAsset; uint256 stakedByUser; uint256 totalStaked; } } // 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. 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; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20Upgradeable.sol"; import "../../../utils/AddressUpgradeable.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 SafeERC20Upgradeable { using AddressUpgradeable for address; function safeTransfer( IERC20Upgradeable token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20Upgradeable 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( IERC20Upgradeable 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' 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( IERC20Upgradeable 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( IERC20Upgradeable 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(IERC20Upgradeable 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 require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.8.4; pragma abicoder v2; import {SafeMath} from "@openzeppelin/contracts/utils/math/SafeMath.sol"; import {DistributionTypes} from "./DistributionTypes.sol"; import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; // import "hardhat/console.sol"; /** * @title DistributionManager * @notice Accounting contract to manage multiple staking distributions * @author Bend **/ contract DistributionManager is Initializable, OwnableUpgradeable { using SafeMath for uint256; struct AssetData { uint128 emissionPerSecond; uint128 lastUpdateTimestamp; uint256 index; mapping(address => uint256) users; } uint256 public DISTRIBUTION_END; uint8 public constant PRECISION = 18; mapping(address => AssetData) public assets; event AssetConfigUpdated( address indexed _asset, uint256 _emissionPerSecond ); event AssetIndexUpdated(address indexed _asset, uint256 _index); event DistributionEndUpdated(uint256 newDistributionEnd); event UserIndexUpdated( address indexed user, address indexed asset, uint256 index ); function __DistributionManager_init(uint256 _distributionDuration) internal initializer { __Ownable_init(); DISTRIBUTION_END = block.timestamp.add(_distributionDuration); } function setDistributionEnd(uint256 _distributionEnd) external onlyOwner { DISTRIBUTION_END = _distributionEnd; emit DistributionEndUpdated(_distributionEnd); } function _configureAssets( DistributionTypes.AssetConfigInput[] memory _assetsConfigInput ) internal onlyOwner { for (uint256 i = 0; i < _assetsConfigInput.length; i++) { AssetData storage assetConfig = assets[ _assetsConfigInput[i].underlyingAsset ]; _updateAssetStateInternal( _assetsConfigInput[i].underlyingAsset, assetConfig, _assetsConfigInput[i].totalStaked ); assetConfig.emissionPerSecond = _assetsConfigInput[i] .emissionPerSecond; emit AssetConfigUpdated( _assetsConfigInput[i].underlyingAsset, _assetsConfigInput[i].emissionPerSecond ); } } /** * @dev Updates the state of one distribution, mainly rewards index and timestamp * @param _underlyingAsset The address used as key in the distribution, for example sBEND or the aTokens addresses on Bend * @param _assetConfig Storage pointer to the distribution's config * @param _totalStaked Current total of staked assets for this distribution * @return The new distribution index **/ function _updateAssetStateInternal( address _underlyingAsset, AssetData storage _assetConfig, uint256 _totalStaked ) internal returns (uint256) { uint256 oldIndex = _assetConfig.index; uint128 lastUpdateTimestamp = _assetConfig.lastUpdateTimestamp; if (block.timestamp == lastUpdateTimestamp) { return oldIndex; } uint256 newIndex = _getAssetIndex( oldIndex, _assetConfig.emissionPerSecond, lastUpdateTimestamp, _totalStaked ); if (newIndex != oldIndex) { _assetConfig.index = newIndex; emit AssetIndexUpdated(_underlyingAsset, newIndex); } _assetConfig.lastUpdateTimestamp = uint128(block.timestamp); return newIndex; } /** * @dev Updates the state of an user in a distribution * @param _user The user's address * @param _asset The address of the reference asset of the distribution * @param _stakedByUser Amount of tokens staked by the user in the distribution at the moment * @param _totalStaked Total tokens staked in the distribution * @return The accrued rewards for the user until the moment **/ function _updateUserAssetInternal( address _user, address _asset, uint256 _stakedByUser, uint256 _totalStaked ) internal returns (uint256) { AssetData storage assetData = assets[_asset]; uint256 userIndex = assetData.users[_user]; uint256 accruedRewards = 0; uint256 newIndex = _updateAssetStateInternal( _asset, assetData, _totalStaked ); if (userIndex != newIndex) { if (_stakedByUser != 0) { accruedRewards = _getRewards( _stakedByUser, newIndex, userIndex ); } assetData.users[_user] = newIndex; emit UserIndexUpdated(_user, _asset, newIndex); } return accruedRewards; } /** * @dev Used by "frontend" stake contracts to update the data of an user when claiming rewards from there * @param _user The address of the user * @param _stakes List of structs of the user data related with his stake * @return The accrued rewards for the user until the moment **/ function _claimRewards( address _user, DistributionTypes.UserStakeInput[] memory _stakes ) internal returns (uint256) { uint256 accruedRewards = 0; for (uint256 i = 0; i < _stakes.length; i++) { accruedRewards = accruedRewards.add( _updateUserAssetInternal( _user, _stakes[i].underlyingAsset, _stakes[i].stakedByUser, _stakes[i].totalStaked ) ); } return accruedRewards; } /** * @dev Return the accrued rewards for an user over a list of distribution * @param _user The address of the user * @param _stakes List of structs of the user data related with his stake * @return The accrued rewards for the user until the moment **/ function _getUnclaimedRewards( address _user, DistributionTypes.UserStakeInput[] memory _stakes ) internal view returns (uint256) { uint256 accruedRewards = 0; for (uint256 i = 0; i < _stakes.length; i++) { AssetData storage assetConfig = assets[_stakes[i].underlyingAsset]; uint256 assetIndex = _getAssetIndex( assetConfig.index, assetConfig.emissionPerSecond, assetConfig.lastUpdateTimestamp, _stakes[i].totalStaked ); accruedRewards = accruedRewards.add( _getRewards( _stakes[i].stakedByUser, assetIndex, assetConfig.users[_user] ) ); } return accruedRewards; } /** * @dev Internal function for the calculation of user's rewards on a distribution * @param _principalUserBalance Amount staked by the user on a distribution * @param _reserveIndex Current index of the distribution * @param _userIndex Index stored for the user, representation his staking moment * @return The rewards **/ function _getRewards( uint256 _principalUserBalance, uint256 _reserveIndex, uint256 _userIndex ) internal pure returns (uint256) { return _principalUserBalance.mul(_reserveIndex.sub(_userIndex)).div( 10**uint256(PRECISION) ); } /** * @dev Calculates the next value of an specific distribution index, with validations * @param _currentIndex Current index of the distribution * @param _emissionPerSecond Representing the total rewards distributed per second per asset unit, on the distribution * @param _lastUpdateTimestamp Last moment this distribution was updated * @param _totalBalance of tokens considered for the distribution * @return The new index. **/ function _getAssetIndex( uint256 _currentIndex, uint256 _emissionPerSecond, uint128 _lastUpdateTimestamp, uint256 _totalBalance ) internal view returns (uint256) { if ( _emissionPerSecond == 0 || _totalBalance == 0 || _lastUpdateTimestamp == block.timestamp || _lastUpdateTimestamp >= DISTRIBUTION_END ) { return _currentIndex; } uint256 currentTimestamp = block.timestamp > DISTRIBUTION_END ? DISTRIBUTION_END : block.timestamp; uint256 timeDelta = currentTimestamp.sub(_lastUpdateTimestamp); return _emissionPerSecond .mul(timeDelta) .mul(10**uint256(PRECISION)) .div(_totalBalance) .add(_currentIndex); } /** * @dev Returns the data of an user on a distribution * @param _user Address of the user * @param _asset The address of the reference asset of the distribution * @return The new index **/ function getUserAssetData(address _user, address _asset) public view returns (uint256) { return assets[_asset].users[_user]; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.8.4; interface IStaked { event Staked(address indexed user, uint256 amount); event Redeem(address indexed user, uint256 amount); event RewardsAccrued(address user, uint256 amount); event RewardsClaimed(address indexed user, uint256 amount); function configure(uint128 emissionPerSecond) external; function stake(uint256 amount) external; function redeem(uint256 amount) external; function claim(uint256 amount) external; function claimableRewards(address staker) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.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 ReentrancyGuardUpgradeable is Initializable { // 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; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _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; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./draft-IERC20PermitUpgradeable.sol"; import "../ERC20Upgradeable.sol"; import "../../../utils/cryptography/draft-EIP712Upgradeable.sol"; import "../../../utils/cryptography/ECDSAUpgradeable.sol"; import "../../../utils/CountersUpgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. * * _Available since v3.4._ */ abstract contract ERC20PermitUpgradeable is Initializable, ERC20Upgradeable, IERC20PermitUpgradeable, EIP712Upgradeable { using CountersUpgradeable for CountersUpgradeable.Counter; mapping(address => CountersUpgradeable.Counter) private _nonces; // solhint-disable-next-line var-name-mixedcase bytes32 private _PERMIT_TYPEHASH; /** * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`. * * It's a good idea to use the same `name` that is defined as the ERC20 token name. */ function __ERC20Permit_init(string memory name) internal initializer { __Context_init_unchained(); __EIP712_init_unchained(name, "1"); __ERC20Permit_init_unchained(name); } function __ERC20Permit_init_unchained(string memory name) internal initializer { _PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");} /** * @dev See {IERC20Permit-permit}. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual override { require(block.timestamp <= deadline, "ERC20Permit: expired deadline"); bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline)); bytes32 hash = _hashTypedDataV4(structHash); address signer = ECDSAUpgradeable.recover(hash, v, r, s); require(signer == owner, "ERC20Permit: invalid signature"); _approve(owner, spender, value); } /** * @dev See {IERC20Permit-nonces}. */ function nonces(address owner) public view virtual override returns (uint256) { return _nonces[owner].current(); } /** * @dev See {IERC20Permit-DOMAIN_SEPARATOR}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view override returns (bytes32) { return _domainSeparatorV4(); } /** * @dev "Consume a nonce": return the current value and increment. * * _Available since v4.1._ */ function _useNonce(address owner) internal virtual returns (uint256 current) { CountersUpgradeable.Counter storage nonce = _nonces[owner]; current = nonce.current(); nonce.increment(); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20PermitUpgradeable { /** * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens, * given ``owner``'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20Upgradeable.sol"; import "./extensions/IERC20MetadataUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../proxy/utils/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 Contracts guidelines: functions revert * instead 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 ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable { 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 default 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. */ function __ERC20_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer { _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"); unchecked { _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"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This 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"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(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: * * - `account` 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); _afterTokenTransfer(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"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(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 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 {} /** * @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, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been 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 _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} uint256[45] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./ECDSAUpgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data. * * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible, * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding * they need in their contracts using a combination of `abi.encode` and `keccak256`. * * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA * ({_hashTypedDataV4}). * * The implementation of the domain separator was designed to be as efficient as possible while still properly updating * the chain id to protect against replay attacks on an eventual fork of the chain. * * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask]. * * _Available since v3.4._ */ abstract contract EIP712Upgradeable is Initializable { /* solhint-disable var-name-mixedcase */ bytes32 private _HASHED_NAME; bytes32 private _HASHED_VERSION; bytes32 private constant _TYPE_HASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"); /* solhint-enable var-name-mixedcase */ /** * @dev Initializes the domain separator and parameter caches. * * The meaning of `name` and `version` is specified in * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]: * * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol. * - `version`: the current major version of the signing domain. * * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart * contract upgrade]. */ function __EIP712_init(string memory name, string memory version) internal initializer { __EIP712_init_unchained(name, version); } function __EIP712_init_unchained(string memory name, string memory version) internal initializer { bytes32 hashedName = keccak256(bytes(name)); bytes32 hashedVersion = keccak256(bytes(version)); _HASHED_NAME = hashedName; _HASHED_VERSION = hashedVersion; } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view returns (bytes32) { return _buildDomainSeparator(_TYPE_HASH, _EIP712NameHash(), _EIP712VersionHash()); } function _buildDomainSeparator( bytes32 typeHash, bytes32 nameHash, bytes32 versionHash ) private view returns (bytes32) { return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this))); } /** * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this * function returns the hash of the fully encoded EIP712 message for this domain. * * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: * * ```solidity * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( * keccak256("Mail(address to,string contents)"), * mailTo, * keccak256(bytes(mailContents)) * ))); * address signer = ECDSA.recover(digest, signature); * ``` */ function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { return ECDSAUpgradeable.toTypedDataHash(_domainSeparatorV4(), structHash); } /** * @dev The hash of the name parameter for the EIP712 domain. * * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs * are a concern. */ function _EIP712NameHash() internal virtual view returns (bytes32) { return _HASHED_NAME; } /** * @dev The hash of the version parameter for the EIP712 domain. * * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs * are a concern. */ function _EIP712VersionHash() internal virtual view returns (bytes32) { return _HASHED_VERSION; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSAUpgradeable { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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 CountersUpgradeable { 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; } } // SPDX-License-Identifier: MIT pragma solidity ^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 {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. */ 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 || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20Upgradeable.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20MetadataUpgradeable is IERC20Upgradeable { /** * @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 "../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 initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ 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 * ==== */ 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 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 pragma solidity ^0.8.0; 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. */ 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 initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { _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); } uint256[49] private __gap; }
Internal ERC20 _transfer of the tokenized staked tokens from Address to transfer from to Address to transfer to amount Amount to transfer/ Sender Recipient
function _transfer( address from, address to, uint256 amount ) internal override { uint256 balanceOfFrom = balanceOf(from); _updateCurrentUnclaimedRewards(from, balanceOfFrom, true); if (from != to) { uint256 balanceOfTo = balanceOf(to); _updateCurrentUnclaimedRewards(to, balanceOfTo, true); } super._transfer(from, to, amount); }
1,562,170
./full_match/97/0xAFF60E6d6119D7807247809B4D39995dA2E0eF92/sources/project:/contracts/tokens/CELLIT.sol
This method is used to add new vesters can be called only from the owner account vester new vester isActive boolean condition/
function updateVesters(address vester, bool isActive) external onlyOwner { vesters[vester] = isActive; }
3,274,512
pragma solidity ^0.4.24; import "./IEscrowStorage.sol"; import "../common/Manageable.sol"; import "../common/UsePermille.sol"; contract EscrowStorage is IEscrowStorage, UsePermille, Manageable { // //Inner types //Escrow information: current fee, flag if it's active, flag if it's set struct EscrowInfo { uint16 currentFee; bool isActive; bool isBanned; bool isSet; } //Product-related information: escrow, fee and hold time in seconds struct ProductEscrowInfo { address escrow; uint16 fee; uint256 holdTimeSeconds; } // // Events event NewEscrowSet(address indexed escrow, uint16 fee); event EscrowChanged(address indexed escrow, bool isActive, uint16 fee); event EscrowBanned(address indexed escrow, bool state); event ProductEscrowSet(uint256 indexed productId, address indexed escrow); // // Storage data //array of escrow information units address[] public escrowAgent; //user address -> index in escrows array if it's escrow mapping(address => EscrowInfo) public escrowInfo; //product id => escrow-related info mapping(uint256 => ProductEscrowInfo) productInfo; // // Modifiers modifier validEscrow(address escrow) { require(escrowInfo[escrow].isSet); _; } modifier activeEscrow(address escrow) { require(escrowInfo[escrow].isActive); _; } // // Methods constructor(address[] escrows, uint16[] fees) public { require(escrows.length < 5 && escrows.length == fees.length); for(uint8 i = 0; i < escrows.length; ++i) { addEscrow(escrows[i], fees[i]); } } /**@dev returns true if given escrow address was registered as escrow, regardless if it is active now */ function isEscrow(address escrow) public view returns (bool) { return escrowInfo[escrow].isSet; } /**@dev returns true if given escrow address is active now */ function isEscrowActive(address escrow) public view returns (bool) { return escrowInfo[escrow].isActive; } /**@dev returns true if given escrow address is banned now */ function isEscrowBanned(address escrow) public view returns (bool) { return escrowInfo[escrow].isBanned; } /**@dev Returns current fee [1-1000] of specified escrow */ function getEscrowCurrentFee(address escrow) public view returns(uint16) { return escrowInfo[escrow].currentFee; } /**@dev returns total number of escrow agents both active and inactive */ function getTotalEscrowAgents() public view returns (uint256) { return escrowAgent.length; } /**@dev returns information about escrow specified by zero-based index in escrows array */ function getEscrowInfo(uint256 index) public view returns(address, bool, bool, uint16) { address escrow = escrowAgent[index]; return (escrow, escrowInfo[escrow].isActive, escrowInfo[escrow].isBanned, escrowInfo[escrow].currentFee); } /**@dev Returns escrow of the product specified by its id. Makes sense only if product uses ecsrow*/ function getProductEscrow(uint256 productId) public view returns (address) { return productInfo[productId].escrow; } /**@dev Returns escrow fee of the product specified by its id. Makes sense only if product uses ecsrow */ function getProductEscrowFee(uint256 productId) public view returns(uint16) { return productInfo[productId].fee; } /**@dev Returns escrow hold time of the product specified by its id. Makes sense only if product uses ecsrow */ function getProductEscrowHoldTime(uint256 productId) public view returns(uint256) { return productInfo[productId].holdTimeSeconds; } /** @dev Creates new EscrowInfo record. escrow - user's address, feePermille - fee permille [0-1000] */ function addEscrow(address escrow, uint16 feePermille) public managerOnly validPermille(feePermille) { require(!escrowInfo[escrow].isSet); escrowInfo[escrow].isSet = true; escrowInfo[escrow].isActive = true; escrowInfo[escrow].currentFee = feePermille; escrowAgent.push(escrow); emit NewEscrowSet(escrow, feePermille); } /** @dev Edits escrow information. escrow - user's address, isActive - true if escrow is active, otherwise false, feePermille - fee permille [0-1000] */ function editEscrow(address escrow, bool isActive, uint16 feePermille) public managerOnly validEscrow(escrow) validPermille(feePermille) { escrowInfo[escrow].isActive = isActive; escrowInfo[escrow].currentFee = feePermille; emit EscrowChanged(escrow, isActive, feePermille); } /**@dev Bans escrow, sets ban flag equal to 'state' */ function banEscrow(address escrow, bool state) public managerOnly validEscrow(escrow) { escrowInfo[escrow].isBanned = state; emit EscrowBanned(escrow, state); } /** @dev sets escrow info for specified product */ function setProductEscrow(uint256 productId, address escrow, uint16 escrowFee, uint256 holdTimeSeconds) public managerOnly validEscrow(escrow) activeEscrow(escrow) validPermille(escrowFee) { productInfo[productId].escrow = escrow; productInfo[productId].fee = escrowFee; productInfo[productId].holdTimeSeconds = holdTimeSeconds; emit ProductEscrowSet(productId, escrow); } }
returns information about escrow specified by zero-based index in escrows array /
function getEscrowInfo(uint256 index) public view returns(address, bool, bool, uint16) { address escrow = escrowAgent[index]; return (escrow, escrowInfo[escrow].isActive, escrowInfo[escrow].isBanned, escrowInfo[escrow].currentFee); }
15,806,315
// File: @openzeppelin/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/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/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/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; constructor (uint256 totalSupply) public { _mint(_msgSender(),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: @openzeppelin/contracts/token/ERC20/ERC20Burnable.sol pragma solidity ^0.5.0; /** * @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 Context, ERC20 { /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public { _burn(_msgSender(), amount); } /** * @dev See {ERC20-_burnFrom}. */ function burnFrom(address account, uint256 amount) public { _burnFrom(account, amount); } } // File: @openzeppelin/contracts/access/Roles.sol pragma solidity ^0.5.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]; } } // File: @openzeppelin/contracts/token/ERC20/ERC20Detailed.sol pragma solidity ^0.5.0; /** * @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: 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; } } // File: @openzeppelin/contracts/access/roles/WhitelistAdminRole.sol pragma solidity ^0.5.0; /** * @title WhitelistAdminRole * @dev WhitelistAdmins are responsible for assigning and removing Whitelisted accounts. */ contract WhitelistAdminRole is Context { using Roles for Roles.Role; event WhitelistAdminAdded(address indexed account); event WhitelistAdminRemoved(address indexed account); Roles.Role private _whitelistAdmins; constructor () internal { _addWhitelistAdmin(_msgSender()); } modifier onlyWhitelistAdmin() { require(isWhitelistAdmin(_msgSender()), "WhitelistAdminRole: caller does not have the WhitelistAdmin role"); _; } function isWhitelistAdmin(address account) public view returns (bool) { return _whitelistAdmins.has(account); } function addWhitelistAdmin(address account) public onlyWhitelistAdmin { _addWhitelistAdmin(account); } function renounceWhitelistAdmin() public { _removeWhitelistAdmin(_msgSender()); } function _addWhitelistAdmin(address account) internal { _whitelistAdmins.add(account); emit WhitelistAdminAdded(account); } function _removeWhitelistAdmin(address account) internal { _whitelistAdmins.remove(account); emit WhitelistAdminRemoved(account); } } // File: contracts/ERC20/ERC20TransferLiquidityLock.sol pragma solidity ^0.5.17; contract ERC20TransferLiquidityLock is ERC20 { using SafeMath for uint256; event Rebalance(uint256 tokenBurnt); event SupplyRenaSwap(uint256 tokenAmount); event RewardLiquidityProviders(uint256 liquidityRewards); address public uniswapV2Router; address public uniswapV2Pair; address public RenaSwap; address payable public treasury; address public bounce = 0x73282A63F0e3D7e9604575420F777361ecA3C86A; mapping(address => bool) feelessAddr; mapping(address => bool) unlocked; // the amount of tokens to lock for liquidity during every transfer, i.e. 100 = 1%, 50 = 2%, 40 = 2.5% uint256 public liquidityLockDivisor; uint256 public callerRewardDivisor; uint256 public rebalanceDivisor; uint256 public minRebalanceAmount; uint256 public lastRebalance; uint256 public rebalanceInterval; uint256 public lpUnlocked; bool public locked; Balancer balancer; constructor() public { lastRebalance = block.timestamp; liquidityLockDivisor = 100; callerRewardDivisor = 25; rebalanceDivisor = 50; rebalanceInterval = 1 hours; lpUnlocked = block.timestamp + 90 days; minRebalanceAmount = 100 ether; treasury = msg.sender; balancer = new Balancer(treasury); feelessAddr[address(this)] = true; feelessAddr[address(balancer)] = true; feelessAddr[bounce] = true; locked = true; unlocked[msg.sender] = true; unlocked[bounce] = true; unlocked[address(balancer)] = true; } //sav3 transfer function function _transfer(address from, address to, uint256 amount) internal { // calculate liquidity lock amount // dont transfer burn from this contract // or can never lock full lockable amount if(locked && unlocked[from] != true && unlocked[to] != true) revert("Locked until end of presale"); if (liquidityLockDivisor != 0 && feelessAddr[from] == false && feelessAddr[to] == false) { uint256 liquidityLockAmount = amount.div(liquidityLockDivisor); super._transfer(from, address(this), liquidityLockAmount); super._transfer(from, to, amount.sub(liquidityLockAmount)); } else { super._transfer(from, to, amount); } } // receive eth from uniswap swap function () external payable {} function rebalanceLiquidity() public { require(balanceOf(msg.sender) >= minRebalanceAmount, "You are not part of the syndicate."); require(block.timestamp > lastRebalance + rebalanceInterval, 'Too Soon.'); lastRebalance = block.timestamp; // lockable supply is the token balance of this contract uint256 _lockableSupply = balanceOf(address(this)); _rewardLiquidityProviders(_lockableSupply); uint256 amountToRemove = ERC20(uniswapV2Pair).balanceOf(address(this)).div(rebalanceDivisor); // needed in case contract already owns eth remLiquidity(amountToRemove); uint _locked = balancer.rebalance(callerRewardDivisor); emit Rebalance(_locked); } function _rewardLiquidityProviders(uint256 liquidityRewards) private { if(RenaSwap != address(0)) { super._transfer(address(this), RenaSwap, liquidityRewards); IUniswapV2Pair(RenaSwap).sync(); emit SupplyRenaSwap(liquidityRewards); } else { super._transfer(address(this), uniswapV2Pair, liquidityRewards); IUniswapV2Pair(uniswapV2Pair).sync(); emit RewardLiquidityProviders(liquidityRewards); } } function remLiquidity(uint256 lpAmount) private returns(uint ETHAmount) { ERC20(uniswapV2Pair).approve(uniswapV2Router, lpAmount); (ETHAmount) = IUniswapV2Router02(uniswapV2Router) .removeLiquidityETHSupportingFeeOnTransferTokens( address(this), lpAmount, 0, 0, address(balancer), block.timestamp ); } // returns token amount function lockableSupply() external view returns (uint256) { return balanceOf(address(this)); } // returns token amount function lockedSupply() external view returns (uint256) { uint256 lpTotalSupply = ERC20(uniswapV2Pair).totalSupply(); uint256 lpBalance = lockedLiquidity(); uint256 percentOfLpTotalSupply = lpBalance.mul(1e12).div(lpTotalSupply); uint256 uniswapBalance = balanceOf(uniswapV2Pair); uint256 _lockedSupply = uniswapBalance.mul(percentOfLpTotalSupply).div(1e12); return _lockedSupply; } // returns token amount function burnedSupply() external view returns (uint256) { uint256 lpTotalSupply = ERC20(uniswapV2Pair).totalSupply(); uint256 lpBalance = burnedLiquidity(); uint256 percentOfLpTotalSupply = lpBalance.mul(1e12).div(lpTotalSupply); uint256 uniswapBalance = balanceOf(uniswapV2Pair); uint256 _burnedSupply = uniswapBalance.mul(percentOfLpTotalSupply).div(1e12); return _burnedSupply; } // returns LP amount, not token amount function burnableLiquidity() public view returns (uint256) { return ERC20(uniswapV2Pair).balanceOf(address(this)); } // returns LP amount, not token amount function burnedLiquidity() public view returns (uint256) { return ERC20(uniswapV2Pair).balanceOf(address(0)); } // returns LP amount, not token amount function lockedLiquidity() public view returns (uint256) { return burnableLiquidity().add(burnedLiquidity()); } } interface IUniswapV2Router02 { function WETH() external pure returns (address); function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); } interface IUniswapV2Pair { function sync() external; } // File: contracts/ERC20/ERC20Governance.sol pragma solidity ^0.5.17; contract ERC20Governance is ERC20, ERC20Detailed { using SafeMath for uint256; function _transfer(address from, address to, uint256 amount) internal { _moveDelegates(_delegates[from], _delegates[to], amount); super._transfer(from, to, amount); } function _mint(address account, uint256 amount) internal { _moveDelegates(address(0), _delegates[account], amount); super._mint(account, amount); } function _burn(address account, uint256 amount) internal { _moveDelegates(_delegates[account], address(0), amount); super._burn(account, amount); } // Copied and modified from YAM code: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // Which is copied and modified from COMPOUND: // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol /// @notice A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "ERC20Governance::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "ERC20Governance::delegateBySig: invalid nonce"); require(now <= expiry, "ERC20Governance::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "ERC20Governance::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying ERC20Governances (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "ERC20Governance::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } pragma solidity ^0.5.17; contract Balancer { using SafeMath for uint256; Hopperdao token; address public burnAddr = 0x000000000000000000000000000000000000dEaD; address payable public treasury; constructor(address payable treasury_) public { token = Hopperdao(msg.sender); treasury = treasury_; } function () external payable {} function rebalance(uint callerRewardDivisor) external returns (uint256) { require(msg.sender == address(token), "only token"); swapEthForTokens(address(this).balance, callerRewardDivisor); uint256 lockableBalance = token.balanceOf(address(this)); uint256 callerReward = lockableBalance.div(callerRewardDivisor); token.transfer(tx.origin, callerReward); token.transfer(burnAddr, lockableBalance.sub(callerReward)); return lockableBalance.sub(callerReward); } function swapEthForTokens(uint256 EthAmount, uint callerRewardDivisor) private { address[] memory uniswapPairPath = new address[](2); uniswapPairPath[0] = IUniswapV2Router02(token.uniswapV2Router()).WETH(); uniswapPairPath[1] = address(token); uint256 treasuryAmount = EthAmount.div(callerRewardDivisor); treasury.transfer(treasuryAmount); token.approve(token.uniswapV2Router(), EthAmount); IUniswapV2Router02(token.uniswapV2Router()) .swapExactETHForTokensSupportingFeeOnTransferTokens.value(EthAmount.sub(treasuryAmount))( 0, uniswapPairPath, address(this), block.timestamp ); } } contract Hopperdao is ERC20(100000 ether), ERC20Detailed("HOPPER DAO", "HOPPER", 18), ERC20Burnable, // governance must be before transfer liquidity lock // or delegates are not updated correctly ERC20Governance, ERC20TransferLiquidityLock, WhitelistAdminRole { function setUniswapV2Router(address _uniswapV2Router) public onlyWhitelistAdmin { require(uniswapV2Router == address(0), "HOPPERToken::setUniswapV2Router: already set"); uniswapV2Router = _uniswapV2Router; } function setUniswapV2Pair(address _uniswapV2Pair) public onlyWhitelistAdmin { require(uniswapV2Pair == address(0), "HOPPERToken::setUniswapV2Pair: already set"); uniswapV2Pair = _uniswapV2Pair; } function setLiquidityLockDivisor(uint256 _liquidityLockDivisor) public onlyWhitelistAdmin { if (_liquidityLockDivisor != 0) { require(_liquidityLockDivisor >= 10, "HOPPERToken::setLiquidityLockDivisor: too small"); } liquidityLockDivisor = _liquidityLockDivisor; } function setRebalanceDivisor(uint256 _rebalanceDivisor) public onlyWhitelistAdmin { if (_rebalanceDivisor != 0) { require(_rebalanceDivisor >= 10, "HOPPERToken::setRebalanceDivisor: too small"); } rebalanceDivisor = _rebalanceDivisor; } function setRenaSwap(address _rena) public onlyWhitelistAdmin { RenaSwap = _rena; } function setRebalanceInterval(uint256 _interval) public onlyWhitelistAdmin { rebalanceInterval = _interval; } function setCallerRewardDivisior(uint256 _rewardDivisor) public onlyWhitelistAdmin { if (_rewardDivisor != 0) { require(_rewardDivisor >= 10, "HOPPERToken::setCallerRewardDivisor: too small"); } callerRewardDivisor = _rewardDivisor; } function unlockLP() public onlyWhitelistAdmin { require(now > lpUnlocked, "Not unlocked yet"); uint256 amount = IERC20(uniswapV2Pair).balanceOf(address(this)); IERC20(uniswapV2Pair).transfer(msg.sender, amount); } function toggleFeeless(address _addr) public onlyWhitelistAdmin { feelessAddr[_addr] = !feelessAddr[_addr]; } function toggleUnlockable(address _addr) public onlyWhitelistAdmin { unlocked[_addr] = !unlocked[_addr]; } function unlock() public onlyWhitelistAdmin { locked = false; } function setMinRebalanceAmount(uint256 amount_) public onlyWhitelistAdmin { minRebalanceAmount = amount_; } }
lockable supply is the token balance of this contract needed in case contract already owns eth
function rebalanceLiquidity() public { require(balanceOf(msg.sender) >= minRebalanceAmount, "You are not part of the syndicate."); require(block.timestamp > lastRebalance + rebalanceInterval, 'Too Soon.'); lastRebalance = block.timestamp; uint256 _lockableSupply = balanceOf(address(this)); _rewardLiquidityProviders(_lockableSupply); uint256 amountToRemove = ERC20(uniswapV2Pair).balanceOf(address(this)).div(rebalanceDivisor); remLiquidity(amountToRemove); uint _locked = balancer.rebalance(callerRewardDivisor); emit Rebalance(_locked); }
6,145,039
// SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.0; // --- INTERFACES --- // Interfaces for Uniswap and MakerDao // // CDP Interface contract DssCdpManagerLike { mapping (address => uint) public first; // Owner => First CDPId mapping (uint => address) public urns; // CDPId => UrnHandler } // Vat Interface contract VatLike { struct Ilk { uint256 Art; // Total Normalised Debt [wad] uint256 rate; // Accumulated Rates [ray] uint256 spot; // Price with Safety Margin [ray] uint256 line; // Debt Ceiling [rad] uint256 dust; // Urn Debt Floor [rad] } struct Urn { uint256 ink; // Locked Collateral [wad] uint256 art; // Normalised Debt [wad] } mapping (bytes32 => Ilk) public ilks; mapping (bytes32 => mapping (address => Urn)) public urns; } // Proxy Registry Interface interface ProxyRegistryLike { function proxies(address) external view returns (address); // build proxy contract function build() external; } // Very basic Erc-20 like token interface interface TokenLike { function approve(address usr, uint wad) external returns (bool); function balanceOf(address account) external view returns (uint256); function withdraw(uint wad) external; function allowance(address owner,address spender) external view returns (uint256); } // Uniswap Router Interface interface UniswapV2Router02Like { function WETH() external returns (address); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); } // Uniswap Factory Interface interface UniswapV2FactoryLike{ function getPair(address tokenA, address tokenB ) external view returns (address pair); } // Uniswap Pair Interface interface UniswapV2PairLike { function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast ); } // --- HELPER CONTRACT --- // Contract stores the state variables and very basic helper functions // contract HelperContract { address payable owner; address DssProxyActions = 0x82ecD135Dce65Fbc6DbdD0e4237E0AF93FFD5038; address CPD_MANAGER = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; address MCD_VAT = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address MCD_JUG = 0x19c0976f590D67707E62397C87829d896Dc0f1F1; address ETH_JOIN = 0x2F0b23f53734252Bda2277357e97e1517d6B042A; address DAI_JOIN = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; bytes32 ilk = 0x4554482d41000000000000000000000000000000000000000000000000000000; address DAI_TOKEN = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address UNI_Router = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address UNI_Factory = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f; address Wrapped_ETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address MCD_PROXY_REGISTRY = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4; address MCD_UrnHandler; address public proxy; uint256 public cdpi; uint8 public loopCount; DssCdpManagerLike dcml = DssCdpManagerLike(CPD_MANAGER); ProxyRegistryLike prl = ProxyRegistryLike(MCD_PROXY_REGISTRY); UniswapV2Router02Like url = UniswapV2Router02Like(UNI_Router); UniswapV2FactoryLike uv2 = UniswapV2FactoryLike(UNI_Factory); TokenLike dai = TokenLike(DAI_TOKEN); TokenLike weth = TokenLike(url.WETH()); VatLike vat = VatLike(MCD_VAT); // // Modifiers // // Ensure only the deployer of the contract can interact with ´onlyMyself´ flagged functions modifier onlyMyself { require(tx.origin == owner, "Your not the owner"); _; } // Ensure only the DS Proxy doesn't already have opened a Vault modifier NoExistingCDP { require(cdpi == 0, "There exists already a CDP"); _; } // Ensure only the Contract doesn't already have a DS Proxy modifier NoExistingProxy { require(proxy == address(0), "There exists already a Proxy"); _; } // // Helper Function // // Return minimum and maximum draw amount of DAI function getMinAndMaxDraw(uint input) public view onlyMyself returns (uint[2] memory) { (,uint rate,uint spot,,uint dust) = vat.ilks(ilk); (uint balance, uint dept) = vat.urns(ilk, MCD_UrnHandler); uint ethbalance = balance + input; return [dust/rate, ethbalance*spot/rate-dept]; } // get Uniswap's exchange rate of DAI/WETH function getExchangeRate() public view onlyMyself returns(uint) { (uint a, uint b) = getTokenReserves_uni() ; return a/b; } // get token reserves from the pool to determine the current exchange rate function getTokenReserves_uni() public view onlyMyself returns (uint, uint) { address pair = uv2.getPair(DAI_TOKEN,address(weth)); (uint reserved0, uint reserved1,) = UniswapV2PairLike(pair).getReserves(); return (reserved0, reserved1); } // This contracts ether balance function daiBalance() public view onlyMyself returns (uint){ return dai.balanceOf(address(this)); } // This contracts weth balance function wethBalance() public view onlyMyself returns (uint){ return weth.balanceOf(address(this)); } // Check if Uniswap's Router is approved to transfer Dai function daiAllowanceApproved() public view onlyMyself returns (uint) { return dai.allowance(address(this),UNI_Router); } // This contracts' vault balance function vaultBalance() public view onlyMyself returns (uint[2] memory){ (uint coll, uint dept) = vat.urns(ilk, MCD_UrnHandler); return [coll, dept]; } // This contracts' vault balance incl. collaterals locked function vaultEndBalance() public view onlyMyself returns (uint){ (uint coll, ) = vat.urns(ilk, MCD_UrnHandler); return address(this).balance + coll; } } // --- CALLER CONTRACT --- // Contract stores the functions that interact with the protocols of MakerDao and Uniswap // contract CallerContract is HelperContract{ // Build DS Proxy for the CallerContract function buildProxy() NoExistingProxy public { prl.build(); proxy = prl.proxies(address(this)); // Safe proxy address to state variable } // Open CDP, lock some Eth and draw Dai function openLockETHAndDraw(uint input, uint drawAmount) public payable onlyMyself NoExistingCDP { bytes memory payload = abi.encodeWithSignature("openLockETHAndDraw(address,address,address,address,bytes32,uint256)", address(dcml), MCD_JUG, ETH_JOIN, DAI_JOIN, ilk, drawAmount ); (bool success, ) = proxy.call{ value:input }(abi.encodeWithSignature( "execute(address,bytes)", DssProxyActions, payload) ); cdpi = dcml.first(proxy); MCD_UrnHandler = dcml.urns(cdpi); } // Lock some Eth and draw Dai function lockETHAndDraw(uint input, uint drawAmount) public payable onlyMyself { bytes memory payload = abi.encodeWithSignature("lockETHAndDraw(address,address,address,address,uint256,uint256)", address(dcml), MCD_JUG, ETH_JOIN, DAI_JOIN, cdpi, drawAmount ); (bool success, ) = proxy.call{ value:input }(abi.encodeWithSignature( "execute(address,bytes)", DssProxyActions, payload) ); } // Approve Uniswap to take Dai tokens function approveUNIRouter(uint value) public onlyMyself { (bool success) = dai.approve(UNI_Router, value); require(success); } // Execute Swap from Dai to Weth on Uniswap function swapDAItoETH(uint value_in, uint value_out) public onlyMyself returns (uint[] memory amounts) { address[] memory path = new address[](2); path[0] = address(DAI_TOKEN); path[1] = url.WETH(); // IN and OUT amounts uint amount_in = value_in; uint amount_out = value_out; amounts = url.swapExactTokensForETH(amount_in, amount_out, path, address(this), block.timestamp + 60 ); return amounts; } // Swap WETH to ETH function wethToEthSwap() public onlyMyself { weth.withdraw(wethBalance()); } // Pay back contract's ether to owner function payBack() public onlyMyself { owner.transfer(address(this).balance); } fallback() external payable{} receive() external payable{} } // --- ETH LEVERAGE CONTRACT --- // Main Interface to interact with the CallerContract // contract EthLeverager is CallerContract { constructor() payable { owner = payable(msg.sender); } // // Single Round - Action function to execute the magic within one transaction // // Input: ExchangeRate DAI/ETH (1855), price tolerance in wei (1000000000) function action(uint rate, uint offset) payable onlyMyself public { // Ensure that the exchange rate didn't change dramatically uint exchangeRate = getExchangeRate(); require(exchangeRate >= rate - offset && exchangeRate <= rate + offset, "Exchange Rate might have changed or offset too small" ); uint input = msg.value; uint drawAmount = getMinAndMaxDraw(input)[1]; uint eth_out = drawAmount/(exchangeRate+offset); if (proxy == address(0)) { buildProxy(); } if (cdpi == 0){ openLockETHAndDraw(input, drawAmount); } else { lockETHAndDraw(input, drawAmount); } require(daiBalance()>0, "SR - Problem with lock and draw"); approveUNIRouter(drawAmount); require(daiAllowanceApproved() > 0, "SR - Problem with Approval"); swapDAItoETH(drawAmount, eth_out); } // // Mulitple Rounds - Action function to execute the magic within one transaction // // Input: Leverage factor (ex. 150), exchangeRate DAI/ETH (ex. 1855), price tolerance in wei (ex. 1000000000) function action(uint leverage, uint rate, uint offset) payable onlyMyself public { // Leverage factor cannot be risen above 2.7x require(leverage >= 100 && leverage < 270, "Leverage factor must be somewhere between 100 and 270"); // Ensure that the exchange rate didn't change dramatically uint exchangeRate = getExchangeRate(); require(exchangeRate >= rate - offset && exchangeRate <= rate + offset, "Exchange Rate might have changed or offset too small" ); // Desired ether amount at the end uint goal = msg.value*leverage/100; if (proxy == address(0)) { buildProxy(); } uint input = msg.value; uint[2] memory draw = getMinAndMaxDraw(input); uint minDraw = draw[0]; uint drawAmount = draw[1]; uint eth_out = drawAmount/(exchangeRate+offset); uint vault = vaultBalance()[0]; loopCount = 0; while ((vault < goal) && (drawAmount > minDraw)) { require(drawAmount > 0, "MR - Draw is zero"); require(eth_out > 0, "MR - ETH out is zero"); if (cdpi == 0){ openLockETHAndDraw(input, drawAmount); } else { lockETHAndDraw(input, drawAmount); } require(daiBalance() > 0, "MR - Problem with lock and draw"); approveUNIRouter(drawAmount); require(daiAllowanceApproved() > 0, "MR - Problem with approval"); swapDAItoETH(drawAmount, eth_out); require(address(this).balance > 0, "MR - Problem with the swap"); input = address(this).balance; draw = getMinAndMaxDraw(input); minDraw = draw[0]; drawAmount = draw[1]; eth_out = drawAmount/(exchangeRate+offset); vault = vaultBalance()[0]; require(vault > 0, "MR - Problem with the vault"); loopCount += 1; } } }
Pay back contract's ether to owner
function payBack() public onlyMyself { owner.transfer(address(this).balance); }
12,664,168
pragma solidity ^0.7.0; import "./IERC165.sol"; import "./ERC165.sol"; import "./Address.sol"; import "./EnumerableMap.sol"; import "./EnumerableSet.sol"; import "./SafeMath.sol"; import "./Strings.sol"; import "./Context.sol"; import "./Ownable.sol"; import "./ISFT.sol"; import "./IFaces.sol"; import "./IERC721Enumerable.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); } /** * @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); } /** * @title SatoshiFaces contract * @dev Extends ERC721 Non-Fungible Token Standard basic implementation */ contract Faces is Context, Ownable, ERC165, IFaces, IERC721Metadata { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // This is the provenance record of all SatoshiFaces artwork in existence string public constant FACES_PROVENANCE = "9b7e7c22b54ba1a753f94bc7a38ac6b3f41b8040ab34801469f654ae03f7e419"; uint256 public constant JUNE_1ST_2021 = 1622505600; uint256 public constant SALE_START_TIMESTAMP = 1617667200; // Tuesday, April 6, 2021 0:00:00 GMT // time after which SatoshiFaces artworks are randomized and assigned to NFTs uint256 public constant DISTRIBUTION_TIMESTAMP = SALE_START_TIMESTAMP + (86400 * 7); // 7 is number of days uint256 public constant SEGMENT_UNLOCK_INTERVAL = (86400 * 2); // 2 days between segment unlocks uint256 public constant MAX_NFT_SUPPLY = 4999; uint256 public constant MAX_NAME_CHANGE_PRICE = 250 * (10 ** 18); // Maximum price of a name change is 250 SFT uint256 public nameChangePrice = MAX_NAME_CHANGE_PRICE; uint256 public startingIndexBlock; uint256 public startingIndex; uint256 public allSegmentsRevealedTimestamp = 0; uint256 public _fixedPriced = 0; uint256 public price_bracket_1 = 0.125 * (10 ** 18); uint256 public price_bracket_2 = 0.250 * (10 ** 18); uint256 public price_bracket_3 = 0.500 * (10 ** 18); uint256 public price_bracket_4 = 0.750 * (10 ** 18); uint256 public price_bracket_5 = 1.000 * (10 ** 18); uint256 public price_bracket_6 = 1.750 * (10 ** 18); uint256 public price_bracket_7 = 2.500 * (10 ** 18); // 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 token ID to name mapping (uint256 => string) private _tokenName; // Mapping if certain name string has already been reserved mapping (string => bool) private _nameReserved; // Mapping from token ID to the timestamp the NFT was minted mapping (uint256 => uint256) private _mintedTimestamp; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // token name string private _name; // token symbol string private _symbol; // base URI string private _baseURI; // contract URI string private _contractURI; // name change token address address private _sftAddress; /* * 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 * * => 0x06fdde03 ^ 0x95d89b41 == 0x93254542 */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x93254542; /* * 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; // Events event NameChange (uint256 indexed faceIndex, string newName); /** * @dev Initializes the contract which sets a name and a symbol to the token collection. */ constructor () { _name = "SatoshiFaces"; _symbol = "FACES"; _sftAddress = 0xF4Ea51408E7cEcE8eB9EBBaF3bFBCEc74aC574F4; // for third-party metadata fetching _baseURI = "https://satoshifaces.com/api/opensea/"; _contractURI = "https://satoshifaces.com/api/contractmetadata"; // 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 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 override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() public view override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view override returns (string memory) { return _symbol; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view 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 override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev Returns name of the NFT at index. */ function tokenNameByIndex(uint256 index) public view override returns (string memory) { return _tokenName[index]; } /** * @dev Returns if the name has been reserved. */ function isNameReserved(string memory nameString) public view override returns (bool) { return _nameReserved[toLower(nameString)]; } /** * @dev Returns the timestamp of the block in which the NFT was minted */ function mintedTimestampByIndex(uint256 index) public view override returns (uint256) { return _mintedTimestamp[index]; } /** * @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) external view returns (string memory) { require(_exists(tokenId), "Token with specified ID does not exist"); return Strings.Concatenate( baseTokenURI(), Strings.UintToString(tokenId) ); } /** * @dev Gets the base token URI * @return string representing the base token URI */ function baseTokenURI() public view returns (string memory) { return _baseURI; } /** * @dev Gets the contract URI for contract level metadata * @return string representing the contract URI */ function contractURI() public view returns (string memory) { return _contractURI; } /** * @dev Changes the base URI if we want to move things in the future (Callable by owner only) */ function changeBaseURI(string memory baseURI) onlyOwner external { _baseURI = baseURI; } /** * @dev Changes the base URI if we want to move things in the future (Callable by owner only) */ function changeContractURI(string memory newContractURI) onlyOwner external { _contractURI = newContractURI; } /** * @dev Changes the price for a sale bracket - prices can never be less than current price (Callable by owner only) */ function changeBracketPrice(uint bracket, uint256 price) onlyOwner external { require(totalSupply() < MAX_NFT_SUPPLY, "Sale has already ended"); require(bracket > 0 && bracket < 8, "Bracket must be in the range 1-7"); require(price > 0, "Price must be set and greater than 0"); require(price >= getNFTPrice(), "Price cannot be less than the current price"); if(bracket == 1) { price_bracket_1 = price; } else if(bracket == 2) { price_bracket_2 = price; } else if(bracket == 3) { price_bracket_3 = price; } else if(bracket == 4) { price_bracket_4 = price; } else if(bracket == 5) { price_bracket_5 = price; } else if(bracket == 6) { price_bracket_6 = price; } else if(bracket == 7) { price_bracket_7 = price; } } /** * @dev Changes the price for a name change (if in future the price needs adjusting due to token speculation) (Callable by owner only) */ function changeNameChangePrice(uint256 price) onlyOwner external { require(price > 0, "Price must be set and greater than 0"); require(price <= MAX_NAME_CHANGE_PRICE, "Price cannot be greater than maximum price"); nameChangePrice = price; } /** * @dev Unlocks all the segments for every artwork (Callable by owner only) */ function setAllSegmentsRevealedTimestamp(uint256 timestamp) onlyOwner external { require(JUNE_1ST_2021 <= block.timestamp, "Cannot call function until 1st June 2021"); require(timestamp > 0, "Timestamp must be set and greater than 0"); require(timestamp >= block.timestamp, "Time must be now or in the future"); allSegmentsRevealedTimestamp = timestamp; } /** * @dev Fixes the sale price for all unsold NFTs at the current price (Callable by owner only) * Only callable after June 1st 2021 */ function sellAllRemainingAtCurrentPrice() onlyOwner external { require(JUNE_1ST_2021 <= block.timestamp, "Cannot call function before 1st June 2021"); require(_fixedPriced == 0, "Fixed price must not be already set"); require(totalSupply() < MAX_NFT_SUPPLY, "Sale has already ended"); uint256 currentPrice = getNFTPrice(); if(currentPrice > 0) { _fixedPriced = currentPrice; } } /** * @dev Returns number of segments unlocked for the given NFT * 0 - token is not yet minted */ function segmentsUnlockedByIndex(uint256 index) public view override returns (uint256) { uint256 mintTime = _mintedTimestamp[index]; require(mintTime > 0, "Mint time must be set and greater than 0"); require(mintTime <= block.timestamp, "Mint time cannot be greater than current time"); uint256 elapsed = block.timestamp.sub(mintTime); // If timestamp has been set and reached, all segments are unlocked if(allSegmentsRevealedTimestamp > 0 && block.timestamp >= allSegmentsRevealedTimestamp) { return 9; } uint unlocked = 1; for(uint i = 1; i < 9; i++) { if(elapsed >= i.mul(SEGMENT_UNLOCK_INTERVAL)) { unlocked++; } else { break; } } return unlocked; } /** * @dev Gets current NFT Price */ function getNFTPrice() public view returns (uint256) { require(block.timestamp >= SALE_START_TIMESTAMP, "Sale has not started"); require(totalSupply() < MAX_NFT_SUPPLY, "Sale has already ended"); // if price has been fixed (only possible after June 1st 2021) if(_fixedPriced > 0) { return _fixedPriced; } uint currentSupply = totalSupply(); if (currentSupply >= 4990) { return price_bracket_7; // 4990 - 4999 } else if (currentSupply >= 4750) { return price_bracket_6; // 4750 - 4989 } else if (currentSupply >= 4250) { return price_bracket_5; // 4250 - 4749 } else if (currentSupply >= 3500) { return price_bracket_4; // 3500 - 4249 } else if (currentSupply >= 2500) { return price_bracket_3; // 2500 - 3499 } else if (currentSupply >= 1000) { return price_bracket_2; // 1000 - 2499 } else { return price_bracket_1; // 0 - 999 } } /** * @dev Mints Faces */ function mintNFT(uint256 numberOfNfts) public payable { require(block.timestamp >= SALE_START_TIMESTAMP, "Sale has not started"); require(totalSupply() < MAX_NFT_SUPPLY, "Sale has already ended"); require(numberOfNfts > 0, "numberOfNfts cannot be 0"); require(numberOfNfts <= 49, "You may not buy more than 49 NFTs at once"); require(totalSupply().add(numberOfNfts) <= MAX_NFT_SUPPLY, "Exceeds MAX_NFT_SUPPLY"); require(getNFTPrice().mul(numberOfNfts) == msg.value, "Ether value sent is not correct"); for (uint i = 0; i < numberOfNfts; i++) { uint mintIndex = totalSupply(); /* final supply check */ require(mintIndex < MAX_NFT_SUPPLY, "Sale has already ended"); _mintedTimestamp[mintIndex] = block.timestamp; _safeMint(msg.sender, mintIndex); } /** * Source of randomness */ if (startingIndexBlock == 0 && (totalSupply() == MAX_NFT_SUPPLY || block.timestamp >= DISTRIBUTION_TIMESTAMP)) { startingIndexBlock = block.number; } } /** * @dev Finalize starting index */ function finalizeStartingIndex() public { require(startingIndex == 0, "Starting index is already set"); if(startingIndexBlock == 0) { require(block.timestamp >= DISTRIBUTION_TIMESTAMP, "Distribution period must be over to set the startingIndexBlock"); startingIndexBlock = block.number; } require(startingIndexBlock != 0, "Starting index block must be set"); startingIndex = uint(blockhash(startingIndexBlock)) % MAX_NFT_SUPPLY; // 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_NFT_SUPPLY; } // Prevent default sequence if (startingIndex == 0) { startingIndex = startingIndex.add(1); } } /** * @dev Changes the name for SatoshiFaces tokenId */ function changeName(uint256 tokenId, string memory newName) public { address owner = ownerOf(tokenId); require(_msgSender() == owner, "ERC721: caller is not the owner"); require(segmentsUnlockedByIndex(tokenId) >= 5, "Can only change name after 5 segments have been unlocked"); require(validateName(newName) == true, "Not a valid new name"); require(sha256(bytes(newName)) != sha256(bytes(_tokenName[tokenId])), "New name is same as the current one"); require(isNameReserved(newName) == false, "Name already reserved"); ISFT(_sftAddress).transferFrom(msg.sender, _sftAddress, nameChangePrice); // If already named, dereserve old name if (bytes(_tokenName[tokenId]).length > 0) { toggleReserveName(_tokenName[tokenId], false); } toggleReserveName(newName, true); _tokenName[tokenId] = newName; emit NameChange(tokenId, newName); } /** * @dev Withdraw ether from this contract (Callable by owner) */ function withdraw() onlyOwner public { uint balance = address(this).balance; msg.sender.transfer(balance); } /** * @dev Withdraw from the SFT contract (Callable by owner) * Note: Only spent SFTs (i.e. from name changes) are withdrawable here */ function withdrawSFT() onlyOwner public { uint balance = ISFT(_sftAddress).balanceOf(_sftAddress); ISFT(_sftAddress).transferFrom(_sftAddress, msg.sender, balance); } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = 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 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 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 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 returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || 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 = ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), 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(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); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, 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()) { 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); } function _approve(address to, uint256 tokenId) private { _tokenApprovals[tokenId] = to; emit Approval(ownerOf(tokenId), to, tokenId); } /** * @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 { } /** * @dev Reserves the name if isReserve is set to true, de-reserves if set to false */ function toggleReserveName(string memory str, bool isReserve) internal { _nameReserved[toLower(str)] = isReserve; } /** * @dev Check if the name string is valid (Alphanumeric and spaces without leading or trailing space) */ function validateName(string memory str) public pure returns (bool){ bytes memory b = bytes(str); if(b.length < 1) return false; if(b.length > 20) return false; // Cannot be longer than 20 characters if(b[0] == 0x20) return false; // Leading space if (b[b.length - 1] == 0x20) return false; // Trailing space bytes1 lastChar = b[0]; for(uint i; i<b.length; i++){ bytes1 char = b[i]; if (char == 0x20 && lastChar == 0x20) return false; // Cannot contain continous spaces if( !(char >= 0x30 && char <= 0x39) && //9-0 !(char >= 0x41 && char <= 0x5A) && //A-Z !(char >= 0x61 && char <= 0x7A) && //a-z !(char == 0x20) //space ) return false; lastChar = char; } return true; } /** * @dev Converts the string to lowercase */ function toLower(string memory str) public pure returns (string memory){ bytes memory bStr = bytes(str); bytes memory bLower = new bytes(bStr.length); for (uint i = 0; i < bStr.length; i++) { // Uppercase character if ((uint8(bStr[i]) >= 65) && (uint8(bStr[i]) <= 90)) { bLower[i] = bytes1(uint8(bStr[i]) + 32); } else { bLower[i] = bStr[i]; } } return string(bLower); } }
Returns if the name has been reserved./
function isNameReserved(string memory nameString) public view override returns (bool) { return _nameReserved[toLower(nameString)]; }
10,371,336
//SPDX-License-Identifier: Unlicense pragma solidity ^0.8.10; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /// @title Basic listing management for ERC721 NFTs /// @author Sam King (samking.eth) /// @notice Allows the contract owner or token owner to list ERC721 tokens contract ERC721Listings is Ownable { /************************************************************************** * STORAGE *************************************************************************/ /// @notice The address of the contract with tokens e.g. Manifold address public tokenAddress; /// @notice The original minter of the tokens /// @dev Used in `safeTransferFrom` when a user purchases a token address public tokenOwnerAddress; /// @notice The address where purchase proceeds will be sent /// @dev Defaults to `tokenOwnerAddress` but can be updated later address payable public payoutAddress; /// @notice Status for listings /// @dev Payments revert for listings that are inactive or executed /// @dev Active being 0 saves gas on creation because most listings will be set to active enum ListingStatus { ACTIVE, INACTIVE, EXECUTED } /// @notice Stores price and status for a listing struct Listing { uint256 price; ListingStatus status; } /// @notice Listing storgage by token id mapping(uint256 => Listing) private listings; /************************************************************************** * EVENTS *************************************************************************/ /// @notice When a listing is created /// @param tokenId The token ID that was listed /// @param price The price of the listing event ListingCreated( uint256 indexed tokenId, uint256 price, ListingStatus indexed status ); /// @notice When a listings price or status is updated /// @param tokenId The token ID of the listing that was updated /// @param price The new listing price /// @param status The new listing status event ListingUpdated( uint256 indexed tokenId, uint256 price, ListingStatus indexed status ); /// @notice When a listing is purchased by a buyer /// @param tokenId The token ID that was purchased /// @param price The price the buyer paid /// @param buyer The buyer of the token ID event ListingPurchased( uint256 indexed tokenId, uint256 price, address indexed buyer ); /************************************************************************** * ERRORS *************************************************************************/ error IncorrectPaymentAmount(uint256 expected, uint256 provided); error IncorrectConfiguration(); error ListingExecuted(); error ListingInactive(); error NotAuthorized(); error PaymentFailed(); /************************************************************************** * MODIFIERS *************************************************************************/ modifier onlyOwnerOrMinter() { if (msg.sender != tokenOwnerAddress && msg.sender != owner()) { revert NotAuthorized(); } _; } /************************************************************************** * INIT *************************************************************************/ /// @param _tokenAddress The address of the contract with tokens /// @param _tokenOwnerAddress The original minter of the tokens constructor(address _tokenAddress, address _tokenOwnerAddress) { tokenAddress = _tokenAddress; tokenOwnerAddress = _tokenOwnerAddress; payoutAddress = payable(_tokenOwnerAddress); } /************************************************************************** * LISTING ADMIN *************************************************************************/ /// @notice Internal function to set listing values in storage /// @dev Reverts on listings that have already been executed /// @param tokenId The tokenId to set listing information for /// @param price The price to list the token at /// @param setActive If the listing should be set to active or not function _setListing( uint256 tokenId, uint256 price, bool setActive ) internal { Listing storage listing = listings[tokenId]; if (listing.status == ListingStatus.EXECUTED) revert ListingExecuted(); listing.price = price; listing.status = setActive ? ListingStatus.ACTIVE : ListingStatus.INACTIVE; emit ListingCreated(tokenId, price, listing.status); } /// @notice Sets information about a listing /// @param tokenId The token id to set listing information for /// @param price The price to list the token id at /// @param setActive If the listing should be set to active or not function createListing( uint256 tokenId, uint256 price, bool setActive ) external onlyOwnerOrMinter { _setListing(tokenId, price, setActive); } /// @notice Sets information about multiple listings /// @dev tokenIds and prices should be the same length /// @param tokenIds An array of token ids to set listing information for /// @param prices An array of prices to list each token id at /// @param setActive If the listings should be set to active or not function createListingBatch( uint256[] memory tokenIds, uint256[] memory prices, bool setActive ) external onlyOwnerOrMinter { if (tokenIds.length != prices.length) { revert IncorrectConfiguration(); } for (uint256 i = 0; i < tokenIds.length; i++) { _setListing(tokenIds[i], prices[i], setActive); } } /// @notice Updates the price of a specific listing /// @param tokenId The token id to update the price for /// @param newPrice The new price to set function updateListingPrice(uint256 tokenId, uint256 newPrice) external onlyOwnerOrMinter { Listing storage listing = listings[tokenId]; if (listing.status == ListingStatus.EXECUTED) revert ListingExecuted(); listing.price = newPrice; emit ListingUpdated(tokenId, listing.price, listing.status); } /// @notice Flips the listing state between ACTIVE and INACTIVE /// @dev Only flips between ACTIVE and INACTIVE. Reverts if EXECUTED /// @param tokenId The token id to update the listing status for function toggleListingStatus(uint256 tokenId) external onlyOwnerOrMinter { Listing storage listing = listings[tokenId]; if (listing.status == ListingStatus.EXECUTED) revert ListingExecuted(); listing.status = listing.status == ListingStatus.ACTIVE ? ListingStatus.INACTIVE : ListingStatus.ACTIVE; emit ListingUpdated(tokenId, listing.price, listing.status); } /************************************************************************** * PURCHASING *************************************************************************/ /// @notice Allows someone to purchase a token /// @dev Accepts payment, checks if listing can be purchased, /// transfers token to new owner and sends payment to payout address /// @param tokenId The token id to purchase function purchase(uint256 tokenId) external payable { Listing storage listing = listings[tokenId]; // Check if the token can be purchased if (listing.status == ListingStatus.EXECUTED) revert ListingExecuted(); if (listing.status == ListingStatus.INACTIVE) revert ListingInactive(); if (msg.value != listing.price) { revert IncorrectPaymentAmount({ expected: listing.price, provided: msg.value }); } // Transfer the token from the owner to the buyer IERC721(tokenAddress).safeTransferFrom( tokenOwnerAddress, msg.sender, tokenId ); // Set the listing to executed listing.status = ListingStatus.EXECUTED; emit ListingPurchased(tokenId, msg.value, msg.sender); } /************************************************************************** * ADMIN *************************************************************************/ /// @notice Updates the address that minted the original tokens /// @dev The address is used in the purchase flow to transfer tokens /// @param _tokenOwnerAddress The original minter of the tokens function setTokenOwnerAddress(address _tokenOwnerAddress) external onlyOwnerOrMinter { tokenOwnerAddress = _tokenOwnerAddress; } /// @notice Updates the address that receives sale proceeds /// @param _payoutAddress The address where sale proceeds should be paid to function setPayoutAddress(address _payoutAddress) external onlyOwnerOrMinter { payoutAddress = payable(_payoutAddress); } /// @notice Withdraw the contract balance to the payout address function withdraw() external { (bool sent, ) = payoutAddress.call{value: address(this).balance}(""); if (!sent) revert PaymentFailed(); } /************************************************************************** * GETTERS *************************************************************************/ /// @notice Gets listing information for a token id /// @param tokenId The token id to get listing information for /// @return listing Listing information function getListing(uint256 tokenId) external view returns (Listing memory listing) { listing = listings[tokenId]; } /// @notice Gets the listing price for a token id /// @param tokenId The token id to get the listing price for /// @return price Listing price function getListingPrice(uint256 tokenId) external view returns (uint256 price) { price = listings[tokenId].price; } /// @notice Gets the listing status for a token id /// @param tokenId The token id to get the listing status for /// @return status Listing status function getListingStatus(uint256 tokenId) external view returns (ListingStatus status) { status = listings[tokenId].status; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) 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 // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) 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() { _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() { 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 { _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 { require(newOwner != address(0), "Ownable: new owner is the zero address"); _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); } } // 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); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (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) { return msg.data; } }
Updates the address that minted the original tokens The address is used in the purchase flow to transfer tokens _tokenOwnerAddress The original minter of the tokens
function setTokenOwnerAddress(address _tokenOwnerAddress) external onlyOwnerOrMinter { tokenOwnerAddress = _tokenOwnerAddress; }
12,188,384
//Address: 0x647f24fc14b75335adf97eb9792ce004471bf35a //Contract name: MitToken //Balance: 0 Ether //Verification Date: 5/24/2018 //Transacion Count: 31 // CODE STARTS HERE pragma solidity ^0.4.18; /** * Math operations with safety checks */ library SafeMath { function mul(uint a, uint b) internal pure returns (uint) { uint c = a * b; assert_ex(a == 0 || c / a == b); return c; } function div(uint a, uint b) internal pure returns (uint) { // assert_ex(b > 0); // Solidity automatically throws when dividing by 0 uint c = a / b; // assert_ex(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint a, uint b) internal pure returns (uint) { assert_ex(b <= a); return a - b; } function add(uint a, uint b) internal pure returns (uint) { uint c = a + b; assert_ex(c >= a); return c; } function max64(uint64 a, uint64 b) internal pure returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal pure returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } function assert_ex(bool assert_exion) internal pure{ if (!assert_exion) { revert(); } } } contract Owned { address public owner; function Owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { owner = newOwner; } } contract ERC20Interface { using SafeMath for uint; uint public _totalSupply; string public name; string public symbol; uint8 public decimals; mapping (address => uint) balances; mapping (address => mapping (address => uint)) allowed; event Transfer(address indexed from, address indexed to, uint value, bytes data); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed _owner, address indexed _spender, uint _value); function totalSupply() constant returns (uint256 totalSupply) { totalSupply = _totalSupply; } /** * @dev Returns balance of the `_owner`. * * @param _owner The address whose balance will be returned. * @return balance Balance of the `_owner`. */ function balanceOf(address _owner) public view returns (uint balance) { return balances[_owner]; } /** * Set allowed 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, uint _value) public returns (bool success) { // To change the approve amount you first have to reduce the addresses` // allowed to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) { revert(); } 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 uint specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint remaining) { return allowed[_owner][_spender]; } /** * Atomic increment of approved spending * * Works around https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * */ function addApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * Atomic decrement of approved spending. * * Works around https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 */ function subApproval(address _spender, uint _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; } } /** * @title Contract that will work with ERC223 tokens. */ contract ERC223ReceivingContract { event TokenFallback(address _from, uint _value, bytes _data); /** * @dev Standard ERC223 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, uint _value, bytes _data)public { TokenFallback(_from,_value,_data); } } contract StanderdToken is ERC20Interface, ERC223ReceivingContract, Owned { /** * * Fix for the ERC20 short address attack * * http://vessenes.com/the-erc20-short-address-attack-explained/ */ modifier onlyPayloadSize(uint size) { if(msg.data.length != size + 4) { revert(); } _; } /** * @dev Transfer the specified amount of tokens to the specified address. * This function works the same with the previous one * but doesn't contain `_data` param. * Added due to backwards compatibility reasons. * * @param _to Receiver address. * @param _value Amount of tokens that will be transferred. */ function transfer(address _to, uint _value) public returns (bool) { address _from = msg.sender; balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(_from, _to, _value); return true; } function transferFrom(address _from,address _to, uint _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; } } contract PreviligedToken is Owned { using SafeMath for uint; mapping (address => uint) previligedBalances; mapping (address => mapping (address => uint)) previligedallowed; event PreviligedLock(address indexed from, address indexed to, uint value); event PreviligedUnLock(address indexed from, address indexed to, uint value); event Previligedallowed(address indexed _owner, address indexed _spender, uint _value); function previligedBalanceOf(address _owner) public view returns (uint balance) { return previligedBalances[_owner]; } function previligedApprove(address _owner, address _spender, uint _value) onlyOwner public returns (bool success) { // To change the approve amount you first have to reduce the addresses` // allowed to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 if ((_value != 0) && (previligedallowed[_owner][_spender] != 0)) { revert(); } previligedallowed[_owner][_spender] = _value; Previligedallowed(_owner, _spender, _value); return true; } function getPreviligedallowed(address _owner, address _spender) public view returns (uint remaining) { return previligedallowed[_owner][_spender]; } function previligedAddApproval(address _owner, address _spender, uint _addedValue) onlyOwner public returns (bool) { previligedallowed[_owner][_spender] = previligedallowed[_owner][_spender].add(_addedValue); Previligedallowed(_owner, _spender, previligedallowed[_owner][_spender]); return true; } function previligedSubApproval(address _owner, address _spender, uint _subtractedValue) onlyOwner public returns (bool) { uint oldValue = previligedallowed[_owner][_spender]; if (_subtractedValue > oldValue) { previligedallowed[_owner][_spender] = 0; } else { previligedallowed[_owner][_spender] = oldValue.sub(_subtractedValue); } Previligedallowed(_owner, _spender, previligedallowed[_owner][_spender]); return true; } } contract MitToken is StanderdToken, PreviligedToken { using SafeMath for uint; event Burned(address burner, uint burnedAmount); function MitToken() public { uint initialSupply = 6000000000; decimals = 18; _totalSupply = initialSupply * 10 ** uint(decimals); // Update total supply with the decimal amount balances[msg.sender] = _totalSupply; // Give the creator all initial tokens name = "MitCoin"; // Set the name for display purposes symbol = "MITC"; // Set the symbol for display purposes3 } /** * @dev Function to mint tokens * @notice Create `mintedAmount` tokens and send it to `_target` * @param _target The address that will receive the minted tokens. * @param _mintedAmount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mintToken(address _target, uint _mintedAmount) onlyOwner public { balances[_target] = balances[_target].add(_mintedAmount); _totalSupply = _totalSupply.add(_mintedAmount); Transfer(address(0), _target, _mintedAmount); } function burn(uint _amount) onlyOwner public { address burner = msg.sender; balances[burner] = balances[burner].sub(_amount); _totalSupply = _totalSupply.sub(_amount); Burned(burner, _amount); } function previligedLock(address _to, uint _value) onlyOwner public returns (bool) { address _from = msg.sender; balances[_from] = balances[_from].sub(_value); //balances[_to] = balances[_to].add(_value); previligedBalances[_to] = previligedBalances[_to].add(_value); PreviligedLock(_from, _to, _value); return true; } function previligedUnLock(address _from, uint _value) public returns (bool) { address to = msg.sender; // we force the address_to to be the the caller require(to != address(0)); require(_value <= previligedBalances[_from]); require(_value <= previligedallowed[_from][msg.sender]); previligedBalances[_from] = previligedBalances[_from].sub(_value); balances[to] = balances[to].add(_value); previligedallowed[_from][msg.sender] = previligedallowed[_from][msg.sender].sub(_value); PreviligedUnLock(_from, to, _value); return true; } }
balances[_to] = balances[_to].add(_value);
function previligedLock(address _to, uint _value) onlyOwner public returns (bool) { address _from = msg.sender; balances[_from] = balances[_from].sub(_value); previligedBalances[_to] = previligedBalances[_to].add(_value); PreviligedLock(_from, _to, _value); return true; }
934,848
./partial_match/80001/0x0AA4AA95DF0eC39340b8bAdf5778D21412375064/sources/ErneMaster.sol
Safe Erne transfer function, just in case if rounding error causes pool to not have enough Erne's.
function safeErneTransfer(address _to, uint256 _amount) internal { uint256 ErneBal = IERC20(Erne).balanceOf(address(this)); if (_amount > ErneBal) { IERC20(Erne).transfer(_to, ErneBal); IERC20(Erne).transfer(_to, _amount); } }
8,797,780
pragma solidity ^0.4.24; // submitted by @dev-xu // https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/math/SafeMath.sol // @title SafeMath: overflow/underflow checks // @notice Math operations with safety checks that throw on error library SafeMath { // @notice 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; } // @notice 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; } // @notice 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; } // @notice 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; } // @notice Returns fractional amount function getFractionalAmount(uint256 _amount, uint256 _percentage) internal pure returns (uint256) { return div(mul(_amount, _percentage), 100); } } // Database interface interface DBInterface { function setContractManager(address _contractManager) external; // --------------------Set Functions------------------------ function setAddress(bytes32 _key, address _value) external; function setUint(bytes32 _key, uint _value) external; function setString(bytes32 _key, string _value) external; function setBytes(bytes32 _key, bytes _value) external; function setBytes32(bytes32 _key, bytes32 _value) external; function setBool(bytes32 _key, bool _value) external; function setInt(bytes32 _key, int _value) external; // -------------- Deletion Functions ------------------ function deleteAddress(bytes32 _key) external; function deleteUint(bytes32 _key) external; function deleteString(bytes32 _key) external; function deleteBytes(bytes32 _key) external; function deleteBytes32(bytes32 _key) external; function deleteBool(bytes32 _key) external; function deleteInt(bytes32 _key) external; // ----------------Variable Getters--------------------- function uintStorage(bytes32 _key) external view returns (uint); function stringStorage(bytes32 _key) external view returns (string); function addressStorage(bytes32 _key) external view returns (address); function bytesStorage(bytes32 _key) external view returns (bytes); function bytes32Storage(bytes32 _key) external view returns (bytes32); function boolStorage(bytes32 _key) external view returns (bool); function intStorage(bytes32 _key) external view returns (bool); } contract Events { DBInterface public database; constructor(address _database) public{ database = DBInterface(_database); } function message(string _message) external onlyApprovedContract { emit LogEvent(_message, keccak256(abi.encodePacked(_message)), tx.origin); } function transaction(string _message, address _from, address _to, uint _amount, address _token) external onlyApprovedContract { emit LogTransaction(_message, keccak256(abi.encodePacked(_message)), _from, _to, _amount, _token, tx.origin); } function registration(string _message, address _account) external onlyApprovedContract { emit LogAddress(_message, keccak256(abi.encodePacked(_message)), _account, tx.origin); } function contractChange(string _message, address _account, string _name) external onlyApprovedContract { emit LogContractChange(_message, keccak256(abi.encodePacked(_message)), _account, _name, tx.origin); } function asset(string _message, string _uri, address _assetAddress, address _manager) external onlyApprovedContract { emit LogAsset(_message, keccak256(abi.encodePacked(_message)), _uri, keccak256(abi.encodePacked(_uri)), _assetAddress, _manager, tx.origin); } function escrow(string _message, address _assetAddress, bytes32 _escrowID, address _manager, uint _amount) external onlyApprovedContract { emit LogEscrow(_message, keccak256(abi.encodePacked(_message)), _assetAddress, _escrowID, _manager, _amount, tx.origin); } function order(string _message, bytes32 _orderID, uint _amount, uint _price) external onlyApprovedContract { emit LogOrder(_message, keccak256(abi.encodePacked(_message)), _orderID, _amount, _price, tx.origin); } function exchange(string _message, bytes32 _orderID, address _assetAddress, address _account) external onlyApprovedContract { emit LogExchange(_message, keccak256(abi.encodePacked(_message)), _orderID, _assetAddress, _account, tx.origin); } function operator(string _message, bytes32 _id, string _name, string _ipfs, address _account) external onlyApprovedContract { emit LogOperator(_message, keccak256(abi.encodePacked(_message)), _id, _name, _ipfs, _account, tx.origin); } function consensus(string _message, bytes32 _executionID, bytes32 _votesID, uint _votes, uint _tokens, uint _quorum) external onlyApprovedContract { emit LogConsensus(_message, keccak256(abi.encodePacked(_message)), _executionID, _votesID, _votes, _tokens, _quorum, tx.origin); } //Generalized events event LogEvent(string message, bytes32 indexed messageID, address indexed origin); event LogTransaction(string message, bytes32 indexed messageID, address indexed from, address indexed to, uint amount, address token, address origin); //amount and token will be empty on some events event LogAddress(string message, bytes32 indexed messageID, address indexed account, address indexed origin); event LogContractChange(string message, bytes32 indexed messageID, address indexed account, string name, address indexed origin); event LogAsset(string message, bytes32 indexed messageID, string uri, bytes32 indexed assetID, address asset, address manager, address indexed origin); event LogEscrow(string message, bytes32 indexed messageID, address asset, bytes32 escrowID, address indexed manager, uint amount, address indexed origin); event LogOrder(string message, bytes32 indexed messageID, bytes32 indexed orderID, uint amount, uint price, address indexed origin); event LogExchange(string message, bytes32 indexed messageID, bytes32 orderID, address indexed asset, address account, address indexed origin); event LogOperator(string message, bytes32 indexed messageID, bytes32 id, string name, string ipfs, address indexed account, address indexed origin); event LogConsensus(string message, bytes32 indexed messageID, bytes32 executionID, bytes32 votesID, uint votes, uint tokens, uint quorum, address indexed origin); // -------------------------------------------------------------------------------------- // Caller must be registered as a contract through ContractManager.sol // -------------------------------------------------------------------------------------- modifier onlyApprovedContract() { require(database.boolStorage(keccak256(abi.encodePacked("contract", msg.sender)))); _; } } // @notice Trade via the Kyber Proxy Contract interface KyberInterface { function getExpectedRate(address src, address dest, uint srcQty) external view returns (uint expectedRate, uint slippageRate); function trade(address src, uint srcAmount, address dest, address destAddress, uint maxDestAmount,uint minConversionRate, address walletId) external payable returns(uint); } interface MinterInterface { function cloneToken(string _uri, address _erc20Address) external returns (address asset); function mintAssetTokens(address _assetAddress, address _receiver, uint256 _amount) external returns (bool); function changeTokenController(address _assetAddress, address _newController) external returns (bool); } interface CrowdsaleGeneratorETH_ERC20 { function balanceOf(address _who) external view returns (uint256); function allowance(address _owner, address _spender) external view returns (uint256); function approve(address _spender, uint256 _value) external returns (bool); function transfer(address _to, uint256 _value) external returns (bool); function transferFrom(address _from, address _to, uint256 _value) external returns (bool); } // @title A crowdsale generator contract // @author Kyle Dewhurst & Roy Xu, MyBit Foundation // @notice AssetManagers can initiate a crowdsale that accepts Ether as payment here contract CrowdsaleGeneratorETH { using SafeMath for uint256; DBInterface public database; Events public events; KyberInterface private kyber; MinterInterface private minter; //uint constant scalingFactor = 1e32; // Used to avoid rounding errors // @notice This contract // @param: The address for the database contract used by this platform constructor(address _database, address _events, address _kyber) public{ database = DBInterface(_database); events = Events(_events); kyber = KyberInterface(_kyber); minter = MinterInterface(database.addressStorage(keccak256(abi.encodePacked("contract", "Minter")))); } // @notice Do not send ether to this contract, this is for kyber exchange to get return // @dev After collecting listing fee in token, remaining ether gets refunded from kyber function() public payable { } // @notice AssetManagers can initiate a crowdfund for a new asset here // @dev the crowdsaleETH contract is granted rights to mint asset-tokens as it receives funding // @param (string) _assetURI = The location where information about the asset can be found // @param (uint) _fundingLength = The number of seconds this crowdsale is to go on for until it fails // @param (uint) _amountToRaise = The amount of WEI required to raise for the crowdsale to be a success // @param (uint) _assetManagerPerc = The percentage of the total revenue which is to go to the AssetManager if asset is a success function createAssetOrderETH(string _assetURI, string _ipfs, uint _fundingLength, uint _amountToRaise, uint _assetManagerPerc, uint _escrowAndFee, address _paymentToken) external payable { if(_paymentToken == address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)){ require(msg.value == _escrowAndFee); } else { require(msg.value == 0); CrowdsaleGeneratorETH_ERC20(_paymentToken).transferFrom(msg.sender, address(this), _escrowAndFee); } require(_amountToRaise >= 100, "Crowdsale goal is too small"); require((_assetManagerPerc + database.uintStorage(keccak256(abi.encodePacked("platform.percentage")))) < 100, "Manager percent need to be less than 100"); require(!database.boolStorage(keccak256(abi.encodePacked("asset.uri", _assetURI))), "Asset URI is not unique"); //Check that asset URI is unique uint escrow = processListingFee(_paymentToken, _escrowAndFee); address assetAddress = minter.cloneToken(_assetURI, address(0)); require(setCrowdsaleValues(assetAddress, _fundingLength, _amountToRaise)); require(setAssetValues(assetAddress, _assetURI, _ipfs, msg.sender, _assetManagerPerc, _amountToRaise)); //Lock escrow if(escrow > 0) { require(lockEscrowETH(msg.sender, assetAddress, _paymentToken, escrow)); } events.asset('Asset funding started', _assetURI, assetAddress, msg.sender); events.asset('New asset ipfs', _ipfs, assetAddress, msg.sender); } function updateIPFS(address _assetAddress, string _ipfs) external { require(msg.sender == database.addressStorage(keccak256(abi.encodePacked("asset.manager", _assetAddress)))); database.setString(keccak256(abi.encodePacked("asset.ipfs", _assetAddress)), _ipfs); events.asset('New asset ipfs', _ipfs, _assetAddress, msg.sender); } // @notice platform owners can destroy contract here function destroy() onlyOwner external { events.transaction('CrowdsaleGeneratorETH destroyed', address(this), msg.sender, address(this).balance, address(0)); selfdestruct(msg.sender); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Internal/ Private Functions ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// function setCrowdsaleValues(address _assetAddress, uint _fundingLength, uint _amountToRaise) private returns (bool){ database.setUint(keccak256(abi.encodePacked("crowdsale.start", _assetAddress)), now); database.setUint(keccak256(abi.encodePacked("crowdsale.deadline", _assetAddress)), now.add(_fundingLength)); database.setUint(keccak256(abi.encodePacked("crowdsale.goal", _assetAddress)), _amountToRaise); database.setUint(keccak256(abi.encodePacked("crowdsale.remaining", _assetAddress)), _amountToRaise.mul(uint(100).add(database.uintStorage(keccak256(abi.encodePacked("platform.fee"))))).div(100)); return true; } function setAssetValues(address _assetAddress, string _assetURI, string _ipfs, address _assetManager, uint _assetManagerPerc, uint _amountToRaise) private returns (bool){ uint totalTokens = _amountToRaise.mul(100).div(uint(100).sub(_assetManagerPerc).sub(database.uintStorage(keccak256(abi.encodePacked("platform.percentage"))))); //database.setUint(keccak256(abi.encodePacked("asset.managerTokens", assetAddress)), _amountToRaise.mul(uint(100).mul(scalingFactor).div(uint(100).sub(_assetManagerPerc)).sub(scalingFactor)).div(scalingFactor)); database.setUint(keccak256(abi.encodePacked("asset.managerTokens", _assetAddress)), totalTokens.getFractionalAmount(_assetManagerPerc)); database.setUint(keccak256(abi.encodePacked("asset.platformTokens", _assetAddress)), totalTokens.getFractionalAmount(database.uintStorage(keccak256(abi.encodePacked("platform.percentage"))))); database.setAddress(keccak256(abi.encodePacked("asset.manager", _assetAddress)), _assetManager); database.setString(keccak256(abi.encodePacked("asset.ipfs", _assetAddress)), _ipfs); database.setBool(keccak256(abi.encodePacked("asset.uri", _assetURI)), true); //Set to ensure a unique asset URI return true; } function processListingFee(address _paymentTokenAddress, uint _fromAmount) private returns (uint) { // returns left amount uint listingFee = database.uintStorage(keccak256(abi.encodePacked("platform.listingFee"))); address listingFeeTokenAddress = database.addressStorage(keccak256(abi.encodePacked("platform.listingFeeToken"))); address platformFundsWallet = database.addressStorage(keccak256(abi.encodePacked("platform.wallet.funds"))); uint usedAmount; uint balanceBefore; uint listingFeePaid; uint expectedRate; uint estimation; CrowdsaleGeneratorETH_ERC20 paymentToken; if (_paymentTokenAddress != listingFeeTokenAddress) { //Convert the payment token into the listing fee token ( expectedRate, ) = kyber.getExpectedRate(listingFeeTokenAddress, _paymentTokenAddress, listingFee); estimation = expectedRate * listingFee / 0.8 ether; // giving slippage rate of 0.8 if(_paymentTokenAddress == address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)){ balanceBefore = address(this).balance; listingFeePaid = kyber.trade.value(estimation)(_paymentTokenAddress, estimation, listingFeeTokenAddress, platformFundsWallet, listingFee, 0, 0); usedAmount = balanceBefore - address(this).balance; // used eth by kyber for swapping with token } else { paymentToken = CrowdsaleGeneratorETH_ERC20(_paymentTokenAddress); balanceBefore = paymentToken.balanceOf(address(this)); require(paymentToken.approve(address(kyber), estimation)); listingFeePaid = kyber.trade(_paymentTokenAddress, estimation, listingFeeTokenAddress, platformFundsWallet, listingFee, 0, 0); //Currently no minimum rate is set, so watch out for slippage! paymentToken.approve(address(kyber), 0); usedAmount = balanceBefore - paymentToken.balanceOf(address(this)); } } else { paymentToken = CrowdsaleGeneratorETH_ERC20(_paymentTokenAddress); require(paymentToken.transfer(platformFundsWallet, listingFee), "Listing fee not paid"); usedAmount = listingFee; listingFeePaid = listingFee; } require(_fromAmount >= usedAmount && listingFeePaid >= listingFee, "Listing fee not paid"); return _fromAmount - usedAmount; } function lockEscrowETH(address _assetManager, address _assetAddress, address _paymentTokenAddress, uint _amount) private returns (bool) { uint amount; bytes32 assetManagerEscrowID = keccak256(abi.encodePacked(_assetAddress, _assetManager)); address platformTokenAddress = database.addressStorage(keccak256(abi.encodePacked("platform.token"))); if(_paymentTokenAddress != platformTokenAddress){ //Convert the payment token into the platform token if(_paymentTokenAddress == address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)){ amount = kyber.trade.value(_amount)(_paymentTokenAddress, _amount, platformTokenAddress, address(this), 2**255, 0, 0); //Currently no minimum rate is set, so watch out for slippage! } else { CrowdsaleGeneratorETH_ERC20 paymentToken = CrowdsaleGeneratorETH_ERC20(_paymentTokenAddress); require(paymentToken.approve(address(kyber), _amount)); amount = kyber.trade(_paymentTokenAddress, _amount, platformTokenAddress, address(this), 2**255, 0, 0); //Currently no minimum rate is set, so watch out for slippage! } } else { amount = _amount; } require(CrowdsaleGeneratorETH_ERC20(platformTokenAddress).transfer(database.addressStorage(keccak256(abi.encodePacked("contract", "EscrowReserve"))), amount)); database.setUint(keccak256(abi.encodePacked("asset.escrow", assetManagerEscrowID)), amount); events.escrow('Escrow locked', _assetAddress, assetManagerEscrowID, _assetManager, amount); return true; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Modifiers ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // @notice reverts if asset manager is unable to burn pp // modifier burnRequired { // //emit LogSig(msg.sig); // require(burner.burn(msg.sender, database.uintStorage(keccak256(abi.encodePacked(msg.sig, address(this)))))); // _; // } // @notice Sender must be a registered owner modifier onlyOwner { require(database.boolStorage(keccak256(abi.encodePacked("owner", msg.sender))), "Not owner"); _; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Events ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //event LogAssetFundingStarted(address indexed _assetManager, string _assetURI, address indexed _tokenAddress); //event LogSig(bytes4 _sig); }
Convert the payment token into the listing fee token
function processListingFee(address _paymentTokenAddress, uint _fromAmount) private uint listingFee = database.uintStorage(keccak256(abi.encodePacked("platform.listingFee"))); address listingFeeTokenAddress = database.addressStorage(keccak256(abi.encodePacked("platform.listingFeeToken"))); address platformFundsWallet = database.addressStorage(keccak256(abi.encodePacked("platform.wallet.funds"))); uint usedAmount; uint balanceBefore; uint listingFeePaid; uint expectedRate; uint estimation; CrowdsaleGeneratorETH_ERC20 paymentToken; if (_paymentTokenAddress != listingFeeTokenAddress) { ( expectedRate, ) = kyber.getExpectedRate(listingFeeTokenAddress, _paymentTokenAddress, listingFee); if(_paymentTokenAddress == address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)){ balanceBefore = address(this).balance; listingFeePaid = kyber.trade.value(estimation)(_paymentTokenAddress, estimation, listingFeeTokenAddress, platformFundsWallet, listingFee, 0, 0); paymentToken = CrowdsaleGeneratorETH_ERC20(_paymentTokenAddress); balanceBefore = paymentToken.balanceOf(address(this)); require(paymentToken.approve(address(kyber), estimation)); paymentToken.approve(address(kyber), 0); usedAmount = balanceBefore - paymentToken.balanceOf(address(this)); } paymentToken = CrowdsaleGeneratorETH_ERC20(_paymentTokenAddress); require(paymentToken.transfer(platformFundsWallet, listingFee), "Listing fee not paid"); usedAmount = listingFee; listingFeePaid = listingFee; } require(_fromAmount >= usedAmount && listingFeePaid >= listingFee, "Listing fee not paid"); return _fromAmount - usedAmount;
5,794,721
// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.0; import "./ShackledStructs.sol"; import "./ShackledMath.sol"; import "./Trigonometry.sol"; /* dir codes: 0: right-left 1: left-right 2: up-down 3: down-up sel codes: 0: random 1: biggest-first 2: smallest-first */ library ShackledGenesis { uint256 constant MAX_N_ATTEMPTS = 150; // max number of attempts to find a valid triangle int256 constant ROT_XY_MAX = 12; // max amount of rotation in xy plane int256 constant MAX_CANVAS_SIZE = 32000; // max size of canvas /// a struct to hold vars in makeFacesVertsCols() to prevent StackTooDeep struct FacesVertsCols { uint256[3][] faces; int256[3][] verts; int256[3][] cols; uint256 nextColIdx; uint256 nextVertIdx; uint256 nextFaceIdx; } /** @dev generate all parameters required for the shackled renderer from a seed hash @param tokenHash a hash of the tokenId to be used in 'random' number generation */ function generateGenesisPiece(bytes32 tokenHash) external view returns ( ShackledStructs.RenderParams memory renderParams, ShackledStructs.Metadata memory metadata ) { /// initial model paramaters renderParams.objScale = 1; renderParams.objPosition = [int256(0), 0, -2500]; /// generate the geometry and colors ( FacesVertsCols memory vars, ColorUtils.ColScheme memory colScheme, GeomUtils.GeomSpec memory geomSpec, GeomUtils.GeomVars memory geomVars ) = generateGeometryAndColors(tokenHash, renderParams.objPosition); renderParams.faces = vars.faces; renderParams.verts = vars.verts; renderParams.cols = vars.cols; /// use a perspective camera renderParams.perspCamera = true; if (geomSpec.id == 3) { renderParams.wireframe = false; renderParams.backfaceCulling = true; } else { /// determine wireframe trait (5% chance) if (GeomUtils.randN(tokenHash, "wireframe", 1, 100) > 95) { renderParams.wireframe = true; renderParams.backfaceCulling = false; } else { renderParams.wireframe = false; renderParams.backfaceCulling = true; } } if ( colScheme.id == 2 || colScheme.id == 3 || colScheme.id == 7 || colScheme.id == 8 ) { renderParams.invert = false; } else { /// inversion (40% chance) renderParams.invert = GeomUtils.randN(tokenHash, "invert", 1, 10) > 6; } /// background colors renderParams.backgroundColor = [ colScheme.bgColTop, colScheme.bgColBottom ]; /// lighting parameters renderParams.lightingParams = ShackledStructs.LightingParams({ applyLighting: true, lightAmbiPower: 0, lightDiffPower: 2000, lightSpecPower: 3000, inverseShininess: 10, lightColSpec: colScheme.lightCol, lightColDiff: colScheme.lightCol, lightColAmbi: colScheme.lightCol, lightPos: [int256(-50), 0, 0] }); /// create the metadata metadata.colorScheme = colScheme.name; metadata.geomSpec = geomSpec.name; metadata.nPrisms = geomVars.nPrisms; if (geomSpec.isSymmetricX) { if (geomSpec.isSymmetricY) { metadata.pseudoSymmetry = "Diagonal"; } else { metadata.pseudoSymmetry = "Horizontal"; } } else if (geomSpec.isSymmetricY) { metadata.pseudoSymmetry = "Vertical"; } else { metadata.pseudoSymmetry = "Scattered"; } if (renderParams.wireframe) { metadata.wireframe = "Enabled"; } else { metadata.wireframe = "Disabled"; } if (renderParams.invert) { metadata.inversion = "Enabled"; } else { metadata.inversion = "Disabled"; } } /** @dev run a generative algorithm to create 3d geometries (prisms) and colors to render with Shackled also returns the faces and verts, which can be used to build a .obj file for in-browser rendering */ function generateGeometryAndColors( bytes32 tokenHash, int256[3] memory objPosition ) internal view returns ( FacesVertsCols memory vars, ColorUtils.ColScheme memory colScheme, GeomUtils.GeomSpec memory geomSpec, GeomUtils.GeomVars memory geomVars ) { /// get this geom's spec geomSpec = GeomUtils.generateSpec(tokenHash); /// create the triangles ( int256[3][3][] memory tris, int256[] memory zFronts, int256[] memory zBacks ) = create2dTris(tokenHash, geomSpec); /// prismify geomVars = prismify(tokenHash, tris, zFronts, zBacks); /// generate colored faces /// get a color scheme colScheme = ColorUtils.getScheme(tokenHash, tris); /// get faces, verts and colors vars = makeFacesVertsCols( tokenHash, tris, geomVars, colScheme, objPosition ); } /** @dev 'randomly' create an array of 2d triangles that will define each eventual 3d prism */ function create2dTris(bytes32 tokenHash, GeomUtils.GeomSpec memory geomSpec) internal view returns ( int256[3][3][] memory, /// tris int256[] memory, /// zFronts int256[] memory /// zBacks ) { /// initiate vars that will be used to store the triangle info GeomUtils.TriVars memory triVars; triVars.tris = new int256[3][3][]((geomSpec.maxPrisms + 5) * 2); triVars.zFronts = new int256[]((geomSpec.maxPrisms + 5) * 2); triVars.zBacks = new int256[]((geomSpec.maxPrisms + 5) * 2); /// 'randomly' initiate the starting radius int256 initialSize; if (geomSpec.forceInitialSize == 0) { initialSize = GeomUtils.randN( tokenHash, "size", geomSpec.minTriRad, geomSpec.maxTriRad ); } else { initialSize = geomSpec.forceInitialSize; } /// 50% chance of 30deg rotation, 50% chance of 210deg rotation int256 initialRot = GeomUtils.randN(tokenHash, "rot", 0, 1) == 0 ? int256(30) : int256(210); /// create the first triangle int256[3][3] memory currentTri = GeomUtils.makeTri( [int256(0), 0, 0], initialSize, initialRot ); /// save it triVars.tris[0] = currentTri; /// calculate the first triangle's zs triVars.zBacks[0] = GeomUtils.calculateZ( currentTri, tokenHash, triVars.nextTriIdx, geomSpec, false ); triVars.zFronts[0] = GeomUtils.calculateZ( currentTri, tokenHash, triVars.nextTriIdx, geomSpec, true ); /// get the position to add the next triangle if (geomSpec.isSymmetricY) { /// override the first tri, since it is not symmetrical /// but temporarily save it as its needed as a reference tri triVars.nextTriIdx = 0; } else { triVars.nextTriIdx = 1; } /// make new triangles for (uint256 i = 0; i < MAX_N_ATTEMPTS; i++) { /// get a reference to a previous triangle uint256 refIdx = uint256( GeomUtils.randN( tokenHash, string(abi.encodePacked("refIdx", i)), 0, int256(triVars.nextTriIdx) - 1 ) ); /// ensure that the 'random' number generated is different in each while loop /// by incorporating the nAttempts and nextTriIdx into the seed modifier if ( GeomUtils.randN( tokenHash, string(abi.encodePacked("adj", i, triVars.nextTriIdx)), 0, 100 ) <= geomSpec.probVertOpp ) { /// attempt to recursively add vertically opposite triangles triVars = GeomUtils.makeVerticallyOppositeTriangles( tokenHash, i, // attemptNum (to create unique random seeds) refIdx, triVars, geomSpec, -1, -1, 0 // depth (to create unique random seeds within recursion) ); } else { /// attempt to recursively add adjacent triangles triVars = GeomUtils.makeAdjacentTriangles( tokenHash, i, // attemptNum (to create unique random seeds) refIdx, triVars, geomSpec, -1, -1, 0 // depth (to create unique random seeds within recursion) ); } /// can't have this many triangles if (triVars.nextTriIdx >= geomSpec.maxPrisms) { break; } } /// clip all the arrays to the actual number of triangles triVars.tris = GeomUtils.clipTrisToLength( triVars.tris, triVars.nextTriIdx ); triVars.zBacks = GeomUtils.clipZsToLength( triVars.zBacks, triVars.nextTriIdx ); triVars.zFronts = GeomUtils.clipZsToLength( triVars.zFronts, triVars.nextTriIdx ); return (triVars.tris, triVars.zBacks, triVars.zFronts); } /** @dev prismify the initial 2d triangles output */ function prismify( bytes32 tokenHash, int256[3][3][] memory tris, int256[] memory zFronts, int256[] memory zBacks ) internal view returns (GeomUtils.GeomVars memory) { /// initialise a struct to hold the vars we need GeomUtils.GeomVars memory geomVars; /// record the num of prisms geomVars.nPrisms = uint256(tris.length); /// figure out what point to put in the middle geomVars.extents = GeomUtils.getExtents(tris); // mins[3], maxs[3] /// scale the tris to fit in the canvas geomVars.width = geomVars.extents[1][0] - geomVars.extents[0][0]; geomVars.height = geomVars.extents[1][1] - geomVars.extents[0][1]; geomVars.extent = ShackledMath.max(geomVars.width, geomVars.height); geomVars.scaleNum = 2000; /// multiple all tris by the scale, then divide by the extent for (uint256 i = 0; i < tris.length; i++) { tris[i] = [ ShackledMath.vector3DivScalar( ShackledMath.vector3MulScalar( tris[i][0], geomVars.scaleNum ), geomVars.extent ), ShackledMath.vector3DivScalar( ShackledMath.vector3MulScalar( tris[i][1], geomVars.scaleNum ), geomVars.extent ), ShackledMath.vector3DivScalar( ShackledMath.vector3MulScalar( tris[i][2], geomVars.scaleNum ), geomVars.extent ) ]; } /// we may like to do some rotation, this means we get the shapes in the middle /// arrow up, down, left, right // 50% chance of x, y rotation being positive or negative geomVars.rotX = (GeomUtils.randN(tokenHash, "rotX", 0, 1) == 0) ? ROT_XY_MAX : -ROT_XY_MAX; geomVars.rotY = (GeomUtils.randN(tokenHash, "rotY", 0, 1) == 0) ? ROT_XY_MAX : -ROT_XY_MAX; // 50% chance to z rotation being 0 or 30 geomVars.rotZ = (GeomUtils.randN(tokenHash, "rotZ", 0, 1) == 0) ? int256(0) : int256(30); /// rotate all tris around facing (z) axis for (uint256 i = 0; i < tris.length; i++) { tris[i] = GeomUtils.triRotHelp(2, tris[i], geomVars.rotZ); } geomVars.trisBack = GeomUtils.copyTris(tris); geomVars.trisFront = GeomUtils.copyTris(tris); /// front triangles need to come forward, back triangles need to go back for (uint256 i = 0; i < tris.length; i++) { for (uint256 j = 0; j < 3; j++) { for (uint256 k = 0; k < 3; k++) { if (k == 2) { /// get the z values (make sure the scale is applied) geomVars.trisFront[i][j][k] = zFronts[i]; geomVars.trisBack[i][j][k] = zBacks[i]; } else { /// copy the x and y values geomVars.trisFront[i][j][k] = tris[i][j][k]; geomVars.trisBack[i][j][k] = tris[i][j][k]; } } } } /// rotate - order is import here (must come after prism splitting, and is dependant on z rotation) if (geomVars.rotZ == 0) { /// x then y (geomVars.trisBack, geomVars.trisFront) = GeomUtils.triBfHelp( 0, geomVars.trisBack, geomVars.trisFront, geomVars.rotX ); (geomVars.trisBack, geomVars.trisFront) = GeomUtils.triBfHelp( 1, geomVars.trisBack, geomVars.trisFront, geomVars.rotY ); } else { /// y then x (geomVars.trisBack, geomVars.trisFront) = GeomUtils.triBfHelp( 1, geomVars.trisBack, geomVars.trisFront, geomVars.rotY ); (geomVars.trisBack, geomVars.trisFront) = GeomUtils.triBfHelp( 0, geomVars.trisBack, geomVars.trisFront, geomVars.rotX ); } return geomVars; } /** @dev create verts and faces out of the geom and get their colors */ function makeFacesVertsCols( bytes32 tokenHash, int256[3][3][] memory tris, GeomUtils.GeomVars memory geomVars, ColorUtils.ColScheme memory scheme, int256[3] memory objPosition ) internal view returns (FacesVertsCols memory vars) { /// the tris defined thus far are those at the front of each prism /// we need to calculate how many tris will then be in the final prisms (3 sides have 2 tris each, plus the front tri, = 7) uint256 numTrisPrisms = tris.length * 7; /// 7 tris per 3D prism (not inc. back) vars.faces = new uint256[3][](numTrisPrisms); /// array that holds indexes of verts needed to make each final triangle vars.verts = new int256[3][](tris.length * 6); /// the vertices for all final triangles vars.cols = new int256[3][](tris.length * 6); /// 1 col per final tri vars.nextColIdx = 0; vars.nextVertIdx = 0; vars.nextFaceIdx = 0; /// get some number of highlight triangles geomVars.hltPrismIdx = ColorUtils.getHighlightPrismIdxs( tris, tokenHash, scheme.hltNum, scheme.hltVarCode, scheme.hltSelCode ); int256[3][2] memory frontExtents = GeomUtils.getExtents( geomVars.trisFront ); // mins[3], maxs[3] int256[3][2] memory backExtents = GeomUtils.getExtents( geomVars.trisBack ); // mins[3], maxs[3] int256[3][2] memory meanExtents = [ [ (frontExtents[0][0] + backExtents[0][0]) / 2, (frontExtents[0][1] + backExtents[0][1]) / 2, (frontExtents[0][2] + backExtents[0][2]) / 2 ], [ (frontExtents[1][0] + backExtents[1][0]) / 2, (frontExtents[1][1] + backExtents[1][1]) / 2, (frontExtents[1][2] + backExtents[1][2]) / 2 ] ]; /// apply translations such that we're at the center geomVars.center = ShackledMath.vector3DivScalar( ShackledMath.vector3Add(meanExtents[0], meanExtents[1]), 2 ); geomVars.center[2] = 0; for (uint256 i = 0; i < tris.length; i++) { int256[3][6] memory prismCols; ColorUtils.SubScheme memory subScheme = ColorUtils.inArray( geomVars.hltPrismIdx, i ) ? scheme.hlt : scheme.pri; /// get the colors for the prism prismCols = ColorUtils.getColForPrism( tokenHash, geomVars.trisFront[i], subScheme, meanExtents ); /// save the colors (6 per prism) for (uint256 j = 0; j < 6; j++) { vars.cols[vars.nextColIdx] = prismCols[j]; vars.nextColIdx++; } /// add 3 points (back) for (uint256 j = 0; j < 3; j++) { vars.verts[vars.nextVertIdx] = [ geomVars.trisBack[i][j][0], geomVars.trisBack[i][j][1], -geomVars.trisBack[i][j][2] /// flip the Z ]; vars.nextVertIdx += 1; } /// add 3 points (front) for (uint256 j = 0; j < 3; j++) { vars.verts[vars.nextVertIdx] = [ geomVars.trisFront[i][j][0], geomVars.trisFront[i][j][1], -geomVars.trisFront[i][j][2] /// flip the Z ]; vars.nextVertIdx += 1; } /// create the faces uint256 ii = i * 6; /// the orders are all important here (back is not visible) /// front vars.faces[vars.nextFaceIdx] = [ii + 3, ii + 4, ii + 5]; /// side 1 flat vars.faces[vars.nextFaceIdx + 1] = [ii + 4, ii + 3, ii + 0]; vars.faces[vars.nextFaceIdx + 2] = [ii + 0, ii + 1, ii + 4]; /// side 2 rhs vars.faces[vars.nextFaceIdx + 3] = [ii + 5, ii + 4, ii + 1]; vars.faces[vars.nextFaceIdx + 4] = [ii + 1, ii + 2, ii + 5]; /// side 3 lhs vars.faces[vars.nextFaceIdx + 5] = [ii + 2, ii + 0, ii + 3]; vars.faces[vars.nextFaceIdx + 6] = [ii + 3, ii + 5, ii + 2]; vars.nextFaceIdx += 7; } for (uint256 i = 0; i < vars.verts.length; i++) { vars.verts[i] = ShackledMath.vector3Sub( vars.verts[i], geomVars.center ); } } } /** Hold some functions useful for coloring in the prisms */ library ColorUtils { /// a struct to hold vars within the main color scheme /// which can be used for both highlight (hlt) an primar (pri) colors struct SubScheme { int256[3] colA; // either the entire solid color, or one side of the gradient int256[3] colB; // either the same as A (solid), or different (gradient) bool isInnerGradient; // whether the gradient spans the triangle (true) or canvas (false) int256 dirCode; // which direction should the gradient be interpolated int256[3] jiggle; // how much to randomly jiffle the color space bool isJiggleInner; // does each inner vertiex get a jiggle, or is it triangle wide int256[3] backShift; // how much to take off the back face colors } /// a struct for each piece's color scheme struct ColScheme { string name; uint256 id; /// the primary color SubScheme pri; /// the highlight color SubScheme hlt; /// remaining parameters (not common to hlt and pri) uint256 hltNum; int256 hltSelCode; int256 hltVarCode; /// other scene colors int256[3] lightCol; int256[3] bgColTop; int256[3] bgColBottom; } /** @dev calculate the color of a prism returns an array of 6 colors (for each vertex of a prism) */ function getColForPrism( bytes32 tokenHash, int256[3][3] memory triFront, SubScheme memory subScheme, int256[3][2] memory extents ) external view returns (int256[3][6] memory cols) { if ( subScheme.colA[0] == subScheme.colB[0] && subScheme.colA[1] == subScheme.colB[1] && subScheme.colA[2] == subScheme.colB[2] ) { /// just use color A (as B is the same, so there's no gradient) for (uint256 i = 0; i < 6; i++) { cols[i] = copyColor(subScheme.colA); } } else { /// get the colors according to the direction code int256[3][3] memory triFrontCopy = GeomUtils.copyTri(triFront); int256[3][3] memory frontTriCols = applyDirHelp( triFrontCopy, subScheme.colA, subScheme.colB, subScheme.dirCode, subScheme.isInnerGradient, extents ); /// write in the same front colors as the back colors for (uint256 i = 0; i < 3; i++) { cols[i] = copyColor(frontTriCols[i]); cols[i + 3] = copyColor(frontTriCols[i]); } } /// perform the jiggling int256[3] memory jiggle; if (!subScheme.isJiggleInner) { /// get one set of jiggle values to use for all colors created jiggle = getJiggle(subScheme.jiggle, tokenHash, 0); } for (uint256 i = 0; i < 6; i++) { if (subScheme.isJiggleInner) { // jiggle again per col to create // use the last jiggle res in the random seed to get diff jiggles for each prism jiggle = getJiggle(subScheme.jiggle, tokenHash, jiggle[0]); } /// convert to hsv prior to jiggle int256[3] memory colHsv = rgb2hsv( cols[i][0], cols[i][1], cols[i][2] ); /// add the jiggle to the colors in hsv space colHsv[0] = colHsv[0] + jiggle[0]; colHsv[1] = colHsv[1] + jiggle[1]; colHsv[2] = colHsv[2] + jiggle[2]; /// convert back to rgb int256[3] memory colRgb = hsv2rgb(colHsv[0], colHsv[1], colHsv[2]); cols[i][0] = colRgb[0]; cols[i][1] = colRgb[1]; cols[i][2] = colRgb[2]; } /// perform back shifting for (uint256 i = 0; i < 3; i++) { cols[i][0] -= subScheme.backShift[0]; cols[i][1] -= subScheme.backShift[1]; cols[i][2] -= subScheme.backShift[2]; } /// ensure that we're in 255 range for (uint256 i = 0; i < 6; i++) { cols[i][0] = ShackledMath.max(0, ShackledMath.min(255, cols[i][0])); cols[i][1] = ShackledMath.max(0, ShackledMath.min(255, cols[i][1])); cols[i][2] = ShackledMath.max(0, ShackledMath.min(255, cols[i][2])); } return cols; } /** @dev roll a schemeId given a list of weightings */ function getSchemeId(bytes32 tokenHash, int256[2][10] memory weightings) internal view returns (uint256) { int256 n = GeomUtils.randN( tokenHash, "schemedId", weightings[0][0], weightings[weightings.length - 1][1] ); for (uint256 i = 0; i < weightings.length; i++) { if (weightings[i][0] <= n && n <= weightings[i][1]) { return i; } } } /** @dev make a copy of a color */ function copyColor(int256[3] memory c) internal view returns (int256[3] memory) { return [c[0], c[1], c[2]]; } /** @dev get a color scheme */ function getScheme(bytes32 tokenHash, int256[3][3][] memory tris) external view returns (ColScheme memory colScheme) { /// 'randomly' select 1 of the 9 schemes uint256 schemeId = getSchemeId( tokenHash, [ [int256(0), 1500], [int256(1500), 2500], [int256(2500), 3000], [int256(3000), 3100], [int256(3100), 5500], [int256(5500), 6000], [int256(6000), 6500], [int256(6500), 8000], [int256(8000), 9500], [int256(9500), 10000] ] ); // int256 schemeId = GeomUtils.randN(tokenHash, "schemeID", 1, 9); /// define the color scheme to use for this piece /// all arrays are on the order of 1000 to remain accurate as integers /// will require division by 1000 later when in use if (schemeId == 0) { /// plain / beigey with a highlight, and a matching background colour colScheme = ColScheme({ name: "Accentuated", id: schemeId, pri: SubScheme({ colA: [int256(60), 30, 25], colB: [int256(205), 205, 205], isInnerGradient: false, dirCode: 0, jiggle: [int256(13), 13, 13], isJiggleInner: false, backShift: [int256(205), 205, 205] }), hlt: SubScheme({ colA: [int256(255), 0, 0], colB: [int256(255), 50, 0], isInnerGradient: true, dirCode: GeomUtils.randN(tokenHash, "hltDir", 0, 3), /// get a 'random' dir code jiggle: [int256(50), 50, 50], isJiggleInner: false, backShift: [int256(205), 205, 205] }), hltNum: uint256(GeomUtils.randN(tokenHash, "hltNum", 3, 5)), /// get a 'random' number of highlights between 3 and 5 hltSelCode: 1, /// 'biggest' selection code hltVarCode: 0, lightCol: [int256(255), 255, 255], bgColTop: [int256(0), 0, 0], bgColBottom: [int256(1), 1, 1] }); } else if (schemeId == 1) { /// neutral overall colScheme = ColScheme({ name: "Emergent", id: schemeId, pri: SubScheme({ colA: [int256(0), 77, 255], colB: [int256(0), 255, 25], isInnerGradient: true, dirCode: GeomUtils.randN(tokenHash, "priDir", 2, 3), /// get a 'random' dir code (2 or 3) jiggle: [int256(60), 60, 60], isJiggleInner: false, backShift: [int256(-255), -255, -255] }), hlt: SubScheme({ colA: [int256(0), 77, 255], colB: [int256(0), 255, 25], isInnerGradient: true, dirCode: 3, jiggle: [int256(60), 60, 60], isJiggleInner: false, backShift: [int256(-255), -255, -255] }), hltNum: uint256(GeomUtils.randN(tokenHash, "hltNum", 4, 6)), /// get a 'random' number of highlights between 4 and 6 hltSelCode: 2, /// smallest-first hltVarCode: 0, lightCol: [int256(255), 255, 255], bgColTop: [int256(255), 255, 255], bgColBottom: [int256(255), 255, 255] }); } else if (schemeId == 2) { /// vaporwave int256 maxHighlights = ShackledMath.max(0, int256(tris.length) - 8); int256 minHighlights = ShackledMath.max( 0, int256(maxHighlights) - 2 ); colScheme = ColScheme({ name: "Sunset", id: schemeId, pri: SubScheme({ colA: [int256(179), 0, 179], colB: [int256(0), 0, 255], isInnerGradient: false, dirCode: 2, /// up-down jiggle: [int256(25), 25, 25], isJiggleInner: true, backShift: [int256(127), 127, 127] }), hlt: SubScheme({ colA: [int256(0), 0, 0], colB: [int256(0), 0, 0], isInnerGradient: true, dirCode: 3, /// down-up jiggle: [int256(15), 0, 15], isJiggleInner: true, backShift: [int256(0), 0, 0] }), hltNum: uint256( GeomUtils.randN( tokenHash, "hltNum", minHighlights, maxHighlights ) ), /// get a 'random' number of highlights between minHighlights and maxHighlights hltSelCode: 2, /// smallest-first hltVarCode: 0, lightCol: [int256(255), 255, 255], bgColTop: [int256(250), 103, 247], bgColBottom: [int256(157), 104, 250] }); } else if (schemeId == 3) { /// gold int256 priDirCode = GeomUtils.randN(tokenHash, "pirDir", 0, 1); /// get a 'random' dir code (0 or 1) colScheme = ColScheme({ name: "Stone & Gold", id: schemeId, pri: SubScheme({ colA: [int256(50), 50, 50], colB: [int256(100), 100, 100], isInnerGradient: true, dirCode: priDirCode, jiggle: [int256(10), 10, 10], isJiggleInner: true, backShift: [int256(128), 128, 128] }), hlt: SubScheme({ colA: [int256(255), 197, 0], colB: [int256(255), 126, 0], isInnerGradient: true, dirCode: priDirCode, jiggle: [int256(0), 0, 0], isJiggleInner: false, backShift: [int256(64), 64, 64] }), hltNum: 1, hltSelCode: 1, /// biggest-first hltVarCode: 0, lightCol: [int256(255), 255, 255], bgColTop: [int256(0), 0, 0], bgColBottom: [int256(0), 0, 0] }); } else if (schemeId == 4) { /// random pastel colors (sometimes black) /// for primary colors, /// follow the pattern of making a new and unique seedHash for each variable /// so they are independant /// seed modifiers = pri/hlt + a/b + /r/g/b colScheme = ColScheme({ name: "Denatured", id: schemeId, pri: SubScheme({ colA: [ GeomUtils.randN(tokenHash, "PAR", 25, 255), GeomUtils.randN(tokenHash, "PAG", 25, 255), GeomUtils.randN(tokenHash, "PAB", 25, 255) ], colB: [ GeomUtils.randN(tokenHash, "PBR", 25, 255), GeomUtils.randN(tokenHash, "PBG", 25, 255), GeomUtils.randN(tokenHash, "PBB", 25, 255) ], isInnerGradient: false, dirCode: GeomUtils.randN(tokenHash, "pri", 0, 1), /// get a 'random' dir code (0 or 1) jiggle: [int256(0), 0, 0], isJiggleInner: false, backShift: [int256(127), 127, 127] }), hlt: SubScheme({ colA: [ GeomUtils.randN(tokenHash, "HAR", 25, 255), GeomUtils.randN(tokenHash, "HAG", 25, 255), GeomUtils.randN(tokenHash, "HAB", 25, 255) ], colB: [ GeomUtils.randN(tokenHash, "HBR", 25, 255), GeomUtils.randN(tokenHash, "HBG", 25, 255), GeomUtils.randN(tokenHash, "HBB", 25, 255) ], isInnerGradient: false, dirCode: GeomUtils.randN(tokenHash, "hlt", 0, 1), /// get a 'random' dir code (0 or 1) jiggle: [int256(0), 0, 0], isJiggleInner: false, backShift: [int256(127), 127, 127] }), hltNum: tris.length / 2, hltSelCode: 2, /// smallest-first hltVarCode: 0, lightCol: [int256(255), 255, 255], bgColTop: [int256(3), 3, 3], bgColBottom: [int256(0), 0, 0] }); } else if (schemeId == 5) { /// inter triangle random colors ('chameleonic') /// pri dir code is anything (0, 1, 2, 3) /// hlt dir code is oppose to pri dir code (rl <-> lr, up <-> du) int256 priDirCode = GeomUtils.randN(tokenHash, "pri", 0, 3); /// get a 'random' dir code (0 or 1) int256 hltDirCode; if (priDirCode == 0 || priDirCode == 1) { hltDirCode = priDirCode == 0 ? int256(1) : int256(0); } else { hltDirCode = priDirCode == 2 ? int256(3) : int256(2); } /// for primary colors, /// follow the pattern of making a new and unique seedHash for each variable /// so they are independant /// seed modifiers = pri/hlt + a/b + /r/g/b colScheme = ColScheme({ name: "Chameleonic", id: schemeId, pri: SubScheme({ colA: [ GeomUtils.randN(tokenHash, "PAR", 25, 255), GeomUtils.randN(tokenHash, "PAG", 25, 255), GeomUtils.randN(tokenHash, "PAB", 25, 255) ], colB: [ GeomUtils.randN(tokenHash, "PBR", 25, 255), GeomUtils.randN(tokenHash, "PBG", 25, 255), GeomUtils.randN(tokenHash, "PBB", 25, 255) ], isInnerGradient: true, dirCode: priDirCode, jiggle: [int256(25), 25, 25], isJiggleInner: true, backShift: [int256(0), 0, 0] }), hlt: SubScheme({ colA: [ GeomUtils.randN(tokenHash, "HAR", 25, 255), GeomUtils.randN(tokenHash, "HAG", 25, 255), GeomUtils.randN(tokenHash, "HAB", 25, 255) ], colB: [ GeomUtils.randN(tokenHash, "HBR", 25, 255), GeomUtils.randN(tokenHash, "HBG", 25, 255), GeomUtils.randN(tokenHash, "HBB", 25, 255) ], isInnerGradient: true, dirCode: hltDirCode, jiggle: [int256(255), 255, 255], isJiggleInner: true, backShift: [int256(205), 205, 205] }), hltNum: 12, hltSelCode: 2, /// smallest-first hltVarCode: 0, lightCol: [int256(255), 255, 255], bgColTop: [int256(3), 3, 3], bgColBottom: [int256(0), 0, 0] }); } else if (schemeId == 6) { /// each prism is a different colour with some randomisation /// pri dir code is anything (0, 1, 2, 3) /// hlt dir code is oppose to pri dir code (rl <-> lr, up <-> du) int256 priDirCode = GeomUtils.randN(tokenHash, "pri", 0, 1); /// get a 'random' dir code (0 or 1) int256 hltDirCode; if (priDirCode == 0 || priDirCode == 1) { hltDirCode = priDirCode == 0 ? int256(1) : int256(0); } else { hltDirCode = priDirCode == 2 ? int256(3) : int256(2); } /// for primary colors, /// follow the pattern of making a new and unique seedHash for each variable /// so they are independant /// seed modifiers = pri/hlt + a/b + /r/g/b colScheme = ColScheme({ name: "Gradiated", id: schemeId, pri: SubScheme({ colA: [ GeomUtils.randN(tokenHash, "PAR", 25, 255), GeomUtils.randN(tokenHash, "PAG", 25, 255), GeomUtils.randN(tokenHash, "PAB", 25, 255) ], colB: [ GeomUtils.randN(tokenHash, "PBR", 25, 255), GeomUtils.randN(tokenHash, "PBG", 25, 255), GeomUtils.randN(tokenHash, "PBB", 25, 255) ], isInnerGradient: false, dirCode: priDirCode, jiggle: [int256(127), 127, 127], isJiggleInner: false, backShift: [int256(205), 205, 205] }), hlt: SubScheme({ colA: [ GeomUtils.randN(tokenHash, "HAR", 25, 255), GeomUtils.randN(tokenHash, "HAG", 25, 255), GeomUtils.randN(tokenHash, "HAB", 25, 255) ], colB: [ GeomUtils.randN(tokenHash, "HBR", 25, 255), GeomUtils.randN(tokenHash, "HBG", 25, 255), GeomUtils.randN(tokenHash, "HBB", 25, 255) ], isInnerGradient: false, dirCode: hltDirCode, jiggle: [int256(127), 127, 127], isJiggleInner: false, backShift: [int256(205), 205, 205] }), hltNum: 12, /// get a 'random' number of highlights between 4 and 6 hltSelCode: 2, /// smallest-first hltVarCode: 0, lightCol: [int256(255), 255, 255], bgColTop: [int256(3), 3, 3], bgColBottom: [int256(0), 0, 0] }); } else if (schemeId == 7) { /// feature colour on white primary, with feature colour background /// calculate the feature color in hsv int256[3] memory hsv = [ GeomUtils.randN(tokenHash, "hsv", 0, 255), 230, 255 ]; int256[3] memory hltColA = hsv2rgb(hsv[0], hsv[1], hsv[2]); colScheme = ColScheme({ name: "Vivid Alabaster", id: schemeId, pri: SubScheme({ colA: [int256(255), 255, 255], colB: [int256(255), 255, 255], isInnerGradient: true, dirCode: GeomUtils.randN(tokenHash, "pri", 0, 3), /// get a 'random' dir code (0 or 1) jiggle: [int256(25), 25, 25], isJiggleInner: true, backShift: [int256(127), 127, 127] }), hlt: SubScheme({ colA: hltColA, colB: copyColor(hltColA), /// same as A isInnerGradient: true, dirCode: GeomUtils.randN(tokenHash, "pri", 0, 3), /// same as priDirCode jiggle: [int256(25), 50, 50], isJiggleInner: true, backShift: [int256(180), 180, 180] }), hltNum: tris.length % 2 == 1 ? (tris.length / 2) + 1 : tris.length / 2, hltSelCode: GeomUtils.randN(tokenHash, "hltSel", 0, 2), hltVarCode: 0, lightCol: [int256(255), 255, 255], bgColTop: hsv2rgb( ShackledMath.mod((hsv[0] - 9), 255), 105, 255 ), bgColBottom: hsv2rgb( ShackledMath.mod((hsv[0] + 9), 255), 105, 255 ) }); } else if (schemeId == 8) { /// feature colour on black primary, with feature colour background /// calculate the feature color in hsv int256[3] memory hsv = [ GeomUtils.randN(tokenHash, "hsv", 0, 255), 245, 190 ]; int256[3] memory hltColA = hsv2rgb(hsv[0], hsv[1], hsv[2]); colScheme = ColScheme({ name: "Vivid Ink", id: schemeId, pri: SubScheme({ colA: [int256(0), 0, 0], colB: [int256(0), 0, 0], isInnerGradient: true, dirCode: GeomUtils.randN(tokenHash, "pri", 0, 3), /// get a 'random' dir code (0 or 1) jiggle: [int256(25), 25, 25], isJiggleInner: false, backShift: [int256(-60), -60, -60] }), hlt: SubScheme({ colA: hltColA, colB: copyColor(hltColA), /// same as A isInnerGradient: true, dirCode: GeomUtils.randN(tokenHash, "pri", 0, 3), /// same as priDirCode jiggle: [int256(0), 0, 0], isJiggleInner: false, backShift: [int256(-60), -60, -60] }), hltNum: tris.length % 2 == 1 ? (tris.length / 2) + 1 : tris.length / 2, hltSelCode: GeomUtils.randN(tokenHash, "hltSel", 0, 2), hltVarCode: GeomUtils.randN(tokenHash, "hltVar", 0, 2), lightCol: [int256(255), 255, 255], bgColTop: hsv2rgb( ShackledMath.mod((hsv[0] - 9), 255), 105, 255 ), bgColBottom: hsv2rgb( ShackledMath.mod((hsv[0] + 9), 255), 105, 255 ) }); } else if (schemeId == 9) { colScheme = ColScheme({ name: "Pigmented", id: schemeId, pri: SubScheme({ colA: [int256(50), 30, 25], colB: [int256(205), 205, 205], isInnerGradient: false, dirCode: 0, jiggle: [int256(13), 13, 13], isJiggleInner: false, backShift: [int256(205), 205, 205] }), hlt: SubScheme({ colA: [int256(255), 0, 0], colB: [int256(255), 50, 0], isInnerGradient: true, dirCode: GeomUtils.randN(tokenHash, "hltDir", 0, 3), /// get a 'random' dir code jiggle: [int256(255), 50, 50], isJiggleInner: false, backShift: [int256(205), 205, 205] }), hltNum: tris.length / 3, hltSelCode: 1, /// 'biggest' selection code hltVarCode: 0, lightCol: [int256(255), 255, 255], bgColTop: [int256(0), 0, 0], bgColBottom: [int256(7), 7, 7] }); } else { revert("invalid scheme id"); } return colScheme; } /** @dev convert hsv to rgb color assume h, s and v and in range [0, 255] outputs rgb in range [0, 255] */ function hsv2rgb( int256 h, int256 s, int256 v ) internal view returns (int256[3] memory res) { /// ensure range 0, 255 h = ShackledMath.max(0, ShackledMath.min(255, h)); s = ShackledMath.max(0, ShackledMath.min(255, s)); v = ShackledMath.max(0, ShackledMath.min(255, v)); int256 h2 = (((h % 255) * 1e3) / 255) * 360; /// convert to degress int256 v2 = (v * 1e3) / 255; int256 s2 = (s * 1e3) / 255; /// calculate c, x and m while scaling all by 1e3 /// otherwise x will be too small and round to 0 int256 c = (v2 * s2) / 1e3; int256 x = (c * (1 * 1e3 - ShackledMath.abs(((h2 / 60) % (2 * 1e3)) - (1 * 1e3)))); x = x / 1e3; int256 m = v2 - c; if (0 <= h2 && h2 < 60000) { res = [c + m, x + m, m]; } else if (60000 <= h2 && h2 < 120000) { res = [x + m, c + m, m]; } else if (120000 < h2 && h2 < 180000) { res = [m, c + m, x + m]; } else if (180000 < h2 && h2 < 240000) { res = [m, x + m, c + m]; } else if (240000 < h2 && h2 < 300000) { res = [x + m, m, c + m]; } else if (300000 < h2 && h2 < 360000) { res = [c + m, m, x + m]; } else { res = [int256(0), 0, 0]; } /// scale into correct range return [ (res[0] * 255) / 1e3, (res[1] * 255) / 1e3, (res[2] * 255) / 1e3 ]; } /** @dev convert rgb to hsv expects rgb to be in range [0, 255] outputs hsv in range [0, 255] */ function rgb2hsv( int256 r, int256 g, int256 b ) internal view returns (int256[3] memory) { int256 r2 = (r * 1e3) / 255; int256 g2 = (g * 1e3) / 255; int256 b2 = (b * 1e3) / 255; int256 max = ShackledMath.max(ShackledMath.max(r2, g2), b2); int256 min = ShackledMath.min(ShackledMath.min(r2, g2), b2); int256 delta = max - min; /// calculate hue int256 h; if (delta != 0) { if (max == r2) { int256 _h = ((g2 - b2) * 1e3) / delta; h = 60 * ShackledMath.mod(_h, 6000); } else if (max == g2) { h = 60 * (((b2 - r2) * 1e3) / delta + (2000)); } else if (max == b2) { h = 60 * (((r2 - g2) * 1e3) / delta + (4000)); } } h = (h % (360 * 1e3)) / 360; /// calculate saturation int256 s; if (max != 0) { s = (delta * 1e3) / max; } /// calculate value int256 v = max; return [(h * 255) / 1e3, (s * 255) / 1e3, (v * 255) / 1e3]; } /** @dev get vector of three numbers that can be used to jiggle a color */ function getJiggle( int256[3] memory jiggle, bytes32 randomSeed, int256 seedModifier ) internal view returns (int256[3] memory) { return [ jiggle[0] + GeomUtils.randN( randomSeed, string(abi.encodePacked("0", seedModifier)), -jiggle[0], jiggle[0] ), jiggle[1] + GeomUtils.randN( randomSeed, string(abi.encodePacked("1", seedModifier)), -jiggle[1], jiggle[1] ), jiggle[2] + GeomUtils.randN( randomSeed, string(abi.encodePacked("2", seedModifier)), -jiggle[2], jiggle[2] ) ]; } /** @dev check if a uint is in an array */ function inArray(uint256[] memory array, uint256 value) external view returns (bool) { for (uint256 i = 0; i < array.length; i++) { if (array[i] == value) { return true; } } return false; } /** @dev a helper function to apply the direction code in interpolation */ function applyDirHelp( int256[3][3] memory triFront, int256[3] memory colA, int256[3] memory colB, int256 dirCode, bool isInnerGradient, int256[3][2] memory extents ) internal view returns (int256[3][3] memory triCols) { uint256[3] memory order; if (isInnerGradient) { /// perform the simple 3 sort - always color by the front order = getOrderedPointIdxsInDir(triFront, dirCode); } else { /// order irrelevant in other case order = [uint256(0), 1, 2]; } /// axis is 0 (horizontal) if dir code is left-right or right-left /// 1 (vertical) otherwise uint256 axis = (dirCode == 0 || dirCode == 1) ? 0 : 1; int256 length; if (axis == 0) { length = extents[1][0] - extents[0][0]; } else { length = extents[1][1] - extents[0][1]; } /// if we're interpolating across the triangle (inner) /// then do so by calculating the color at each point in the triangle for (uint256 i = 0; i < 3; i++) { triCols[order[i]] = interpColHelp( colA, colB, (isInnerGradient) ? triFront[order[0]][axis] : int256(-length / 2), (isInnerGradient) ? triFront[order[2]][axis] : int256(length / 2), triFront[order[i]][axis] ); } } /** @dev a helper function to order points by index in a desired direction */ function getOrderedPointIdxsInDir(int256[3][3] memory tri, int256 dirCode) internal view returns (uint256[3] memory) { // flip if dir is left-right or down-up bool flip = (dirCode == 1 || dirCode == 3) ? true : false; // axis is 0 if horizontal (left-right or right-left), 1 otherwise (vertical) uint256 axis = (dirCode == 0 || dirCode == 1) ? 0 : 1; /// get the values of each point in the tri (flipped as required) int256 f = (flip) ? int256(-1) : int256(1); int256 a = f * tri[0][axis]; int256 b = f * tri[1][axis]; int256 c = f * tri[2][axis]; /// get the ordered indices uint256[3] memory ixOrd = [uint256(0), 1, 2]; /// simplest way to sort 3 numbers if (a > b) { (a, b) = (b, a); (ixOrd[0], ixOrd[1]) = (ixOrd[1], ixOrd[0]); } if (a > c) { (a, c) = (c, a); (ixOrd[0], ixOrd[2]) = (ixOrd[2], ixOrd[0]); } if (b > c) { (b, c) = (c, b); (ixOrd[1], ixOrd[2]) = (ixOrd[2], ixOrd[1]); } return ixOrd; } /** @dev a helper function for linear interpolation betweet two colors*/ function interpColHelp( int256[3] memory colA, int256[3] memory colB, int256 low, int256 high, int256 val ) internal view returns (int256[3] memory result) { int256 ir; int256 lerpScaleFactor = 1e3; if (high - low == 0) { ir = 1; } else { ir = ((val - low) * lerpScaleFactor) / (high - low); } for (uint256 i = 0; i < 3; i++) { /// dont allow interpolation to go below 0 result[i] = ShackledMath.max( 0, colA[i] + ((colB[i] - colA[i]) * ir) / lerpScaleFactor ); } } /** @dev get indexes of the prisms to use highlight coloring*/ function getHighlightPrismIdxs( int256[3][3][] memory tris, bytes32 tokenHash, uint256 nHighlights, int256 varCode, int256 selCode ) internal view returns (uint256[] memory idxs) { nHighlights = nHighlights < tris.length ? nHighlights : tris.length; ///if we just want random triangles then there's no need to sort if (selCode == 0) { idxs = ShackledMath.randomIdx( tokenHash, uint256(nHighlights), tris.length - 1 ); } else { idxs = getSortedTrisIdxs(tris, nHighlights, varCode, selCode); } } /** @dev return the index of the tris sorted by sel code @param selCode will be 1 (biggest first) or 2 (smallest first) */ function getSortedTrisIdxs( int256[3][3][] memory tris, uint256 nHighlights, int256 varCode, int256 selCode ) internal view returns (uint256[] memory) { // determine the sort order int256 orderFactor = (selCode == 2) ? int256(1) : int256(-1); /// get the list of triangle sizes int256[] memory sizes = new int256[](tris.length); for (uint256 i = 0; i < tris.length; i++) { if (varCode == 0) { // use size sizes[i] = GeomUtils.getRadiusLen(tris[i]) * orderFactor; } else if (varCode == 1) { // use x sizes[i] = GeomUtils.getCenterVec(tris[i])[0] * orderFactor; } else if (varCode == 2) { // use y sizes[i] = GeomUtils.getCenterVec(tris[i])[1] * orderFactor; } } /// initialise the index array uint256[] memory idxs = new uint256[](tris.length); for (uint256 i = 0; i < tris.length; i++) { idxs[i] = i; } /// run a boilerplate insertion sort over the index array for (uint256 i = 1; i < tris.length; i++) { int256 key = sizes[i]; uint256 j = i - 1; while (j > 0 && key < sizes[j]) { sizes[j + 1] = sizes[j]; idxs[j + 1] = idxs[j]; j--; } sizes[j + 1] = key; idxs[j + 1] = i; } uint256 nToCull = tris.length - nHighlights; assembly { mstore(idxs, sub(mload(idxs), nToCull)) } return idxs; } } /** Hold some functions externally to reduce contract size for mainnet deployment */ library GeomUtils { /// misc constants int256 constant MIN_INT = type(int256).min; int256 constant MAX_INT = type(int256).max; /// constants for doing trig int256 constant PI = 3141592653589793238; // pi as an 18 decimal value (wad) /// parameters that control geometry creation struct GeomSpec { string name; int256 id; int256 forceInitialSize; uint256 maxPrisms; int256 minTriRad; int256 maxTriRad; bool varySize; int256 depthMultiplier; bool isSymmetricX; bool isSymmetricY; int256 probVertOpp; int256 probAdjRec; int256 probVertOppRec; } /// variables uses when creating the initial 2d triangles struct TriVars { uint256 nextTriIdx; int256[3][3][] tris; int256[3][3] tri; int256 zBackRef; int256 zFrontRef; int256[] zFronts; int256[] zBacks; bool recursiveAttempt; } /// variables used when creating 3d prisms struct GeomVars { int256 rotX; int256 rotY; int256 rotZ; int256[3][2] extents; int256[3] center; int256 width; int256 height; int256 extent; int256 scaleNum; uint256[] hltPrismIdx; int256[3][3][] trisBack; int256[3][3][] trisFront; uint256 nPrisms; } /** @dev generate parameters that will control how the geometry is built */ function generateSpec(bytes32 tokenHash) external view returns (GeomSpec memory spec) { // 'randomly' select 1 of possible geometry specifications uint256 specId = getSpecId( tokenHash, [ [int256(0), 1000], [int256(1000), 3000], [int256(3000), 3500], [int256(3500), 4500], [int256(4500), 5000], [int256(5000), 6000], [int256(6000), 8000] ] ); bool isSymmetricX = GeomUtils.randN(tokenHash, "symmX", 0, 2) > 0; bool isSymmetricY = GeomUtils.randN(tokenHash, "symmY", 0, 2) > 0; int256 defaultDepthMultiplier = randN(tokenHash, "depthMult", 80, 120); int256 defaultMinTriRad = 4800; int256 defaultMaxTriRad = defaultMinTriRad * 3; uint256 defaultMaxPrisms = uint256( randN(tokenHash, "maxPrisms", 8, 16) ); if (specId == 0) { /// all vertically opposite spec = GeomSpec({ id: 0, name: "Verticalized", forceInitialSize: (defaultMinTriRad * 5) / 2, maxPrisms: defaultMaxPrisms, minTriRad: defaultMinTriRad, maxTriRad: defaultMaxTriRad, varySize: true, depthMultiplier: defaultDepthMultiplier, probVertOpp: 100, probVertOppRec: 100, probAdjRec: 0, isSymmetricX: isSymmetricX, isSymmetricY: isSymmetricY }); } else if (specId == 1) { /// fully adjacent spec = GeomSpec({ id: 1, name: "Adjoint", forceInitialSize: (defaultMinTriRad * 5) / 2, maxPrisms: defaultMaxPrisms, minTriRad: defaultMinTriRad, maxTriRad: defaultMaxTriRad, varySize: true, depthMultiplier: defaultDepthMultiplier, probVertOpp: 0, probVertOppRec: 0, probAdjRec: 100, isSymmetricX: isSymmetricX, isSymmetricY: isSymmetricY }); } else if (specId == 2) { /// few but big spec = GeomSpec({ id: 2, name: "Cetacean", forceInitialSize: 0, maxPrisms: 8, minTriRad: defaultMinTriRad * 3, maxTriRad: defaultMinTriRad * 4, varySize: true, depthMultiplier: defaultDepthMultiplier, probVertOpp: 50, probVertOppRec: 50, probAdjRec: 50, isSymmetricX: isSymmetricX, isSymmetricY: isSymmetricY }); } else if (specId == 3) { /// lots but small spec = GeomSpec({ id: 3, name: "Swarm", forceInitialSize: 0, maxPrisms: 16, minTriRad: defaultMinTriRad, maxTriRad: defaultMinTriRad * 2, varySize: true, depthMultiplier: defaultDepthMultiplier, probVertOpp: 50, probVertOppRec: 0, probAdjRec: 0, isSymmetricX: isSymmetricX, isSymmetricY: isSymmetricY }); } else if (specId == 4) { /// all same size spec = GeomSpec({ id: 4, name: "Isomorphic", forceInitialSize: 0, maxPrisms: defaultMaxPrisms, minTriRad: defaultMinTriRad, maxTriRad: defaultMaxTriRad, varySize: false, depthMultiplier: defaultDepthMultiplier, probVertOpp: 50, probVertOppRec: 50, probAdjRec: 50, isSymmetricX: isSymmetricX, isSymmetricY: isSymmetricY }); } else if (specId == 5) { /// trains spec = GeomSpec({ id: 5, name: "Extruded", forceInitialSize: 0, maxPrisms: 10, minTriRad: defaultMinTriRad, maxTriRad: defaultMaxTriRad, varySize: true, depthMultiplier: defaultDepthMultiplier, probVertOpp: 50, probVertOppRec: 50, probAdjRec: 50, isSymmetricX: isSymmetricX, isSymmetricY: isSymmetricY }); } else if (specId == 6) { /// flatpack spec = GeomSpec({ id: 6, name: "Uniform", forceInitialSize: 0, maxPrisms: 12, minTriRad: defaultMinTriRad, maxTriRad: defaultMaxTriRad, varySize: true, depthMultiplier: defaultDepthMultiplier, probVertOpp: 50, probVertOppRec: 50, probAdjRec: 50, isSymmetricX: isSymmetricX, isSymmetricY: isSymmetricY }); } else { revert("invalid specId"); } } /** @dev make triangles to the side of a reference triangle */ function makeAdjacentTriangles( bytes32 tokenHash, uint256 attemptNum, uint256 refIdx, TriVars memory triVars, GeomSpec memory geomSpec, int256 overrideSideIdx, int256 overrideScale, int256 depth ) public view returns (TriVars memory) { /// get the side index (0, 1 or 2) int256 sideIdx; if (overrideSideIdx == -1) { sideIdx = randN( tokenHash, string(abi.encodePacked("sideIdx", attemptNum, depth)), 0, 2 ); } else { sideIdx = overrideSideIdx; } /// get the scale /// this value is scaled up by 1e3 (desired range is 0.333 to 0.8) /// the scale will be divided out when used int256 scale; if (geomSpec.varySize) { if (overrideScale == -1) { scale = randN( tokenHash, string(abi.encodePacked("scaleAdj", attemptNum, depth)), 333, 800 ); } else { scale = overrideScale; } } else { scale = 1e3; } /// make a new triangle int256[3][3] memory newTri = makeTriAdjacent( tokenHash, geomSpec, attemptNum, triVars.tris[refIdx], sideIdx, scale, depth ); /// set the zbackref and frontbackref triVars.zBackRef = -1; /// calculate a new z back triVars.zFrontRef = -1; /// calculate a new z ftont // try to add the triangle, and use the reference z height triVars.recursiveAttempt = false; bool wasAdded = attemptToAddTri(newTri, tokenHash, triVars, geomSpec); if (wasAdded) { // run again if ( randN( tokenHash, string( abi.encodePacked("addAdjRecursive", attemptNum, depth) ), 0, 100 ) <= geomSpec.probAdjRec ) { triVars = makeAdjacentTriangles( tokenHash, attemptNum, triVars.nextTriIdx - 1, triVars, geomSpec, sideIdx, 666, /// always make the next one 2/3 scale depth + 1 ); } } return triVars; } /** @dev make triangles vertically opposite a reference triangle */ function makeVerticallyOppositeTriangles( bytes32 tokenHash, uint256 attemptNum, uint256 refIdx, TriVars memory triVars, GeomSpec memory geomSpec, int256 overrideSideIdx, int256 overrideScale, int256 depth ) public view returns (TriVars memory) { /// get the side index (0, 1 or 2) int256 sideIdx; if (overrideSideIdx == -1) { sideIdx = randN( tokenHash, string(abi.encodePacked("vertOppSideIdx", attemptNum, depth)), 0, 2 ); } else { sideIdx = overrideSideIdx; } /// get the scale /// this value is scaled up by 1e3 /// use attemptNum in seedModifier to ensure unique values each attempt int256 scale; if (geomSpec.varySize) { if (overrideScale == -1) { if ( // prettier-ignore randN( tokenHash, string(abi.encodePacked("vertOppScale1", attemptNum, depth)), 0, 100 ) > 33 ) { // prettier-ignore if ( randN( tokenHash, string(abi.encodePacked("vertOppScale2", attemptNum, depth) ), 0, 100 ) > 50 ) { scale = 1000; /// desired = 1 (same scale) } else { scale = 500; /// desired = 0.5 (half scale) } } else { scale = 2000; /// desired = 2 (double scale) } } else { scale = overrideScale; } } else { scale = 1e3; } /// make a new triangle int256[3][3] memory newTri = makeTriVertOpp( triVars.tris[refIdx], geomSpec, sideIdx, scale ); /// set the zbackref and frontbackref triVars.zBackRef = -1; /// calculate a new z back triVars.zFrontRef = triVars.zFronts[refIdx]; // try to add the triangle, and use the reference z height triVars.recursiveAttempt = false; bool wasAdded = attemptToAddTri(newTri, tokenHash, triVars, geomSpec); if (wasAdded) { /// run again if ( randN( tokenHash, string( abi.encodePacked("recursiveVertOpp", attemptNum, depth) ), 0, 100 ) <= geomSpec.probVertOppRec ) { triVars = makeVerticallyOppositeTriangles( tokenHash, attemptNum, refIdx, triVars, geomSpec, sideIdx, 666, /// always make the next one 2/3 scale depth + 1 ); } } return triVars; } /** @dev place a triangle vertically opposite over the given point @param refTri the reference triangle to base the new triangle on */ function makeTriVertOpp( int256[3][3] memory refTri, GeomSpec memory geomSpec, int256 sideIdx, int256 scale ) internal view returns (int256[3][3] memory) { /// calculate the center of the reference triangle /// add and then divide by 1e3 (the factor by which scale is scaled up) int256 centerDist = (getRadiusLen(refTri) * (1e3 + scale)) / 1e3; /// get the new triangle's direction int256 newAngle = sideIdx * 120 + 60 + (isTriPointingUp(refTri) ? int256(60) : int256(0)); int256 spacing = 64; /// calculate the true offset int256[3] memory offset = vector3RotateZ( [int256(0), centerDist + spacing, 0], newAngle ); int256[3] memory centerVec = getCenterVec(refTri); int256[3] memory newCentre = ShackledMath.vector3Add(centerVec, offset); /// return the new triangle (div by 1e3 to account for scale) int256 newRadius = (scale * getRadiusLen(refTri)) / 1e3; newRadius = ShackledMath.min(geomSpec.maxTriRad, newRadius); newAngle -= 210; return makeTri(newCentre, newRadius, newAngle); } /** @dev make a new adjacent triangle */ function makeTriAdjacent( bytes32 tokenHash, GeomSpec memory geomSpec, uint256 attemptNum, int256[3][3] memory refTri, int256 sideIdx, int256 scale, int256 depth ) internal view returns (int256[3][3] memory) { /// calculate the center of the new triangle /// add and then divide by 1e3 (the factor by which scale is scaled up) int256 centerDist = (getPerpLen(refTri) * (1e3 + scale)) / 1e3; /// get the new triangle's direction int256 newAngle = sideIdx * 120 + (isTriPointingUp(refTri) ? int256(60) : int256(0)); /// determine the direction of the offset offset /// get a unique random seed each attempt to ensure variation // prettier-ignore int256 offsetDirection = randN( tokenHash, string(abi.encodePacked("lateralOffset", attemptNum, depth)), 0, 1 ) * 2 - 1; /// put if off to one side of the triangle if it's smaller /// scale is on order of 1e3 int256 lateralOffset = (offsetDirection * (1e3 - scale) * getSideLen(refTri)) / 1e3; /// make a gap between the triangles int256 spacing = 6000; /// calculate the true offset int256[3] memory offset = vector3RotateZ( [lateralOffset, centerDist + spacing, 0], newAngle ); int256[3] memory newCentre = ShackledMath.vector3Add( getCenterVec(refTri), offset ); /// return the new triangle (div by 1e3 to account for scale) int256 newRadius = (scale * getRadiusLen(refTri)) / 1e3; newRadius = ShackledMath.min(geomSpec.maxTriRad, newRadius); newAngle -= 30; return makeTri(newCentre, newRadius, newAngle); } /** @dev create a triangle centered at centre, with length from centre to point of radius */ function makeTri( int256[3] memory centre, int256 radius, int256 angle ) internal view returns (int256[3][3] memory tri) { /// create a vector to rotate around 3 times int256[3] memory offset = [radius, 0, 0]; /// make 3 points of the tri for (uint256 i = 0; i < 3; i++) { int256 armAngle = 120 * int256(i); int256[3] memory offsetVec = vector3RotateZ( offset, armAngle + angle ); tri[i] = ShackledMath.vector3Add(centre, offsetVec); } } /** @dev rotate a vector around x */ function vector3RotateX(int256[3] memory v, int256 deg) internal view returns (int256[3] memory) { /// get the cos and sin of the angle (int256 cos, int256 sin) = trigHelper(deg); /// calculate new y and z (scaling down to account for trig scaling) int256 y = ((v[1] * cos) - (v[2] * sin)) / 1e18; int256 z = ((v[1] * sin) + (v[2] * cos)) / 1e18; return [v[0], y, z]; } /** @dev rotate a vector around y */ function vector3RotateY(int256[3] memory v, int256 deg) internal view returns (int256[3] memory) { /// get the cos and sin of the angle (int256 cos, int256 sin) = trigHelper(deg); /// calculate new x and z (scaling down to account for trig scaling) int256 x = ((v[0] * cos) - (v[2] * sin)) / 1e18; int256 z = ((v[0] * sin) + (v[2] * cos)) / 1e18; return [x, v[1], z]; } /** @dev rotate a vector around z */ function vector3RotateZ(int256[3] memory v, int256 deg) internal view returns (int256[3] memory) { /// get the cos and sin of the angle (int256 cos, int256 sin) = trigHelper(deg); /// calculate new x and y (scaling down to account for trig scaling) int256 x = ((v[0] * cos) - (v[1] * sin)) / 1e18; int256 y = ((v[0] * sin) + (v[1] * cos)) / 1e18; return [x, y, v[2]]; } /** @dev calculate sin and cos of an angle */ function trigHelper(int256 deg) internal view returns (int256 cos, int256 sin) { /// deal with negative degrees here, since Trigonometry.sol can't int256 n360 = (ShackledMath.abs(deg) / 360) + 1; deg = (deg + (360 * n360)) % 360; uint256 rads = uint256((deg * PI) / 180); /// calculate radians (in 1e18 space) cos = Trigonometry.cos(rads); sin = Trigonometry.sin(rads); } /** @dev Get the 3d vector at the center of a triangle */ function getCenterVec(int256[3][3] memory tri) internal view returns (int256[3] memory) { return ShackledMath.vector3DivScalar( ShackledMath.vector3Add( ShackledMath.vector3Add(tri[0], tri[1]), tri[2] ), 3 ); } /** @dev Get the length from the center of a triangle to point*/ function getRadiusLen(int256[3][3] memory tri) internal view returns (int256) { return ShackledMath.vector3Len( ShackledMath.vector3Sub(getCenterVec(tri), tri[0]) ); } /** @dev Get the length from any point on triangle to other point (equilateral)*/ function getSideLen(int256[3][3] memory tri) internal view returns (int256) { // len * 0.886 return (getRadiusLen(tri) * 8660) / 10000; } /** @dev Get the shortes length from center of triangle to side */ function getPerpLen(int256[3][3] memory tri) internal view returns (int256) { return getRadiusLen(tri) / 2; } /** @dev Determine if a triangle is pointing up*/ function isTriPointingUp(int256[3][3] memory tri) internal view returns (bool) { int256 centerY = getCenterVec(tri)[1]; /// count how many verts are above this y value int256 nAbove = 0; for (uint256 i = 0; i < 3; i++) { if (tri[i][1] > centerY) { nAbove++; } } return nAbove == 1; } /** @dev check if two triangles are close */ function areTrisClose(int256[3][3] memory tri1, int256[3][3] memory tri2) internal view returns (bool) { int256 lenBetweenCenters = ShackledMath.vector3Len( ShackledMath.vector3Sub(getCenterVec(tri1), getCenterVec(tri2)) ); return lenBetweenCenters < (getPerpLen(tri1) + getPerpLen(tri2)); } /** @dev check if two triangles have overlapping points*/ function areTrisPointsOverlapping( int256[3][3] memory tri1, int256[3][3] memory tri2 ) internal view returns (bool) { /// check triangle a against b if ( isPointInTri(tri1, tri2[0]) || isPointInTri(tri1, tri2[1]) || isPointInTri(tri1, tri2[2]) ) { return true; } /// check triangle b against a if ( isPointInTri(tri2, tri1[0]) || isPointInTri(tri2, tri1[1]) || isPointInTri(tri2, tri1[2]) ) { return true; } /// otherwise they mustn't be overlapping return false; } /** @dev calculate if a point is in a tri*/ function isPointInTri(int256[3][3] memory tri, int256[3] memory p) internal view returns (bool) { int256[3] memory p1 = tri[0]; int256[3] memory p2 = tri[1]; int256[3] memory p3 = tri[2]; int256 alphaNum = (p2[1] - p3[1]) * (p[0] - p3[0]) + (p3[0] - p2[0]) * (p[1] - p3[1]); int256 alphaDenom = (p2[1] - p3[1]) * (p1[0] - p3[0]) + (p3[0] - p2[0]) * (p1[1] - p3[1]); int256 betaNum = (p3[1] - p1[1]) * (p[0] - p3[0]) + (p1[0] - p3[0]) * (p[1] - p3[1]); int256 betaDenom = (p2[1] - p3[1]) * (p1[0] - p3[0]) + (p3[0] - p2[0]) * (p1[1] - p3[1]); if (alphaDenom == 0 || betaDenom == 0) { return false; } else { int256 alpha = (alphaNum * 1e6) / alphaDenom; int256 beta = (betaNum * 1e6) / betaDenom; int256 gamma = 1e6 - alpha - beta; return alpha > 0 && beta > 0 && gamma > 0; } } /** @dev check all points of the tri to see if it overlaps with any other tris */ function isTriOverlappingWithTris( int256[3][3] memory tri, int256[3][3][] memory tris, uint256 nextTriIdx ) internal view returns (bool) { /// check against all other tris added thus fat for (uint256 i = 0; i < nextTriIdx; i++) { if ( areTrisClose(tri, tris[i]) || areTrisPointsOverlapping(tri, tris[i]) ) { return true; } } return false; } function isPointCloseToLine( int256[3] memory p, int256[3] memory l1, int256[3] memory l2 ) internal view returns (bool) { int256 x0 = p[0]; int256 y0 = p[1]; int256 x1 = l1[0]; int256 y1 = l1[1]; int256 x2 = l2[0]; int256 y2 = l2[1]; int256 distanceNum = ShackledMath.abs( (x2 - x1) * (y1 - y0) - (x1 - x0) * (y2 - y1) ); int256 distanceDenom = ShackledMath.hypot((x2 - x1), (y2 - y1)); int256 distance = distanceNum / distanceDenom; if (distance < 8) { return true; } } /** compare a triangles points against the lines of other tris */ function isTrisPointsCloseToLines( int256[3][3] memory tri, int256[3][3][] memory tris, uint256 nextTriIdx ) internal view returns (bool) { for (uint256 i = 0; i < nextTriIdx; i++) { for (uint256 p = 0; p < 3; p++) { if (isPointCloseToLine(tri[p], tris[i][0], tris[i][1])) { return true; } if (isPointCloseToLine(tri[p], tris[i][1], tris[i][2])) { return true; } if (isPointCloseToLine(tri[p], tris[i][2], tris[i][0])) { return true; } } } } /** @dev check if tri to add meets certain criteria */ function isTriLegal( int256[3][3] memory tri, int256[3][3][] memory tris, uint256 nextTriIdx, int256 minTriRad ) internal view returns (bool) { // check radius first as point checks will fail // if the radius is too small if (getRadiusLen(tri) < minTriRad) { return false; } return (!isTriOverlappingWithTris(tri, tris, nextTriIdx) && !isTrisPointsCloseToLines(tri, tris, nextTriIdx)); } /** @dev helper function to add triangles */ function attemptToAddTri( int256[3][3] memory tri, bytes32 tokenHash, TriVars memory triVars, GeomSpec memory geomSpec ) internal view returns (bool added) { bool isLegal = isTriLegal( tri, triVars.tris, triVars.nextTriIdx, geomSpec.minTriRad ); if (isLegal && triVars.nextTriIdx < geomSpec.maxPrisms) { // add the triangle triVars.tris[triVars.nextTriIdx] = tri; added = true; // add the new zs if (triVars.zBackRef == -1) { /// z back ref is not provided, calculate it triVars.zBacks[triVars.nextTriIdx] = calculateZ( tri, tokenHash, triVars.nextTriIdx, geomSpec, false ); } else { /// use the provided z back (from the ref) triVars.zBacks[triVars.nextTriIdx] = triVars.zBackRef; } if (triVars.zFrontRef == -1) { /// z front ref is not provided, calculate it triVars.zFronts[triVars.nextTriIdx] = calculateZ( tri, tokenHash, triVars.nextTriIdx, geomSpec, true ); } else { /// use the provided z front (from the ref) triVars.zFronts[triVars.nextTriIdx] = triVars.zFrontRef; } // increment the tris counter triVars.nextTriIdx += 1; // if we're using any type of symmetry then attempt to add a symmetric triangle // only do this recursively once if ( (geomSpec.isSymmetricX || geomSpec.isSymmetricY) && (!triVars.recursiveAttempt) ) { int256[3][3] memory symTri = copyTri(tri); if (geomSpec.isSymmetricX) { symTri[0][0] = -symTri[0][0]; symTri[1][0] = -symTri[1][0]; symTri[2][0] = -symTri[2][0]; // symCenter[0] = -symCenter[0]; } if (geomSpec.isSymmetricY) { symTri[0][1] = -symTri[0][1]; symTri[1][1] = -symTri[1][1]; symTri[2][1] = -symTri[2][1]; // symCenter[1] = -symCenter[1]; } if ( (geomSpec.isSymmetricX || geomSpec.isSymmetricY) && !(geomSpec.isSymmetricX && geomSpec.isSymmetricY) ) { symTri = [symTri[2], symTri[1], symTri[0]]; } triVars.recursiveAttempt = true; triVars.zBackRef = triVars.zBacks[triVars.nextTriIdx - 1]; triVars.zFrontRef = triVars.zFronts[triVars.nextTriIdx - 1]; attemptToAddTri(symTri, tokenHash, triVars, geomSpec); } } } /** @dev rotate a triangle by x, y, or z @param axis 0 = x, 1 = y, 2 = z */ function triRotHelp( int256 axis, int256[3][3] memory tri, int256 rot ) internal view returns (int256[3][3] memory) { if (axis == 0) { return [ vector3RotateX(tri[0], rot), vector3RotateX(tri[1], rot), vector3RotateX(tri[2], rot) ]; } else if (axis == 1) { return [ vector3RotateY(tri[0], rot), vector3RotateY(tri[1], rot), vector3RotateY(tri[2], rot) ]; } else if (axis == 2) { return [ vector3RotateZ(tri[0], rot), vector3RotateZ(tri[1], rot), vector3RotateZ(tri[2], rot) ]; } } /** @dev a helper to run rotation functions on back/front triangles */ function triBfHelp( int256 axis, int256[3][3][] memory trisBack, int256[3][3][] memory trisFront, int256 rot ) internal view returns (int256[3][3][] memory, int256[3][3][] memory) { int256[3][3][] memory trisBackNew = new int256[3][3][](trisBack.length); int256[3][3][] memory trisFrontNew = new int256[3][3][]( trisFront.length ); for (uint256 i = 0; i < trisBack.length; i++) { trisBackNew[i] = triRotHelp(axis, trisBack[i], rot); trisFrontNew[i] = triRotHelp(axis, trisFront[i], rot); } return (trisBackNew, trisFrontNew); } /** @dev get the maximum extent of the geometry (vertical or horizontal) */ function getExtents(int256[3][3][] memory tris) internal view returns (int256[3][2] memory) { int256 minX = MAX_INT; int256 maxX = MIN_INT; int256 minY = MAX_INT; int256 maxY = MIN_INT; int256 minZ = MAX_INT; int256 maxZ = MIN_INT; for (uint256 i = 0; i < tris.length; i++) { for (uint256 j = 0; j < tris[i].length; j++) { minX = ShackledMath.min(minX, tris[i][j][0]); maxX = ShackledMath.max(maxX, tris[i][j][0]); minY = ShackledMath.min(minY, tris[i][j][1]); maxY = ShackledMath.max(maxY, tris[i][j][1]); minZ = ShackledMath.min(minZ, tris[i][j][2]); maxZ = ShackledMath.max(maxZ, tris[i][j][2]); } } return [[minX, minY, minZ], [maxX, maxY, maxZ]]; } /** @dev go through each triangle and apply a 'height' */ function calculateZ( int256[3][3] memory tri, bytes32 tokenHash, uint256 nextTriIdx, GeomSpec memory geomSpec, bool front ) internal view returns (int256) { int256 h; string memory seedMod = string(abi.encodePacked("calcZ", nextTriIdx)); if (front) { if (geomSpec.id == 6) { h = 1; } else { if (randN(tokenHash, seedMod, 0, 10) > 9) { if (randN(tokenHash, seedMod, 0, 10) > 3) { h = 10; } else { h = 22; } } else { if (randN(tokenHash, seedMod, 0, 10) > 5) { h = 8; } else { h = 1; } } } } else { if (geomSpec.id == 6) { h = -1; } else { if (geomSpec.id == 5) { h = -randN(tokenHash, seedMod, 2, 20); } else { h = -2; } } } if (geomSpec.id == 5) { h += 10; } return h * geomSpec.depthMultiplier; } /** @dev roll a specId given a list of weightings */ function getSpecId(bytes32 tokenHash, int256[2][7] memory weightings) internal view returns (uint256) { int256 n = GeomUtils.randN( tokenHash, "specId", weightings[0][0], weightings[weightings.length - 1][1] ); for (uint256 i = 0; i < weightings.length; i++) { if (weightings[i][0] <= n && n <= weightings[i][1]) { return i; } } } /** @dev get a random number between two numbers with a uniform probability distribution @param randomSeed a hash that we can use to 'randomly' get a number @param seedModifier some string to make the result unique for this tokenHash @param min the minimum number (inclusive) @param max the maximum number (inclusive) examples: to get binary output (0 or 1), set min as 0 and max as 1 */ function randN( bytes32 randomSeed, string memory seedModifier, int256 min, int256 max ) internal view returns (int256) { /// use max() to ensure modulo != 0 return int256( uint256(keccak256(abi.encodePacked(randomSeed, seedModifier))) % uint256(ShackledMath.max(1, (max + 1 - min))) ) + min; } /** @dev clip an array of tris to a certain length (to trim empty tail slots) */ function clipTrisToLength(int256[3][3][] memory arr, uint256 desiredLen) internal view returns (int256[3][3][] memory) { uint256 n = arr.length - desiredLen; assembly { mstore(arr, sub(mload(arr), n)) } return arr; } /** @dev clip an array of Z values to a certain length (to trim empty tail slots) */ function clipZsToLength(int256[] memory arr, uint256 desiredLen) internal view returns (int256[] memory) { uint256 n = arr.length - desiredLen; assembly { mstore(arr, sub(mload(arr), n)) } return arr; } /** @dev make a copy of a triangle */ function copyTri(int256[3][3] memory tri) internal view returns (int256[3][3] memory) { return [ [tri[0][0], tri[0][1], tri[0][2]], [tri[1][0], tri[1][1], tri[1][2]], [tri[2][0], tri[2][1], tri[2][2]] ]; } /** @dev make a copy of an array of triangles */ function copyTris(int256[3][3][] memory tris) internal view returns (int256[3][3][] memory) { int256[3][3][] memory newTris = new int256[3][3][](tris.length); for (uint256 i = 0; i < tris.length; i++) { newTris[i] = copyTri(tris[i]); } return newTris; } } // SPDX-License-Identifier: Unlicense pragma solidity ^0.8.0; library ShackledStructs { struct Metadata { string colorScheme; /// name of the color scheme string geomSpec; /// name of the geometry specification uint256 nPrisms; /// number of prisms made string pseudoSymmetry; /// horizontal, vertical, diagonal string wireframe; /// enabled or disabled string inversion; /// enabled or disabled } struct RenderParams { uint256[3][] faces; /// index of verts and colorss used for each face (triangle) int256[3][] verts; /// x, y, z coordinates used in the geometry int256[3][] cols; /// colors of each vert int256[3] objPosition; /// position to place the object int256 objScale; /// scalar for the object int256[3][2] backgroundColor; /// color of the background (gradient) LightingParams lightingParams; /// parameters for the lighting bool perspCamera; /// true = perspective camera, false = orthographic bool backfaceCulling; /// whether to implement backface culling (saves gas!) bool invert; /// whether to invert colors in the final encoding stage bool wireframe; /// whether to only render edges } /// struct for testing lighting struct LightingParams { bool applyLighting; /// true = apply lighting, false = don't apply lighting int256 lightAmbiPower; /// power of the ambient light int256 lightDiffPower; /// power of the diffuse light int256 lightSpecPower; /// power of the specular light uint256 inverseShininess; /// shininess of the material int256[3] lightPos; /// position of the light int256[3] lightColSpec; /// color of the specular light int256[3] lightColDiff; /// color of the diffuse light int256[3] lightColAmbi; /// color of the ambient light } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.0; library ShackledMath { /** @dev Get the minimum of two numbers */ function min(int256 a, int256 b) internal pure returns (int256) { return a < b ? a : b; } /** @dev Get the maximum of two numbers */ function max(int256 a, int256 b) internal pure returns (int256) { return a > b ? a : b; } /** @dev perform a modulo operation, with support for negative numbers */ function mod(int256 n, int256 m) internal pure returns (int256) { if (n < 0) { return ((n % m) + m) % m; } else { return n % m; } } /** @dev 'randomly' select n numbers between 0 and m (useful for getting a randomly sampled index) */ function randomIdx( bytes32 seedModifier, uint256 n, // number of elements to select uint256 m // max value of elements ) internal pure returns (uint256[] memory) { uint256[] memory result = new uint256[](n); for (uint256 i = 0; i < n; i++) { result[i] = uint256(keccak256(abi.encodePacked(seedModifier, i))) % m; } return result; } /** @dev create a 2d array and fill with a single value */ function get2dArray( uint256 m, uint256 q, int256 value ) internal pure returns (int256[][] memory) { /// Create a matrix of values with dimensions (m, q) int256[][] memory rows = new int256[][](m); for (uint256 i = 0; i < m; i++) { int256[] memory row = new int256[](q); for (uint256 j = 0; j < q; j++) { row[j] = value; } rows[i] = row; } return rows; } /** @dev get the absolute of a number */ function abs(int256 x) internal pure returns (int256) { assembly { if slt(x, 0) { x := sub(0, x) } } return x; } /** @dev get the square root of a number */ function sqrt(int256 y) internal pure returns (int256 z) { assembly { if sgt(y, 3) { z := y let x := add(div(y, 2), 1) for { } slt(x, z) { } { z := x x := div(add(div(y, x), x), 2) } } if and(slt(y, 4), sgt(y, 0)) { z := 1 } } } /** @dev get the hypotenuse of a triangle given the length of 2 sides */ function hypot(int256 x, int256 y) internal pure returns (int256) { int256 sumsq; assembly { let xsq := mul(x, x) let ysq := mul(y, y) sumsq := add(xsq, ysq) } return sqrt(sumsq); } /** @dev addition between two vectors (size 3) */ function vector3Add(int256[3] memory v1, int256[3] memory v2) internal pure returns (int256[3] memory result) { assembly { mstore(result, add(mload(v1), mload(v2))) mstore( add(result, 0x20), add(mload(add(v1, 0x20)), mload(add(v2, 0x20))) ) mstore( add(result, 0x40), add(mload(add(v1, 0x40)), mload(add(v2, 0x40))) ) } } /** @dev subtraction between two vectors (size 3) */ function vector3Sub(int256[3] memory v1, int256[3] memory v2) internal pure returns (int256[3] memory result) { assembly { mstore(result, sub(mload(v1), mload(v2))) mstore( add(result, 0x20), sub(mload(add(v1, 0x20)), mload(add(v2, 0x20))) ) mstore( add(result, 0x40), sub(mload(add(v1, 0x40)), mload(add(v2, 0x40))) ) } } /** @dev multiply a vector (size 3) by a constant */ function vector3MulScalar(int256[3] memory v, int256 a) internal pure returns (int256[3] memory result) { assembly { mstore(result, mul(mload(v), a)) mstore(add(result, 0x20), mul(mload(add(v, 0x20)), a)) mstore(add(result, 0x40), mul(mload(add(v, 0x40)), a)) } } /** @dev divide a vector (size 3) by a constant */ function vector3DivScalar(int256[3] memory v, int256 a) internal pure returns (int256[3] memory result) { assembly { mstore(result, sdiv(mload(v), a)) mstore(add(result, 0x20), sdiv(mload(add(v, 0x20)), a)) mstore(add(result, 0x40), sdiv(mload(add(v, 0x40)), a)) } } /** @dev get the length of a vector (size 3) */ function vector3Len(int256[3] memory v) internal pure returns (int256) { int256 res; assembly { let x := mload(v) let y := mload(add(v, 0x20)) let z := mload(add(v, 0x40)) res := add(add(mul(x, x), mul(y, y)), mul(z, z)) } return sqrt(res); } /** @dev scale and then normalise a vector (size 3) */ function vector3NormX(int256[3] memory v, int256 fidelity) internal pure returns (int256[3] memory result) { int256 l = vector3Len(v); assembly { mstore(result, sdiv(mul(fidelity, mload(add(v, 0x40))), l)) mstore( add(result, 0x20), sdiv(mul(fidelity, mload(add(v, 0x20))), l) ) mstore(add(result, 0x40), sdiv(mul(fidelity, mload(v)), l)) } } /** @dev get the dot-product of two vectors (size 3) */ function vector3Dot(int256[3] memory v1, int256[3] memory v2) internal view returns (int256 result) { assembly { result := add( add( mul(mload(v1), mload(v2)), mul(mload(add(v1, 0x20)), mload(add(v2, 0x20))) ), mul(mload(add(v1, 0x40)), mload(add(v2, 0x40))) ) } } /** @dev get the cross product of two vectors (size 3) */ function crossProduct(int256[3] memory v1, int256[3] memory v2) internal pure returns (int256[3] memory result) { assembly { mstore( result, sub( mul(mload(add(v1, 0x20)), mload(add(v2, 0x40))), mul(mload(add(v1, 0x40)), mload(add(v2, 0x20))) ) ) mstore( add(result, 0x20), sub( mul(mload(add(v1, 0x40)), mload(v2)), mul(mload(v1), mload(add(v2, 0x40))) ) ) mstore( add(result, 0x40), sub( mul(mload(v1), mload(add(v2, 0x20))), mul(mload(add(v1, 0x20)), mload(v2)) ) ) } } /** @dev linearly interpolate between two vectors (size 12) */ function vector12Lerp( int256[12] memory v1, int256[12] memory v2, int256 ir, int256 scaleFactor ) internal view returns (int256[12] memory result) { int256[12] memory vd = vector12Sub(v2, v1); // loop through all 12 items assembly { let ix for { let i := 0 } lt(i, 0xC) { // (i < 12) i := add(i, 1) } { /// get index of the next element ix := mul(i, 0x20) /// store into the result array mstore( add(result, ix), add( // v1[i] + (ir * vd[i]) / 1e3 mload(add(v1, ix)), sdiv(mul(ir, mload(add(vd, ix))), 1000) ) ) } } } /** @dev subtraction between two vectors (size 12) */ function vector12Sub(int256[12] memory v1, int256[12] memory v2) internal view returns (int256[12] memory result) { // loop through all 12 items assembly { let ix for { let i := 0 } lt(i, 0xC) { // (i < 12) i := add(i, 1) } { /// get index of the next element ix := mul(i, 0x20) /// store into the result array mstore( add(result, ix), sub( // v1[ix] - v2[ix] mload(add(v1, ix)), mload(add(v2, ix)) ) ) } } } /** @dev map a number from one range into another */ function mapRangeToRange( int256 num, int256 inMin, int256 inMax, int256 outMin, int256 outMax ) internal pure returns (int256 res) { assembly { res := add( sdiv( mul(sub(outMax, outMin), sub(num, inMin)), sub(inMax, inMin) ), outMin ) } } } // SPDX-License-Identifier: MIT /** * @notice Solidity library offering basic trigonometry functions where inputs and outputs are * integers. Inputs are specified in radians scaled by 1e18, and similarly outputs are scaled by 1e18. * * This implementation is based off the Solidity trigonometry library written by Lefteris Karapetsas * which can be found here: https://github.com/Sikorkaio/sikorka/blob/e75c91925c914beaedf4841c0336a806f2b5f66d/contracts/trigonometry.sol * * Compared to Lefteris' implementation, this version makes the following changes: * - Uses a 32 bits instead of 16 bits for improved accuracy * - Updated for Solidity 0.8.x * - Various gas optimizations * - Change inputs/outputs to standard trig format (scaled by 1e18) instead of requiring the * integer format used by the algorithm * * Lefertis' implementation is based off Dave Dribin's trigint C library * http://www.dribin.org/dave/trigint/ * * Which in turn is based from a now deleted article which can be found in the Wayback Machine: * http://web.archive.org/web/20120301144605/http://www.dattalo.com/technical/software/pic/picsine.html */ pragma solidity ^0.8.0; library Trigonometry { // Table index into the trigonometric table uint256 constant INDEX_WIDTH = 8; // Interpolation between successive entries in the table uint256 constant INTERP_WIDTH = 16; uint256 constant INDEX_OFFSET = 28 - INDEX_WIDTH; uint256 constant INTERP_OFFSET = INDEX_OFFSET - INTERP_WIDTH; uint32 constant ANGLES_IN_CYCLE = 1073741824; uint32 constant QUADRANT_HIGH_MASK = 536870912; uint32 constant QUADRANT_LOW_MASK = 268435456; uint256 constant SINE_TABLE_SIZE = 256; // Pi as an 18 decimal value, which is plenty of accuracy: "For JPL's highest accuracy calculations, which are for // interplanetary navigation, we use 3.141592653589793: https://www.jpl.nasa.gov/edu/news/2016/3/16/how-many-decimals-of-pi-do-we-really-need/ uint256 constant PI = 3141592653589793238; uint256 constant TWO_PI = 2 * PI; uint256 constant PI_OVER_TWO = PI / 2; // The constant sine lookup table was generated by generate_trigonometry.py. We must use a constant // bytes array because constant arrays are not supported in Solidity. Each entry in the lookup // table is 4 bytes. Since we're using 32-bit parameters for the lookup table, we get a table size // of 2^(32/4) + 1 = 257, where the first and last entries are equivalent (hence the table size of // 256 defined above) uint8 constant entry_bytes = 4; // each entry in the lookup table is 4 bytes uint256 constant entry_mask = ((1 << (8 * entry_bytes)) - 1); // mask used to cast bytes32 -> lookup table entry bytes constant sin_table = hex"00_00_00_00_00_c9_0f_88_01_92_1d_20_02_5b_26_d7_03_24_2a_bf_03_ed_26_e6_04_b6_19_5d_05_7f_00_35_06_47_d9_7c_07_10_a3_45_07_d9_5b_9e_08_a2_00_9a_09_6a_90_49_0a_33_08_bc_0a_fb_68_05_0b_c3_ac_35_0c_8b_d3_5e_0d_53_db_92_0e_1b_c2_e4_0e_e3_87_66_0f_ab_27_2b_10_72_a0_48_11_39_f0_cf_12_01_16_d5_12_c8_10_6e_13_8e_db_b1_14_55_76_b1_15_1b_df_85_15_e2_14_44_16_a8_13_05_17_6d_d9_de_18_33_66_e8_18_f8_b8_3c_19_bd_cb_f3_1a_82_a0_25_1b_47_32_ef_1c_0b_82_6a_1c_cf_8c_b3_1d_93_4f_e5_1e_56_ca_1e_1f_19_f9_7b_1f_dc_dc_1b_20_9f_70_1c_21_61_b3_9f_22_23_a4_c5_22_e5_41_af_23_a6_88_7e_24_67_77_57_25_28_0c_5d_25_e8_45_b6_26_a8_21_85_27_67_9d_f4_28_26_b9_28_28_e5_71_4a_29_a3_c4_85_2a_61_b1_01_2b_1f_34_eb_2b_dc_4e_6f_2c_98_fb_ba_2d_55_3a_fb_2e_11_0a_62_2e_cc_68_1e_2f_87_52_62_30_41_c7_60_30_fb_c5_4d_31_b5_4a_5d_32_6e_54_c7_33_26_e2_c2_33_de_f2_87_34_96_82_4f_35_4d_90_56_36_04_1a_d9_36_ba_20_13_37_6f_9e_46_38_24_93_b0_38_d8_fe_93_39_8c_dd_32_3a_40_2d_d1_3a_f2_ee_b7_3b_a5_1e_29_3c_56_ba_70_3d_07_c1_d5_3d_b8_32_a5_3e_68_0b_2c_3f_17_49_b7_3f_c5_ec_97_40_73_f2_1d_41_21_58_9a_41_ce_1e_64_42_7a_41_d0_43_25_c1_35_43_d0_9a_ec_44_7a_cd_50_45_24_56_bc_45_cd_35_8f_46_75_68_27_47_1c_ec_e6_47_c3_c2_2e_48_69_e6_64_49_0f_57_ee_49_b4_15_33_4a_58_1c_9d_4a_fb_6c_97_4b_9e_03_8f_4c_3f_df_f3_4c_e1_00_34_4d_81_62_c3_4e_21_06_17_4e_bf_e8_a4_4f_5e_08_e2_4f_fb_65_4c_50_97_fc_5e_51_33_cc_94_51_ce_d4_6e_52_69_12_6e_53_02_85_17_53_9b_2a_ef_54_33_02_7d_54_ca_0a_4a_55_60_40_e2_55_f5_a4_d2_56_8a_34_a9_57_1d_ee_f9_57_b0_d2_55_58_42_dd_54_58_d4_0e_8c_59_64_64_97_59_f3_de_12_5a_82_79_99_5b_10_35_ce_5b_9d_11_53_5c_29_0a_cc_5c_b4_20_df_5d_3e_52_36_5d_c7_9d_7b_5e_50_01_5d_5e_d7_7c_89_5f_5e_0d_b2_5f_e3_b3_8d_60_68_6c_ce_60_ec_38_2f_61_6f_14_6b_61_f1_00_3e_62_71_fa_68_62_f2_01_ac_63_71_14_cc_63_ef_32_8f_64_6c_59_bf_64_e8_89_25_65_63_bf_91_65_dd_fb_d2_66_57_3c_bb_66_cf_81_1f_67_46_c7_d7_67_bd_0f_bc_68_32_57_aa_68_a6_9e_80_69_19_e3_1f_69_8c_24_6b_69_fd_61_4a_6a_6d_98_a3_6a_dc_c9_64_6b_4a_f2_78_6b_b8_12_d0_6c_24_29_5f_6c_8f_35_1b_6c_f9_34_fb_6d_62_27_f9_6d_ca_0d_14_6e_30_e3_49_6e_96_a9_9c_6e_fb_5f_11_6f_5f_02_b1_6f_c1_93_84_70_23_10_99_70_83_78_fe_70_e2_cb_c5_71_41_08_04_71_9e_2c_d1_71_fa_39_48_72_55_2c_84_72_af_05_a6_73_07_c3_cf_73_5f_66_25_73_b5_eb_d0_74_0b_53_fa_74_5f_9d_d0_74_b2_c8_83_75_04_d3_44_75_55_bd_4b_75_a5_85_ce_75_f4_2c_0a_76_41_af_3c_76_8e_0e_a5_76_d9_49_88_77_23_5f_2c_77_6c_4e_da_77_b4_17_df_77_fa_b9_88_78_40_33_28_78_84_84_13_78_c7_ab_a1_79_09_a9_2c_79_4a_7c_11_79_8a_23_b0_79_c8_9f_6d_7a_05_ee_ac_7a_42_10_d8_7a_7d_05_5a_7a_b6_cb_a3_7a_ef_63_23_7b_26_cb_4e_7b_5d_03_9d_7b_92_0b_88_7b_c5_e2_8f_7b_f8_88_2f_7c_29_fb_ed_7c_5a_3d_4f_7c_89_4b_dd_7c_b7_27_23_7c_e3_ce_b1_7d_0f_42_17_7d_39_80_eb_7d_62_8a_c5_7d_8a_5f_3f_7d_b0_fd_f7_7d_d6_66_8e_7d_fa_98_a7_7e_1d_93_e9_7e_3f_57_fe_7e_5f_e4_92_7e_7f_39_56_7e_9d_55_fb_7e_ba_3a_38_7e_d5_e5_c5_7e_f0_58_5f_7f_09_91_c3_7f_21_91_b3_7f_38_57_f5_7f_4d_e4_50_7f_62_36_8e_7f_75_4e_7f_7f_87_2b_f2_7f_97_ce_bc_7f_a7_36_b3_7f_b5_63_b2_7f_c2_55_95_7f_ce_0c_3d_7f_d8_87_8d_7f_e1_c7_6a_7f_e9_cb_bf_7f_f0_94_77_7f_f6_21_81_7f_fa_72_d0_7f_fd_88_59_7f_ff_62_15_7f_ff_ff_ff"; /** * @notice Return the sine of a value, specified in radians scaled by 1e18 * @dev This algorithm for converting sine only uses integer values, and it works by dividing the * circle into 30 bit angles, i.e. there are 1,073,741,824 (2^30) angle units, instead of the * standard 360 degrees (2pi radians). From there, we get an output in range -2,147,483,647 to * 2,147,483,647, (which is the max value of an int32) which is then converted back to the standard * range of -1 to 1, again scaled by 1e18 * @param _angle Angle to convert * @return Result scaled by 1e18 */ function sin(uint256 _angle) internal pure returns (int256) { unchecked { // Convert angle from from arbitrary radian value (range of 0 to 2pi) to the algorithm's range // of 0 to 1,073,741,824 _angle = (ANGLES_IN_CYCLE * (_angle % TWO_PI)) / TWO_PI; // Apply a mask on an integer to extract a certain number of bits, where angle is the integer // whose bits we want to get, the width is the width of the bits (in bits) we want to extract, // and the offset is the offset of the bits (in bits) we want to extract. The result is an // integer containing _width bits of _value starting at the offset bit uint256 interp = (_angle >> INTERP_OFFSET) & ((1 << INTERP_WIDTH) - 1); uint256 index = (_angle >> INDEX_OFFSET) & ((1 << INDEX_WIDTH) - 1); // The lookup table only contains data for one quadrant (since sin is symmetric around both // axes), so here we figure out which quadrant we're in, then we lookup the values in the // table then modify values accordingly bool is_odd_quadrant = (_angle & QUADRANT_LOW_MASK) == 0; bool is_negative_quadrant = (_angle & QUADRANT_HIGH_MASK) != 0; if (!is_odd_quadrant) { index = SINE_TABLE_SIZE - 1 - index; } bytes memory table = sin_table; // We are looking for two consecutive indices in our lookup table // Since EVM is left aligned, to read n bytes of data from idx i, we must read from `i * data_len` + `n` // therefore, to read two entries of size entry_bytes `index * entry_bytes` + `entry_bytes * 2` uint256 offset1_2 = (index + 2) * entry_bytes; // This following snippet will function for any entry_bytes <= 15 uint256 x1_2; assembly { // mload will grab one word worth of bytes (32), as that is the minimum size in EVM x1_2 := mload(add(table, offset1_2)) } // We now read the last two numbers of size entry_bytes from x1_2 // in example: entry_bytes = 4; x1_2 = 0x00...12345678abcdefgh // therefore: entry_mask = 0xFFFFFFFF // 0x00...12345678abcdefgh >> 8*4 = 0x00...12345678 // 0x00...12345678 & 0xFFFFFFFF = 0x12345678 uint256 x1 = (x1_2 >> (8 * entry_bytes)) & entry_mask; // 0x00...12345678abcdefgh & 0xFFFFFFFF = 0xabcdefgh uint256 x2 = x1_2 & entry_mask; // Approximate angle by interpolating in the table, accounting for the quadrant uint256 approximation = ((x2 - x1) * interp) >> INTERP_WIDTH; int256 sine = is_odd_quadrant ? int256(x1) + int256(approximation) : int256(x2) - int256(approximation); if (is_negative_quadrant) { sine *= -1; } // Bring result from the range of -2,147,483,647 through 2,147,483,647 to -1e18 through 1e18. // This can never overflow because sine is bounded by the above values return (sine * 1e18) / 2_147_483_647; } } /** * @notice Return the cosine of a value, specified in radians scaled by 1e18 * @dev This is identical to the sin() method, and just computes the value by delegating to the * sin() method using the identity cos(x) = sin(x + pi/2) * @dev Overflow when `angle + PI_OVER_TWO > type(uint256).max` is ok, results are still accurate * @param _angle Angle to convert * @return Result scaled by 1e18 */ function cos(uint256 _angle) internal pure returns (int256) { unchecked { return sin(_angle + PI_OVER_TWO); } } } // SPDX-License-Identifier: UNLICENSED pragma solidity >=0.6.0; import "../contracts/ShackledGenesis.sol"; contract XShackledGenesis { constructor() {} function xgenerateGenesisPiece(bytes32 tokenHash) external view returns (ShackledStructs.RenderParams memory, ShackledStructs.Metadata memory) { return ShackledGenesis.generateGenesisPiece(tokenHash); } function xgenerateGeometryAndColors(bytes32 tokenHash,int256[3] calldata objPosition) external view returns (ShackledGenesis.FacesVertsCols memory, ColorUtils.ColScheme memory, GeomUtils.GeomSpec memory, GeomUtils.GeomVars memory) { return ShackledGenesis.generateGeometryAndColors(tokenHash,objPosition); } function xcreate2dTris(bytes32 tokenHash,GeomUtils.GeomSpec calldata geomSpec) external view returns (int256[3][3][] memory, int256[] memory, int256[] memory) { return ShackledGenesis.create2dTris(tokenHash,geomSpec); } function xprismify(bytes32 tokenHash,int256[3][3][] calldata tris,int256[] calldata zFronts,int256[] calldata zBacks) external view returns (GeomUtils.GeomVars memory) { return ShackledGenesis.prismify(tokenHash,tris,zFronts,zBacks); } function xmakeFacesVertsCols(bytes32 tokenHash,int256[3][3][] calldata tris,GeomUtils.GeomVars calldata geomVars,ColorUtils.ColScheme calldata scheme,int256[3] calldata objPosition) external view returns (ShackledGenesis.FacesVertsCols memory) { return ShackledGenesis.makeFacesVertsCols(tokenHash,tris,geomVars,scheme,objPosition); } } contract XColorUtils { constructor() {} function xgetColForPrism(bytes32 tokenHash,int256[3][3] calldata triFront,ColorUtils.SubScheme calldata subScheme,int256[3][2] calldata extents) external view returns (int256[3][6] memory) { return ColorUtils.getColForPrism(tokenHash,triFront,subScheme,extents); } function xgetSchemeId(bytes32 tokenHash,int256[2][10] calldata weightings) external view returns (uint256) { return ColorUtils.getSchemeId(tokenHash,weightings); } function xcopyColor(int256[3] calldata c) external view returns (int256[3] memory) { return ColorUtils.copyColor(c); } function xgetScheme(bytes32 tokenHash,int256[3][3][] calldata tris) external view returns (ColorUtils.ColScheme memory) { return ColorUtils.getScheme(tokenHash,tris); } function xhsv2rgb(int256 h,int256 s,int256 v) external view returns (int256[3] memory) { return ColorUtils.hsv2rgb(h,s,v); } function xrgb2hsv(int256 r,int256 g,int256 b) external view returns (int256[3] memory) { return ColorUtils.rgb2hsv(r,g,b); } function xgetJiggle(int256[3] calldata jiggle,bytes32 randomSeed,int256 seedModifier) external view returns (int256[3] memory) { return ColorUtils.getJiggle(jiggle,randomSeed,seedModifier); } function xinArray(uint256[] calldata array,uint256 value) external view returns (bool) { return ColorUtils.inArray(array,value); } function xapplyDirHelp(int256[3][3] calldata triFront,int256[3] calldata colA,int256[3] calldata colB,int256 dirCode,bool isInnerGradient,int256[3][2] calldata extents) external view returns (int256[3][3] memory) { return ColorUtils.applyDirHelp(triFront,colA,colB,dirCode,isInnerGradient,extents); } function xgetOrderedPointIdxsInDir(int256[3][3] calldata tri,int256 dirCode) external view returns (uint256[3] memory) { return ColorUtils.getOrderedPointIdxsInDir(tri,dirCode); } function xinterpColHelp(int256[3] calldata colA,int256[3] calldata colB,int256 low,int256 high,int256 val) external view returns (int256[3] memory) { return ColorUtils.interpColHelp(colA,colB,low,high,val); } function xgetHighlightPrismIdxs(int256[3][3][] calldata tris,bytes32 tokenHash,uint256 nHighlights,int256 varCode,int256 selCode) external view returns (uint256[] memory) { return ColorUtils.getHighlightPrismIdxs(tris,tokenHash,nHighlights,varCode,selCode); } function xgetSortedTrisIdxs(int256[3][3][] calldata tris,uint256 nHighlights,int256 varCode,int256 selCode) external view returns (uint256[] memory) { return ColorUtils.getSortedTrisIdxs(tris,nHighlights,varCode,selCode); } } contract XGeomUtils { constructor() {} function xgenerateSpec(bytes32 tokenHash) external view returns (GeomUtils.GeomSpec memory) { return GeomUtils.generateSpec(tokenHash); } function xmakeAdjacentTriangles(bytes32 tokenHash,uint256 attemptNum,uint256 refIdx,GeomUtils.TriVars calldata triVars,GeomUtils.GeomSpec calldata geomSpec,int256 overrideSideIdx,int256 overrideScale,int256 depth) external view returns (GeomUtils.TriVars memory) { return GeomUtils.makeAdjacentTriangles(tokenHash,attemptNum,refIdx,triVars,geomSpec,overrideSideIdx,overrideScale,depth); } function xmakeVerticallyOppositeTriangles(bytes32 tokenHash,uint256 attemptNum,uint256 refIdx,GeomUtils.TriVars calldata triVars,GeomUtils.GeomSpec calldata geomSpec,int256 overrideSideIdx,int256 overrideScale,int256 depth) external view returns (GeomUtils.TriVars memory) { return GeomUtils.makeVerticallyOppositeTriangles(tokenHash,attemptNum,refIdx,triVars,geomSpec,overrideSideIdx,overrideScale,depth); } function xmakeTriVertOpp(int256[3][3] calldata refTri,GeomUtils.GeomSpec calldata geomSpec,int256 sideIdx,int256 scale) external view returns (int256[3][3] memory) { return GeomUtils.makeTriVertOpp(refTri,geomSpec,sideIdx,scale); } function xmakeTriAdjacent(bytes32 tokenHash,GeomUtils.GeomSpec calldata geomSpec,uint256 attemptNum,int256[3][3] calldata refTri,int256 sideIdx,int256 scale,int256 depth) external view returns (int256[3][3] memory) { return GeomUtils.makeTriAdjacent(tokenHash,geomSpec,attemptNum,refTri,sideIdx,scale,depth); } function xmakeTri(int256[3] calldata centre,int256 radius,int256 angle) external view returns (int256[3][3] memory) { return GeomUtils.makeTri(centre,radius,angle); } function xvector3RotateX(int256[3] calldata v,int256 deg) external view returns (int256[3] memory) { return GeomUtils.vector3RotateX(v,deg); } function xvector3RotateY(int256[3] calldata v,int256 deg) external view returns (int256[3] memory) { return GeomUtils.vector3RotateY(v,deg); } function xvector3RotateZ(int256[3] calldata v,int256 deg) external view returns (int256[3] memory) { return GeomUtils.vector3RotateZ(v,deg); } function xtrigHelper(int256 deg) external view returns (int256, int256) { return GeomUtils.trigHelper(deg); } function xgetCenterVec(int256[3][3] calldata tri) external view returns (int256[3] memory) { return GeomUtils.getCenterVec(tri); } function xgetRadiusLen(int256[3][3] calldata tri) external view returns (int256) { return GeomUtils.getRadiusLen(tri); } function xgetSideLen(int256[3][3] calldata tri) external view returns (int256) { return GeomUtils.getSideLen(tri); } function xgetPerpLen(int256[3][3] calldata tri) external view returns (int256) { return GeomUtils.getPerpLen(tri); } function xisTriPointingUp(int256[3][3] calldata tri) external view returns (bool) { return GeomUtils.isTriPointingUp(tri); } function xareTrisClose(int256[3][3] calldata tri1,int256[3][3] calldata tri2) external view returns (bool) { return GeomUtils.areTrisClose(tri1,tri2); } function xareTrisPointsOverlapping(int256[3][3] calldata tri1,int256[3][3] calldata tri2) external view returns (bool) { return GeomUtils.areTrisPointsOverlapping(tri1,tri2); } function xisPointInTri(int256[3][3] calldata tri,int256[3] calldata p) external view returns (bool) { return GeomUtils.isPointInTri(tri,p); } function xisTriOverlappingWithTris(int256[3][3] calldata tri,int256[3][3][] calldata tris,uint256 nextTriIdx) external view returns (bool) { return GeomUtils.isTriOverlappingWithTris(tri,tris,nextTriIdx); } function xisPointCloseToLine(int256[3] calldata p,int256[3] calldata l1,int256[3] calldata l2) external view returns (bool) { return GeomUtils.isPointCloseToLine(p,l1,l2); } function xisTrisPointsCloseToLines(int256[3][3] calldata tri,int256[3][3][] calldata tris,uint256 nextTriIdx) external view returns (bool) { return GeomUtils.isTrisPointsCloseToLines(tri,tris,nextTriIdx); } function xisTriLegal(int256[3][3] calldata tri,int256[3][3][] calldata tris,uint256 nextTriIdx,int256 minTriRad) external view returns (bool) { return GeomUtils.isTriLegal(tri,tris,nextTriIdx,minTriRad); } function xattemptToAddTri(int256[3][3] calldata tri,bytes32 tokenHash,GeomUtils.TriVars calldata triVars,GeomUtils.GeomSpec calldata geomSpec) external view returns (bool) { return GeomUtils.attemptToAddTri(tri,tokenHash,triVars,geomSpec); } function xtriRotHelp(int256 axis,int256[3][3] calldata tri,int256 rot) external view returns (int256[3][3] memory) { return GeomUtils.triRotHelp(axis,tri,rot); } function xtriBfHelp(int256 axis,int256[3][3][] calldata trisBack,int256[3][3][] calldata trisFront,int256 rot) external view returns (int256[3][3][] memory, int256[3][3][] memory) { return GeomUtils.triBfHelp(axis,trisBack,trisFront,rot); } function xgetExtents(int256[3][3][] calldata tris) external view returns (int256[3][2] memory) { return GeomUtils.getExtents(tris); } function xcalculateZ(int256[3][3] calldata tri,bytes32 tokenHash,uint256 nextTriIdx,GeomUtils.GeomSpec calldata geomSpec,bool front) external view returns (int256) { return GeomUtils.calculateZ(tri,tokenHash,nextTriIdx,geomSpec,front); } function xgetSpecId(bytes32 tokenHash,int256[2][7] calldata weightings) external view returns (uint256) { return GeomUtils.getSpecId(tokenHash,weightings); } function xrandN(bytes32 randomSeed,string calldata seedModifier,int256 min,int256 max) external view returns (int256) { return GeomUtils.randN(randomSeed,seedModifier,min,max); } function xclipTrisToLength(int256[3][3][] calldata arr,uint256 desiredLen) external view returns (int256[3][3][] memory) { return GeomUtils.clipTrisToLength(arr,desiredLen); } function xclipZsToLength(int256[] calldata arr,uint256 desiredLen) external view returns (int256[] memory) { return GeomUtils.clipZsToLength(arr,desiredLen); } function xcopyTri(int256[3][3] calldata tri) external view returns (int256[3][3] memory) { return GeomUtils.copyTri(tri); } function xcopyTris(int256[3][3][] calldata tris) external view returns (int256[3][3][] memory) { return GeomUtils.copyTris(tris); } } // SPDX-License-Identifier: UNLICENSED pragma solidity >=0.6.0; import "../contracts/ShackledMath.sol"; contract XShackledMath { constructor() {} function xmin(int256 a,int256 b) external pure returns (int256) { return ShackledMath.min(a,b); } function xmax(int256 a,int256 b) external pure returns (int256) { return ShackledMath.max(a,b); } function xmod(int256 n,int256 m) external pure returns (int256) { return ShackledMath.mod(n,m); } function xrandomIdx(bytes32 seedModifier,uint256 n,uint256 m) external pure returns (uint256[] memory) { return ShackledMath.randomIdx(seedModifier,n,m); } function xget2dArray(uint256 m,uint256 q,int256 value) external pure returns (int256[][] memory) { return ShackledMath.get2dArray(m,q,value); } function xabs(int256 x) external pure returns (int256) { return ShackledMath.abs(x); } function xsqrt(int256 y) external pure returns (int256) { return ShackledMath.sqrt(y); } function xhypot(int256 x,int256 y) external pure returns (int256) { return ShackledMath.hypot(x,y); } function xvector3Add(int256[3] calldata v1,int256[3] calldata v2) external pure returns (int256[3] memory) { return ShackledMath.vector3Add(v1,v2); } function xvector3Sub(int256[3] calldata v1,int256[3] calldata v2) external pure returns (int256[3] memory) { return ShackledMath.vector3Sub(v1,v2); } function xvector3MulScalar(int256[3] calldata v,int256 a) external pure returns (int256[3] memory) { return ShackledMath.vector3MulScalar(v,a); } function xvector3DivScalar(int256[3] calldata v,int256 a) external pure returns (int256[3] memory) { return ShackledMath.vector3DivScalar(v,a); } function xvector3Len(int256[3] calldata v) external pure returns (int256) { return ShackledMath.vector3Len(v); } function xvector3NormX(int256[3] calldata v,int256 fidelity) external pure returns (int256[3] memory) { return ShackledMath.vector3NormX(v,fidelity); } function xvector3Dot(int256[3] calldata v1,int256[3] calldata v2) external view returns (int256) { return ShackledMath.vector3Dot(v1,v2); } function xcrossProduct(int256[3] calldata v1,int256[3] calldata v2) external pure returns (int256[3] memory) { return ShackledMath.crossProduct(v1,v2); } function xvector12Lerp(int256[12] calldata v1,int256[12] calldata v2,int256 ir,int256 scaleFactor) external view returns (int256[12] memory) { return ShackledMath.vector12Lerp(v1,v2,ir,scaleFactor); } function xvector12Sub(int256[12] calldata v1,int256[12] calldata v2) external view returns (int256[12] memory) { return ShackledMath.vector12Sub(v1,v2); } function xmapRangeToRange(int256 num,int256 inMin,int256 inMax,int256 outMin,int256 outMax) external pure returns (int256) { return ShackledMath.mapRangeToRange(num,inMin,inMax,outMin,outMax); } } // SPDX-License-Identifier: UNLICENSED pragma solidity >=0.6.0; import "../contracts/ShackledStructs.sol"; contract XShackledStructs { constructor() {} } // SPDX-License-Identifier: UNLICENSED pragma solidity >=0.6.0; import "../contracts/Trigonometry.sol"; contract XTrigonometry { constructor() {} function xsin(uint256 _angle) external pure returns (int256) { return Trigonometry.sin(_angle); } function xcos(uint256 _angle) external pure returns (int256) { return Trigonometry.cos(_angle); } }
Return the sine of a value, specified in radians scaled by 1e18 This algorithm for converting sine only uses integer values, and it works by dividing the circle into 30 bit angles, i.e. there are 1,073,741,824 (2^30) angle units, instead of the standard 360 degrees (2pi radians). From there, we get an output in range -2,147,483,647 to 2,147,483,647, (which is the max value of an int32) which is then converted back to the standard range of -1 to 1, again scaled by 1e18 _angle Angle to convert return Result scaled by 1e18/ Convert angle from from arbitrary radian value (range of 0 to 2pi) to the algorithm's range of 0 to 1,073,741,824 Apply a mask on an integer to extract a certain number of bits, where angle is the integer whose bits we want to get, the width is the width of the bits (in bits) we want to extract, and the offset is the offset of the bits (in bits) we want to extract. The result is an integer containing _width bits of _value starting at the offset bit The lookup table only contains data for one quadrant (since sin is symmetric around both axes), so here we figure out which quadrant we're in, then we lookup the values in the table then modify values accordingly mload will grab one word worth of bytes (32), as that is the minimum size in EVM
function sin(uint256 _angle) internal pure returns (int256) { unchecked { _angle = (ANGLES_IN_CYCLE * (_angle % TWO_PI)) / TWO_PI; uint256 interp = (_angle >> INTERP_OFFSET) & ((1 << INTERP_WIDTH) - 1); uint256 index = (_angle >> INDEX_OFFSET) & ((1 << INDEX_WIDTH) - 1); bool is_odd_quadrant = (_angle & QUADRANT_LOW_MASK) == 0; bool is_negative_quadrant = (_angle & QUADRANT_HIGH_MASK) != 0; if (!is_odd_quadrant) { index = SINE_TABLE_SIZE - 1 - index; } bytes memory table = sin_table; assembly { x1_2 := mload(add(table, offset1_2)) } int256 sine = is_odd_quadrant ? int256(x1) + int256(approximation) : int256(x2) - int256(approximation); if (is_negative_quadrant) { sine *= -1; } } }
1,257,401
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; library EnumerableCardNFT { struct CardEntry { bytes32 _tokenId; uint256 _star; // 剩余粉尘 uint256 _tokenVal; uint256[] _cardType; // 词条 uint256[] _cardEntrys; string _uri; address _ownerAddress; } struct CardMap { // Storage of map keys and values CardEntry[] _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; } function _all(CardMap storage map) private view returns (uint256[] memory) { uint256[] memory tokenIds = new uint256[](map._entries.length); for (uint256 i = 0; i < map._entries.length; ++i) { tokenIds[i] = uint256(map._entries[i]._tokenId); } return tokenIds; } /** * @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( CardMap storage map, bytes32 tokenId, uint256 star, // 剩余粉尘 uint256 tokenVal, uint256[] memory cardType, // 词条 uint256[] memory cardEntrys, string memory uri, address ownerAddress ) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[tokenId]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push( CardEntry({ _tokenId: tokenId, _star: star, _tokenVal: tokenVal, _cardType: cardType, _cardEntrys: cardEntrys, _uri: uri, _ownerAddress: ownerAddress }) ); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[tokenId] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._tokenId = tokenId; map._entries[keyIndex - 1]._star = star; map._entries[keyIndex - 1]._tokenVal = tokenVal; map._entries[keyIndex - 1]._cardType = cardType; map._entries[keyIndex - 1]._cardEntrys = cardEntrys; map._entries[keyIndex - 1]._uri = uri; map._entries[keyIndex - 1]._ownerAddress = ownerAddress; return false; } } function _setTokenTo( CardMap storage map, bytes32 tokenId, address ownerAddress ) private returns (bool) { uint256 keyIndex = map._indexes[tokenId]; if (keyIndex == 0) { return false; } map._entries[keyIndex - 1]._ownerAddress = ownerAddress; return true; } /** * @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(CardMap 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. CardEntry 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._tokenId] = 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(CardMap 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(CardMap 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(CardMap storage map, uint256 index) private view returns ( bytes32, uint256, uint256, uint256[] memory, uint256[] memory, string memory, address ) { require( map._entries.length > index, "EnumerableMap: index out of bounds" ); CardEntry storage entry = map._entries[index]; return ( entry._tokenId, entry._star, entry._tokenVal, entry._cardType, entry._cardEntrys, entry._uri, entry._ownerAddress ); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(CardMap storage map, bytes32 tokenId) private view returns (CardEntry memory) { return _get(map, tokenId, "EnumerableMap: nonexistent key"); } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. */ function _get( CardMap storage map, bytes32 tokenId, string memory errorMessage ) private view returns (CardEntry memory) { uint256 keyIndex = map._indexes[tokenId]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]; // All indexes are 1-based } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. */ function _getOwnerAddress( CardMap storage map, bytes32 tokenId, string memory errorMessage ) private view returns (address) { uint256 keyIndex = map._indexes[tokenId]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return (map._entries[keyIndex - 1]._ownerAddress); // All indexes are 1-based } // UintToAddressMap // 主要的数据存储 struct UintToAddressMap { CardMap _inner; } function setTokenTo( UintToAddressMap storage map, uint256 tokenId, address toOwner ) internal returns (bool) { return _setTokenTo(map._inner, bytes32(tokenId), toOwner); } /** * @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 tokenId, uint256 star, // 剩余粉尘 uint256 tokenVal, uint256[] memory cardType, // 词条 uint256[] memory cardEntrys, string memory uri, address owner ) internal returns (bool) { return _set( map._inner, bytes32(tokenId), star, tokenVal, cardType, cardEntrys, uri, owner ); } /** * @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 tokenId) internal returns (bool) { return _remove(map._inner, bytes32(tokenId)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 tokenId) internal view returns (bool) { return _contains(map._inner, bytes32(tokenId)); } /** * @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, uint256, uint256, uint256[] memory, uint256[] memory, string memory, address ) { ( bytes32 _tokenId, uint256 _star, // 剩余粉尘 uint256 _tokenVal, uint256[] memory _cardType, // 词条 uint256[] memory _cardEntrys, string memory _uri, address _ownerAddress ) = _at(map._inner, index); return ( uint256(_tokenId), _star, _tokenVal, _cardType, _cardEntrys, _uri, _ownerAddress ); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get( UintToAddressMap storage map, uint256 key, string memory errorMessage ) internal view returns (CardEntry memory) { return _get(map._inner, bytes32(key), errorMessage); } function getOwner( UintToAddressMap storage map, uint256 tokenId, string memory errorMessage ) internal view returns (address) { return _getOwnerAddress(map._inner, bytes32(tokenId), errorMessage); } function allTokenIds(UintToAddressMap storage map) internal view returns (uint256[] memory) { return _all(map._inner); } }
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, uint256, uint256, uint256[] memory, uint256[] memory, string memory, address ) { ( bytes32 _tokenId, uint256 _star, uint256 _tokenVal, uint256[] memory _cardType, uint256[] memory _cardEntrys, string memory _uri, address _ownerAddress ) = _at(map._inner, index); return ( uint256(_tokenId), _star, _tokenVal, _cardType, _cardEntrys, _uri, _ownerAddress ); }
907,744
pragma solidity ^0.4.24; import "../openzeppelin-solidity-2.0.0/contracts/utils/Address.sol"; import "../openzeppelin-solidity-2.0.0/contracts/math/SafeMath.sol"; import "../openzeppelin-solidity-2.0.0/contracts/ownership/Ownable.sol"; import "../openzeppelin-solidity-2.0.0/contracts/introspection/ERC165Checker.sol"; contract SimpleRndOracle is Ownable { // 使用 Address 库合约 using Address for address; // 使用 SafeMath 库合约 using SafeMath for uint256; // 使用 ERC165Checker 库合约 using ERC165Checker for address; // 接受数据回调的函数选择器常量:bytes4(keccak256("receiveRnd(uint256)")) bytes4 public constant CALLBACK_FUNC_SIG = 0xa46d5843; // 记录所有请求服务的地址的数组 address[] private allRequesters; // 请求数据服务的地址到其请求计数的映射 mapping (address => uint256) private requesterNonce; // 请求数据服务的地址到其当前 requestID 的映射 mapping (address => uint256) private requestIDs; // requestID 到其结果接收地址的映射 mapping (uint256 => address) private callbackAddresses; // 此合约所信任的唯一的数据源地址 address private trustedDataSource; // 通知外部世界已经接收到一个数据请求(已成功注册一个数据请求) event requestRegistered(address indexed _addr, uint256 _requestID); /** * @dev 构造函数 * @param _trustedDataSource 合约信任的外部数据服务签名地址 */ constructor (address _trustedDataSource) public { trustedDataSource = _trustedDataSource; } /** * @dev 可接受捐赠的 fallback 函数 */ function() public payable { // empty fallback function to receive donation } /** * @dev 只允许 owner 调用的修改外部数据服务地址的函数 * @param _trustedDataSource 合约信任的外部数据服务签名地址 */ function changeTrustedDataSource(address _trustedDataSource) public onlyOwner { trustedDataSource = _trustedDataSource; } /** * @dev 只允许 owner 使用的销毁服务合约并取回捐赠的函数 */ function destoryOracle() public onlyOwner { selfdestruct(owner()); } /** * @dev 确保调用方是合约制定的信任数据源地址 */ modifier isTrustedDataSource() { require(trustedDataSource == msg.sender, "You are not trusted party."); _; } /** * @dev 供任意合约调用的注册随机数数据请求的函数 */ function registerRequest() external { // 需要注册的地址必须是合约地址 require(msg.sender.isContract(), "Only contract address can register requests."); // TODO: add implementation // 注意,这里应该检查接收数据的合约是否有必要的回调函数 } /** * @dev 供外部数据服务地址调用的返回数据函数 * @param _requestID 请求 ID * @param _rndNumber 返回的随机数 */ function feedbackRndData(uint256 _requestID, uint256 _rndNumber) external isTrustedDataSource { // TODO: add implementation } } /** * @dev 接收随机数返回的 callback 接口, */ interface IRndNumberReceiver { function receiveRnd(uint256) external; }
只允许 owner 使用的销毁服务合约并取回捐赠的函数/
function destoryOracle() public onlyOwner { selfdestruct(owner()); }
6,357,801
./partial_match/1/0x2F9d44C0A80B9E673b20c469846e46A870A73CA2/sources/Masterchef.sol
See {BEP20-approve}. Requirements: - `spender` cannot be the zero address./
function approve( address spender, uint256 amount ) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; }
2,816,261
// SPDX-License-Identifier: AGPL-3.0 // File contracts/dependencies/open-zeppelin/Context.sol pragma solidity 0.7.5; /* * @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 contracts/dependencies/open-zeppelin/IERC20.sol pragma solidity 0.7.5; /** * @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 contracts/dependencies/open-zeppelin/SafeMath.sol pragma solidity 0.7.5; /** * @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) { // 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. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File contracts/dependencies/open-zeppelin/Address.sol pragma solidity 0.7.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 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'); } } // File contracts/dependencies/open-zeppelin/ERC20.sol pragma solidity ^0.7.5; /** * @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 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string internal _name; string internal _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. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() virtual public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() virtual 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() virtual public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view 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); _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 { } } // File contracts/dependencies/open-zeppelin/Ownable.sol pragma solidity 0.7.5; /** * @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() { 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; } } // File contracts/interfaces/IGovernancePowerDelegationERC20.sol pragma solidity 0.7.5; interface IGovernancePowerDelegationERC20 { enum DelegationType { VOTING_POWER, PROPOSITION_POWER } /** * @dev Emitted when a user delegates governance power to another user. * * @param delegator The delegator. * @param delegatee The delegatee. * @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER). */ event DelegateChanged( address indexed delegator, address indexed delegatee, DelegationType delegationType ); /** * @dev Emitted when an action changes the delegated power of a user. * * @param user The user whose delegated power has changed. * @param amount The new amount of delegated power for the user. * @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER). */ event DelegatedPowerChanged(address indexed user, uint256 amount, DelegationType delegationType); /** * @dev Delegates a specific governance power to a delegatee. * * @param delegatee The address to delegate power to. * @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER). */ function delegateByType(address delegatee, DelegationType delegationType) external virtual; /** * @dev Delegates all governance powers to a delegatee. * * @param delegatee The user to which the power will be delegated. */ function delegate(address delegatee) external virtual; /** * @dev Returns the delegatee of an user. * * @param delegator The address of the delegator. * @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER). */ function getDelegateeByType(address delegator, DelegationType delegationType) external view virtual returns (address); /** * @dev Returns the current delegated power of a user. The current power is the power delegated * at the time of the last snapshot. * * @param user The user whose power to query. * @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER). */ function getPowerCurrent(address user, DelegationType delegationType) external view virtual returns (uint256); /** * @dev Returns the delegated power of a user at a certain block. * * @param user The user whose power to query. * @param blockNumber The block number at which to get the user's power. * @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER). */ function getPowerAtBlock( address user, uint256 blockNumber, DelegationType delegationType ) external view virtual returns (uint256); } // File contracts/governance/token/GovernancePowerDelegationERC20Mixin.sol pragma solidity 0.7.5; /** * @title GovernancePowerDelegationERC20Mixin * @author dYdX * * @dev Provides support for two types of governance powers, both endowed by the governance * token, and separately delegatable. Provides functions for delegation and for querying a user's * power at a certain block number. */ abstract contract GovernancePowerDelegationERC20Mixin is ERC20, IGovernancePowerDelegationERC20 { using SafeMath for uint256; // ============ Constants ============ /// @notice EIP-712 typehash for delegation by signature of a specific governance power type. bytes32 public constant DELEGATE_BY_TYPE_TYPEHASH = keccak256( 'DelegateByType(address delegatee,uint256 type,uint256 nonce,uint256 expiry)' ); /// @notice EIP-712 typehash for delegation by signature of all governance powers. bytes32 public constant DELEGATE_TYPEHASH = keccak256( 'Delegate(address delegatee,uint256 nonce,uint256 expiry)' ); // ============ Structs ============ /// @dev Snapshot of a value on a specific block, used to track voting power for proposals. struct Snapshot { uint128 blockNumber; uint128 value; } // ============ External Functions ============ /** * @notice Delegates a specific governance power to a delegatee. * * @param delegatee The address to delegate power to. * @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER). */ function delegateByType( address delegatee, DelegationType delegationType ) external override { _delegateByType(msg.sender, delegatee, delegationType); } /** * @notice Delegates all governance powers to a delegatee. * * @param delegatee The address to delegate power to. */ function delegate( address delegatee ) external override { _delegateByType(msg.sender, delegatee, DelegationType.VOTING_POWER); _delegateByType(msg.sender, delegatee, DelegationType.PROPOSITION_POWER); } /** * @notice Returns the delegatee of a user. * * @param delegator The address of the delegator. * @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER). */ function getDelegateeByType( address delegator, DelegationType delegationType ) external override view returns (address) { (, , mapping(address => address) storage delegates) = _getDelegationDataByType(delegationType); return _getDelegatee(delegator, delegates); } /** * @notice Returns the current power of a user. The current power is the power delegated * at the time of the last snapshot. * * @param user The user whose power to query. * @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER). */ function getPowerCurrent( address user, DelegationType delegationType ) external override view returns (uint256) { ( mapping(address => mapping(uint256 => Snapshot)) storage snapshots, mapping(address => uint256) storage snapshotsCounts, // delegates ) = _getDelegationDataByType(delegationType); return _searchByBlockNumber(snapshots, snapshotsCounts, user, block.number); } /** * @notice Returns the power of a user at a certain block. * * @param user The user whose power to query. * @param blockNumber The block number at which to get the user's power. * @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER). */ function getPowerAtBlock( address user, uint256 blockNumber, DelegationType delegationType ) external override view returns (uint256) { ( mapping(address => mapping(uint256 => Snapshot)) storage snapshots, mapping(address => uint256) storage snapshotsCounts, // delegates ) = _getDelegationDataByType(delegationType); return _searchByBlockNumber(snapshots, snapshotsCounts, user, blockNumber); } // ============ Internal Functions ============ /** * @dev Delegates one specific power to a delegatee. * * @param delegator The user whose power to delegate. * @param delegatee The address to delegate power to. * @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER). */ function _delegateByType( address delegator, address delegatee, DelegationType delegationType ) internal { require( delegatee != address(0), 'INVALID_DELEGATEE' ); (, , mapping(address => address) storage delegates) = _getDelegationDataByType(delegationType); uint256 delegatorBalance = balanceOf(delegator); address previousDelegatee = _getDelegatee(delegator, delegates); delegates[delegator] = delegatee; _moveDelegatesByType(previousDelegatee, delegatee, delegatorBalance, delegationType); emit DelegateChanged(delegator, delegatee, delegationType); } /** * @dev Moves power from one user to another. * * @param from The user from which delegated power is moved. * @param to The user that will receive the delegated power. * @param amount The amount of power to be moved. * @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER). */ function _moveDelegatesByType( address from, address to, uint256 amount, DelegationType delegationType ) internal { if (from == to) { return; } ( mapping(address => mapping(uint256 => Snapshot)) storage snapshots, mapping(address => uint256) storage snapshotsCounts, // delegates ) = _getDelegationDataByType(delegationType); if (from != address(0)) { uint256 previous = 0; uint256 fromSnapshotsCount = snapshotsCounts[from]; if (fromSnapshotsCount != 0) { previous = snapshots[from][fromSnapshotsCount - 1].value; } else { previous = balanceOf(from); } uint256 newAmount = previous.sub(amount); _writeSnapshot( snapshots, snapshotsCounts, from, uint128(newAmount) ); emit DelegatedPowerChanged(from, newAmount, delegationType); } if (to != address(0)) { uint256 previous = 0; uint256 toSnapshotsCount = snapshotsCounts[to]; if (toSnapshotsCount != 0) { previous = snapshots[to][toSnapshotsCount - 1].value; } else { previous = balanceOf(to); } uint256 newAmount = previous.add(amount); _writeSnapshot( snapshots, snapshotsCounts, to, uint128(newAmount) ); emit DelegatedPowerChanged(to, newAmount, delegationType); } } /** * @dev Searches for a balance snapshot by block number using binary search. * * @param snapshots The mapping of snapshots by user. * @param snapshotsCounts The mapping of the number of snapshots by user. * @param user The user for which the snapshot is being searched. * @param blockNumber The block number being searched. */ function _searchByBlockNumber( mapping(address => mapping(uint256 => Snapshot)) storage snapshots, mapping(address => uint256) storage snapshotsCounts, address user, uint256 blockNumber ) internal view returns (uint256) { require( blockNumber <= block.number, 'INVALID_BLOCK_NUMBER' ); uint256 snapshotsCount = snapshotsCounts[user]; if (snapshotsCount == 0) { return balanceOf(user); } // First check most recent balance if (snapshots[user][snapshotsCount - 1].blockNumber <= blockNumber) { return snapshots[user][snapshotsCount - 1].value; } // Next check implicit zero balance if (snapshots[user][0].blockNumber > blockNumber) { return 0; } uint256 lower = 0; uint256 upper = snapshotsCount - 1; while (upper > lower) { uint256 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Snapshot memory snapshot = snapshots[user][center]; if (snapshot.blockNumber == blockNumber) { return snapshot.value; } else if (snapshot.blockNumber < blockNumber) { lower = center; } else { upper = center - 1; } } return snapshots[user][lower].value; } /** * @dev Returns delegation data (snapshot, snapshotsCount, delegates) by delegation type. * * Note: This mixin contract does not itself define any storage, and we require the inheriting * contract to implement this method to provide access to the relevant mappings in storage. * This pattern was implemented by Aave for legacy reasons and we have decided not to change it. * * @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER). */ function _getDelegationDataByType( DelegationType delegationType ) internal virtual view returns ( mapping(address => mapping(uint256 => Snapshot)) storage, // snapshots mapping(address => uint256) storage, // snapshotsCount mapping(address => address) storage // delegates ); /** * @dev Writes a snapshot of a user's token/power balance. * * @param snapshots The mapping of snapshots by user. * @param snapshotsCounts The mapping of the number of snapshots by user. * @param owner The user whose power to snapshot. * @param newValue The new balance to snapshot at the current block. */ function _writeSnapshot( mapping(address => mapping(uint256 => Snapshot)) storage snapshots, mapping(address => uint256) storage snapshotsCounts, address owner, uint128 newValue ) internal { uint128 currentBlock = uint128(block.number); uint256 ownerSnapshotsCount = snapshotsCounts[owner]; mapping(uint256 => Snapshot) storage ownerSnapshots = snapshots[owner]; if ( ownerSnapshotsCount != 0 && ownerSnapshots[ownerSnapshotsCount - 1].blockNumber == currentBlock ) { // Doing multiple operations in the same block ownerSnapshots[ownerSnapshotsCount - 1].value = newValue; } else { ownerSnapshots[ownerSnapshotsCount] = Snapshot(currentBlock, newValue); snapshotsCounts[owner] = ownerSnapshotsCount + 1; } } /** * @dev Returns the delegatee of a user. If a user never performed any delegation, their * delegated address will be 0x0, in which case we return the user's own address. * * @param delegator The address of the user for which return the delegatee. * @param delegates The mapping of delegates for a particular type of delegation. */ function _getDelegatee( address delegator, mapping(address => address) storage delegates ) internal view returns (address) { address previousDelegatee = delegates[delegator]; if (previousDelegatee == address(0)) { return delegator; } return previousDelegatee; } } // File contracts/governance/token/DydxToken.sol pragma solidity 0.7.5; /** * @title DydxToken * @author dYdX * * @notice The dYdX governance token. */ contract DydxToken is GovernancePowerDelegationERC20Mixin, Ownable { using SafeMath for uint256; // ============ Events ============ /** * @dev Emitted when an address has been added to or removed from the token transfer allowlist. * * @param account Address that was added to or removed from the token transfer allowlist. * @param isAllowed True if the address was added to the allowlist, false if removed. */ event TransferAllowlistUpdated( address account, bool isAllowed ); /** * @dev Emitted when the transfer restriction timestamp is reassigned. * * @param transfersRestrictedBefore The new timestamp on and after which non-allowlisted * transfers may occur. */ event TransfersRestrictedBeforeUpdated( uint256 transfersRestrictedBefore ); // ============ Constants ============ string internal constant NAME = 'dYdX'; string internal constant SYMBOL = 'DYDX'; uint256 public constant INITIAL_SUPPLY = 1_000_000_000 ether; bytes32 public immutable DOMAIN_SEPARATOR; bytes public constant EIP712_VERSION = '1'; bytes32 public constant EIP712_DOMAIN = keccak256( 'EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)' ); bytes32 public constant PERMIT_TYPEHASH = keccak256( 'Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)' ); /// @notice Minimum time between mints. uint256 public constant MINT_MIN_INTERVAL = 365 days; /// @notice Cap on the percentage of the total supply that can be minted at each mint. /// Denominated in percentage points (units out of 100). uint256 public immutable MINT_MAX_PERCENT; /// @notice The timestamp on and after which the transfer restriction must be lifted. uint256 public immutable TRANSFER_RESTRICTION_LIFTED_NO_LATER_THAN; // ============ Storage ============ /// @dev Mapping from (owner) => (next valid nonce) for EIP-712 signatures. mapping(address => uint256) internal _nonces; mapping(address => mapping(uint256 => Snapshot)) public _votingSnapshots; mapping(address => uint256) public _votingSnapshotsCounts; mapping(address => address) public _votingDelegates; mapping(address => mapping(uint256 => Snapshot)) public _propositionPowerSnapshots; mapping(address => uint256) public _propositionPowerSnapshotsCounts; mapping(address => address) public _propositionPowerDelegates; /// @notice Snapshots of the token total supply, at each block where the total supply has changed. mapping(uint256 => Snapshot) public _totalSupplySnapshots; /// @notice Number of snapshots of the token total supply. uint256 public _totalSupplySnapshotsCount; /// @notice Allowlist of addresses which may send or receive tokens while transfers are /// otherwise restricted. mapping(address => bool) public _tokenTransferAllowlist; /// @notice The timestamp on and after which minting may occur. uint256 public _mintingRestrictedBefore; /// @notice The timestamp on and after which non-allowlisted transfers may occur. uint256 public _transfersRestrictedBefore; // ============ Constructor ============ /** * @notice Constructor. * * @param distributor The address which will receive the initial supply of tokens. * @param transfersRestrictedBefore Timestamp, before which transfers are restricted unless the * origin or destination address is in the allowlist. * @param transferRestrictionLiftedNoLaterThan Timestamp, which is the maximum timestamp that transfer * restrictions can be extended to. * @param mintingRestrictedBefore Timestamp, before which minting is not allowed. * @param mintMaxPercent Cap on the percentage of the total supply that can be minted at * each mint. */ constructor( address distributor, uint256 transfersRestrictedBefore, uint256 transferRestrictionLiftedNoLaterThan, uint256 mintingRestrictedBefore, uint256 mintMaxPercent ) ERC20(NAME, SYMBOL) { uint256 chainId; // solium-disable-next-line assembly { chainId := chainid() } DOMAIN_SEPARATOR = keccak256( abi.encode( EIP712_DOMAIN, keccak256(bytes(NAME)), keccak256(bytes(EIP712_VERSION)), chainId, address(this) ) ); // Validate and set parameters. require( transfersRestrictedBefore > block.timestamp, 'TRANSFERS_RESTRICTED_BEFORE_TOO_EARLY' ); require( transfersRestrictedBefore <= transferRestrictionLiftedNoLaterThan, 'MAX_TRANSFER_RESTRICTION_TOO_EARLY' ); require( mintingRestrictedBefore > block.timestamp, 'MINTING_RESTRICTED_BEFORE_TOO_EARLY' ); _transfersRestrictedBefore = transfersRestrictedBefore; TRANSFER_RESTRICTION_LIFTED_NO_LATER_THAN = transferRestrictionLiftedNoLaterThan; _mintingRestrictedBefore = mintingRestrictedBefore; MINT_MAX_PERCENT = mintMaxPercent; // Mint the initial supply. _mint(distributor, INITIAL_SUPPLY); emit TransfersRestrictedBeforeUpdated(transfersRestrictedBefore); } // ============ Other Functions ============ /** * @notice Adds addresses to the token transfer allowlist. Reverts if any of the addresses * already exist in the allowlist. Only callable by owner. * * @param addressesToAdd Addresses to add to the token transfer allowlist. */ function addToTokenTransferAllowlist( address[] calldata addressesToAdd ) external onlyOwner { for (uint256 i = 0; i < addressesToAdd.length; i++) { require( !_tokenTransferAllowlist[addressesToAdd[i]], 'ADDRESS_EXISTS_IN_TRANSFER_ALLOWLIST' ); _tokenTransferAllowlist[addressesToAdd[i]] = true; emit TransferAllowlistUpdated(addressesToAdd[i], true); } } /** * @notice Removes addresses from the token transfer allowlist. Reverts if any of the addresses * don't exist in the allowlist. Only callable by owner. * * @param addressesToRemove Addresses to remove from the token transfer allowlist. */ function removeFromTokenTransferAllowlist( address[] calldata addressesToRemove ) external onlyOwner { for (uint256 i = 0; i < addressesToRemove.length; i++) { require( _tokenTransferAllowlist[addressesToRemove[i]], 'ADDRESS_DOES_NOT_EXIST_IN_TRANSFER_ALLOWLIST' ); _tokenTransferAllowlist[addressesToRemove[i]] = false; emit TransferAllowlistUpdated(addressesToRemove[i], false); } } /** * @notice Updates the transfer restriction. Reverts if the transfer restriction has already passed, * the new transfer restriction is earlier than the previous one, or the new transfer restriction is * after the maximum transfer restriction. * * @param transfersRestrictedBefore The timestamp on and after which non-allowlisted transfers may occur. */ function updateTransfersRestrictedBefore( uint256 transfersRestrictedBefore ) external onlyOwner { uint256 previousTransfersRestrictedBefore = _transfersRestrictedBefore; require( block.timestamp < previousTransfersRestrictedBefore, 'TRANSFER_RESTRICTION_ENDED' ); require( previousTransfersRestrictedBefore <= transfersRestrictedBefore, 'NEW_TRANSFER_RESTRICTION_TOO_EARLY' ); require( transfersRestrictedBefore <= TRANSFER_RESTRICTION_LIFTED_NO_LATER_THAN, 'AFTER_MAX_TRANSFER_RESTRICTION' ); _transfersRestrictedBefore = transfersRestrictedBefore; emit TransfersRestrictedBeforeUpdated(transfersRestrictedBefore); } /** * @notice Mint new tokens. Only callable by owner after the required time period has elapsed. * * @param recipient The address to receive minted tokens. * @param amount The number of tokens to mint. */ function mint( address recipient, uint256 amount ) external onlyOwner { require( block.timestamp >= _mintingRestrictedBefore, 'MINT_TOO_EARLY' ); require( amount <= totalSupply().mul(MINT_MAX_PERCENT).div(100), 'MAX_MINT_EXCEEDED' ); // Update the next allowed minting time. _mintingRestrictedBefore = block.timestamp.add(MINT_MIN_INTERVAL); // Mint the amount. _mint(recipient, amount); } /** * @notice Implements the permit function as specified in EIP-2612. * * @param owner Address of the token owner. * @param spender Address of the spender. * @param value Amount of allowance. * @param deadline Expiration timestamp for the signature. * @param v Signature param. * @param r Signature param. * @param s Signature param. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external { require( owner != address(0), 'INVALID_OWNER' ); require( block.timestamp <= deadline, 'INVALID_EXPIRATION' ); uint256 currentValidNonce = _nonces[owner]; bytes32 digest = keccak256( abi.encodePacked( '\x19\x01', DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, currentValidNonce, deadline)) ) ); require( owner == ecrecover(digest, v, r, s), 'INVALID_SIGNATURE' ); _nonces[owner] = currentValidNonce.add(1); _approve(owner, spender, value); } /** * @notice Get the next valid nonce for EIP-712 signatures. * * This nonce should be used when signing for any of the following functions: * - permit() * - delegateByTypeBySig() * - delegateBySig() */ function nonces( address owner ) external view returns (uint256) { return _nonces[owner]; } function transfer( address recipient, uint256 amount ) public override returns (bool) { _requireTransferAllowed(_msgSender(), recipient); return super.transfer(recipient, amount); } function transferFrom( address sender, address recipient, uint256 amount ) public override returns (bool) { _requireTransferAllowed(sender, recipient); return super.transferFrom(sender, recipient, amount); } /** * @dev Override _mint() to write a snapshot whenever the total supply changes. * * These snapshots are intended to be used by the governance strategy. * * Note that the ERC20 _burn() function is never used. If desired, an official burn mechanism * could be implemented external to this contract, and accounted for in the governance strategy. */ function _mint( address account, uint256 amount ) internal override { super._mint(account, amount); uint256 snapshotsCount = _totalSupplySnapshotsCount; uint128 currentBlock = uint128(block.number); uint128 newValue = uint128(totalSupply()); // Note: There is no special case for the total supply being updated multiple times in the same // block. That should never occur. _totalSupplySnapshots[snapshotsCount] = Snapshot(currentBlock, newValue); _totalSupplySnapshotsCount = snapshotsCount.add(1); } function _requireTransferAllowed( address sender, address recipient ) view internal { // Compare against the constant `TRANSFER_RESTRICTION_LIFTED_NO_LATER_THAN` first // to avoid additional gas costs from reading from storage. if ( block.timestamp < TRANSFER_RESTRICTION_LIFTED_NO_LATER_THAN && block.timestamp < _transfersRestrictedBefore ) { // While transfers are restricted, a transfer is permitted if either the sender or the // recipient is on the allowlist. require( _tokenTransferAllowlist[sender] || _tokenTransferAllowlist[recipient], 'NON_ALLOWLIST_TRANSFERS_DISABLED' ); } } /** * @dev Writes a snapshot before any transfer operation, including: _transfer, _mint and _burn. * - On _transfer, it writes snapshots for both 'from' and 'to'. * - On _mint, only for `to`. * - On _burn, only for `from`. * * @param from The sender. * @param to The recipient. * @param amount The amount being transfered. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal override { address votingFromDelegatee = _getDelegatee(from, _votingDelegates); address votingToDelegatee = _getDelegatee(to, _votingDelegates); _moveDelegatesByType( votingFromDelegatee, votingToDelegatee, amount, DelegationType.VOTING_POWER ); address propPowerFromDelegatee = _getDelegatee(from, _propositionPowerDelegates); address propPowerToDelegatee = _getDelegatee(to, _propositionPowerDelegates); _moveDelegatesByType( propPowerFromDelegatee, propPowerToDelegatee, amount, DelegationType.PROPOSITION_POWER ); } function _getDelegationDataByType( DelegationType delegationType ) internal override view returns ( mapping(address => mapping(uint256 => Snapshot)) storage, // snapshots mapping(address => uint256) storage, // snapshots count mapping(address => address) storage // delegatees list ) { if (delegationType == DelegationType.VOTING_POWER) { return (_votingSnapshots, _votingSnapshotsCounts, _votingDelegates); } else { return ( _propositionPowerSnapshots, _propositionPowerSnapshotsCounts, _propositionPowerDelegates ); } } /** * @dev Delegates specific governance power from signer to `delegatee` using an EIP-712 signature. * * @param delegatee The address to delegate votes to. * @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER). * @param nonce The signer's nonce for EIP-712 signatures on this contract. * @param expiry Expiration timestamp for the signature. * @param v Signature param. * @param r Signature param. * @param s Signature param. */ function delegateByTypeBySig( address delegatee, DelegationType delegationType, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) public { bytes32 structHash = keccak256( abi.encode(DELEGATE_BY_TYPE_TYPEHASH, delegatee, uint256(delegationType), nonce, expiry) ); bytes32 digest = keccak256(abi.encodePacked('\x19\x01', DOMAIN_SEPARATOR, structHash)); address signer = ecrecover(digest, v, r, s); require( signer != address(0), 'INVALID_SIGNATURE' ); require( nonce == _nonces[signer]++, 'INVALID_NONCE' ); require( block.timestamp <= expiry, 'INVALID_EXPIRATION' ); _delegateByType(signer, delegatee, delegationType); } /** * @dev Delegates both governance powers from signer to `delegatee` using an EIP-712 signature. * * @param delegatee The address to delegate votes to. * @param nonce The signer's nonce for EIP-712 signatures on this contract. * @param expiry Expiration timestamp for the signature. * @param v Signature param. * @param r Signature param. * @param s Signature param. */ function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) public { bytes32 structHash = keccak256(abi.encode(DELEGATE_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked('\x19\x01', DOMAIN_SEPARATOR, structHash)); address signer = ecrecover(digest, v, r, s); require( signer != address(0), 'INVALID_SIGNATURE' ); require( nonce == _nonces[signer]++, 'INVALID_NONCE' ); require( block.timestamp <= expiry, 'INVALID_EXPIRATION' ); _delegateByType(signer, delegatee, DelegationType.VOTING_POWER); _delegateByType(signer, delegatee, DelegationType.PROPOSITION_POWER); } }
Removes addresses from the token transfer allowlist. Reverts if any of the addresses don't exist in the allowlist. Only callable by owner. addressesToRemove Addresses to remove from the token transfer allowlist./
function removeFromTokenTransferAllowlist( address[] calldata addressesToRemove ) external onlyOwner { for (uint256 i = 0; i < addressesToRemove.length; i++) { require( _tokenTransferAllowlist[addressesToRemove[i]], 'ADDRESS_DOES_NOT_EXIST_IN_TRANSFER_ALLOWLIST' ); _tokenTransferAllowlist[addressesToRemove[i]] = false; emit TransferAllowlistUpdated(addressesToRemove[i], false); } }
12,691,755
pragma solidity ^0.4.24; import "./CroupierRole.sol"; import "./SafeMath.sol"; contract BlackJack is CroupierRole { using SafeMath for *; uint constant THIS_DIVISOR = 1000; uint constant LOCK_RATIO = 2500; uint8 constant MAX_CUT_CARD = 15; mapping (address => uint256) private _balances; mapping (address => uint256) private _locked; mapping (address => uint256) private _last_apply_time; mapping (address => uint256) private _apply_amount; uint256 private _totalBalance = 0; uint256 public expireBlocks = 255; uint256 public statedPeriod = 30 minutes; uint256 public maxBet = 1 ether; uint256 public minBet = 0.1 ether; uint256 public feeRatio = 10; struct Bet { // gambler's address, 20 bytes. address gambler; // cut card position, the number range is 0-15. uint8 cutCard; // gambler's action list, per 4-bit representing an action, push-down storage. /** * action encoding rules: * 0 - reserved * 1 - Get * 2 - Hit * 3 - Stand * 4 - Double * 5 - Split * 6 - Insurance * 7 - Surrender * 8 - timeout */ bytes11 actions; // betting amount, 128 bits number is enough. uint128 amount; // block number of deal. uint128 dealBlockNumber; } mapping (uint256 => Bet) public bets; event Deposit(address indexed from, uint256 value); event Withdraw(address indexed from, uint256 value); event Apply(address indexed from, uint256 value); event Deal(uint256 indexed commit); event Settle(uint256 indexed commit); event Refund(uint256 indexed commit, uint128 amount); /** * @dev constructor */ constructor() public payable{ } /** * @dev Fallback function. It's another entry for deposit. While owner transfer ether to * this contract, it means increase the pot. */ function () public payable { if(!isOwner(msg.sender)){ _deposit(msg.sender, msg.value); } } /** * @dev Total number of tokens deposit by gamblers. * @return An uint256 representing the total amount owned by gamblers. */ function totalBalance() public view returns (uint256) { return _totalBalance; } /** * @dev Gets the balance of 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 Gets the locked value of specified address. * @param owner The address to query the locked amount of. * @return An uint256 representing the amount locked by the passed address. */ function lockedOf(address owner) public view returns (uint256) { return _locked[owner]; } /** * @dev Gets the last apply-withdraw time of specified address. * @param owner The address to query the last apply time of. * @return An uint256 representing the last apply time by the passed address. */ function lastApplyTime(address owner) public view returns (uint256) { return _last_apply_time[owner]; } /** * @dev Gets the apply-withdraw amount of specified address. * @param owner The address to query the apply amount of. * @return An uint256 representing the apply amount by the passed address. */ function applyAmount(address owner) public view returns (uint256) { return _apply_amount[owner]; } /** * @dev Deal action to start a new game with proxy mode, submit by croupier bot. * @param gambler gambler's address. * @param commit generated by keccak of 2 256-bit reveals, used to unique identify a deck. * gambler get commit but don't know the deck, dealer can't change the deck because of keccak is one-way irreversible. * @param amount 128-bit number of bet amount. * @param cutCard cut card position, gambler set it after receive the commit, so this process can guarantee fairness. * @param v * @param r * @param s v, r,s are components of ECDSA signature. Ensure the deck is signed by the gambler himself. */ function deal(address gambler, uint256 commit, uint128 amount, uint8 cutCard, uint8 v, bytes32 r, bytes32 s) public onlyCroupier { // verify signature. bytes32 signatureHash = keccak256(abi.encodePacked(amount, cutCard, commit)); require (gambler == ecrecover(signatureHash, v, r, s), "ECDSA signature is not valid."); _dealCore(gambler, commit, amount, cutCard); } /** * @dev Settle a deck by croupier. * @param reveal_1 Per byte of 1-26 bytes in reveal_1, reveal_2 representing a single card, 2 256-bit reveal combine a 52 cards deck. * Single card coding rules: * low 4-bit : 0001-1010 points of single card(1-10). * 5-6 bit : suit, 00 - spades, 01 - hearts, 10 - clubs, 11 - diamonds. * 7-8 bit : face cards, 00 - 10, 01 - Jack, 10 - Queen, 11 - King. * @param reveal_2 same as reveal_1. * @param actions gambler's actions. * @param win true - gambler win, false - lose. * @param amount winnings or losses amount. */ function settle(uint256 reveal_1, uint256 reveal_2, bytes11 actions, bool win, uint128 amount) public onlyCroupier { uint commit = uint(keccak256(abi.encodePacked(reveal_1, reveal_2))); Bet storage bet = bets[commit]; // verify commit. address gambler = bet.gambler; uint256 value = uint256(bet.amount); require(gambler != address(0) && value > 0, "Bet should be in 'active' state."); // verify bet is not expired. require(block.number > bet.dealBlockNumber, "Settle in the same block as placeBet, or before."); require(block.number <= uint256(bet.dealBlockNumber).add(expireBlocks), "Bet expired."); // Store actions. bet.actions = actions; bet.amount = 0; // unlock. uint256 lockValue = value.mul(LOCK_RATIO).div(THIS_DIVISOR); _locked[gambler] = _locked[gambler].sub(lockValue); // calculate balance. if(win) { _balances[gambler] = _balances[gambler].add(uint256(amount)); _totalBalance = _totalBalance.add(uint256(amount)); } else{ _balances[gambler] = _balances[gambler].sub(uint256(amount)); _totalBalance = _totalBalance.sub(uint256(amount)); } emit Settle(commit); } /** * @dev Refund a commit while it's expired. * @param commit which one bet been refunded. */ function refund(uint256 commit) public onlyCroupier { // Verify that bet is in 'active' state. Bet storage bet = bets[commit]; uint256 value = uint256(bet.amount); address gambler = bet.gambler; require(gambler != address(0) && value > 0, "Bet should be in 'active' state."); // Verify that bet has already expired. require (block.number > uint256(bet.dealBlockNumber).add(expireBlocks), "Bet not yet expired."); //unlock. uint256 lockValue = value.mul(LOCK_RATIO).div(THIS_DIVISOR); _locked[gambler] = _locked[gambler].sub(lockValue); bet.amount = 0; emit Refund(commit, uint128(value)); } /** * @dev Deposit in this contract. */ function deposit() public payable returns (bool){ _deposit(msg.sender, msg.value); return true; } /** * @dev apply for withdrawal. * @param amount the amount to apply for withdrawal, should be less than balance subtract locked. */ function apply(uint256 amount) public returns (bool){ require(amount <= _balances[msg.sender].sub(_locked[msg.sender]), "Not enough balance."); _last_apply_time[msg.sender] = now; _apply_amount[msg.sender] = amount; emit Apply(msg.sender, amount); return true; } /** * @dev Withdraw from this contract. Should apply at first, and withdraw after the stated apply period. */ function withdraw() public returns (bool){ require(_apply_amount[msg.sender] > 0, ""); require(now >= _last_apply_time[msg.sender].add(statedPeriod), ""); _withdraw(msg.sender, _apply_amount[msg.sender]); _apply_amount[msg.sender] = 0; return true; } /** * @dev Withdraw all by croupier in special cases, such as contract upgrade. * @param from The address to withdraw. */ function withdrawProxy(address from) public onlyCroupier returns(bool) { uint256 amount = balanceOf(from); _withdraw(from, amount); return true; } /** * @dev Deposit for a specified address, internal function. * @param from The address to deposit. * @param value The amount to be deposited. */ function _deposit(address from, uint256 value) internal { require(from != address(0), "Invalid address."); _balances[from] = _balances[from].add(value); _totalBalance = _totalBalance.add(value); emit Deposit(from, value); } /** * @dev Withdraw for a specified address, internal function. Due to house edge of blackjack can't cover the cost of gas, * platform charges 1% fee while withdraw. * @param from The address to withdraw. * @param value The amount to be withdrawed, should be less than balance subtract locked, and this contract can afford. */ function _withdraw(address from, uint256 value) internal { require(from != address(0), "Invalid address."); require(value <= _balances[from].sub(_locked[from]), "Not enough balance."); _balances[from] = _balances[from].sub(value); _totalBalance = _totalBalance.sub(value); uint256 fee = value.mul(feeRatio).div(THIS_DIVISOR); require(value.sub(fee) <= address(this).balance, "Can't afford."); from.transfer(value.sub(fee)); emit Withdraw(from, value); } /** * @dev Check uint256-uint128 type conversion is safe */ function _safeTypeConversion(uint256 a, uint128 b) internal pure returns(bool) { require(a == uint256(b) && uint128(a) == b, "Not safe type conversion."); return true; } /** * @dev Deal action core. */ function _dealCore(address gambler, uint256 commit, uint128 amount, uint8 cutCard) internal { // verify commit is "Clean". Bet storage bet = bets[commit]; require(bet.gambler == address(0), "Bet should be in 'clean' state."); // verify cut card position. require(cutCard <= MAX_CUT_CARD, "Cut card position is not valid."); //verify bet amount range. uint256 value = uint256(amount); require(_safeTypeConversion(value, amount), "Not safe type conversion"); require(value >= minBet && value <= maxBet, "Bet amount is out of range."); uint256 lockValue = value.mul(LOCK_RATIO).div(THIS_DIVISOR); require(lockValue <= balanceOf(gambler).sub(lockedOf(gambler)), "Balance is not enough for locked."); // Store bet parameters on blockchain. _locked[gambler] = _locked[gambler].add(lockValue); bet.gambler = gambler; bet.cutCard = cutCard; bet.amount = amount; bet.dealBlockNumber = uint128(block.number); emit Deal(commit); } /** * @dev Set max bet amount. * @param input in wei. */ function setMaxBet(uint256 input) public onlyOwner { maxBet = input; } /** * @dev Set min bet amount. * @param input in wei. */ function setMinBet(uint256 input) public onlyOwner { minBet = input; } /** * @dev Set fee ratio. * @param input new fee ratio, div by 1000. */ function setFeeRatio(uint256 input) public onlyOwner { feeRatio = input; } /** * @dev Set expiration blocks. * @param input new number of expiration blocks. */ function setExpireBlocks(uint256 input) public onlyOwner { expireBlocks = input; } /** * @dev Set stated apply period. * @param input new number of stated apply period. */ function setStatedPeriod(uint256 input) public onlyOwner { statedPeriod = input; } /** * @dev Withdraw funds to cover costs of operation. * @param amount should ensure the total balances of palyers. */ function withdrawFunds(uint256 amount) public onlyOwner { require(amount <= address(this).balance.sub(_totalBalance), "Not enough funds."); msg.sender.transfer(amount); } /** * @dev kill this contract while upgraded. */ function kill() public onlyOwner { require(_totalBalance == 0, "All of gambler's balances need to be withdrawn."); selfdestruct(msg.sender); } } pragma solidity ^0.4.24; import "./OwnerRole.sol"; contract CroupierRole is OwnerRole{ using Roles for Roles.Role; event CroupierAdded(address indexed account); event CroupierRemoved(address indexed account); Roles.Role private _croupiers; constructor () internal { } modifier onlyCroupier() { require(isCroupier(msg.sender)); _; } function isCroupier(address account) public view returns (bool) { return _croupiers.has(account); } function addCroupier(address account) public onlyOwner { _addCroupier(account); } function removeCroupier(address account) public onlyOwner { _removeCroupier(account); } function _addCroupier(address account) internal { _croupiers.add(account); emit CroupierAdded(account); } function _removeCroupier(address account) internal { _croupiers.remove(account); emit CroupierRemoved(account); } } pragma solidity ^0.4.24; import "./Roles.sol"; contract OwnerRole { using Roles for Roles.Role; event OwnerAdded(address indexed account); event OwnerRemoved(address indexed account); Roles.Role private _owners; constructor () internal { _addOwner(msg.sender); } modifier onlyOwner() { require(isOwner(msg.sender)); _; } function isOwner(address account) public view returns (bool) { return _owners.has(account); } function addOwner(address account) public onlyOwner { _addOwner(account); } function removeOwner(address account) public onlyOwner{ _removeOwner(account); } function _addOwner(address account) internal { _owners.add(account); emit OwnerAdded(account); } function _removeOwner(address account) internal { _owners.remove(account); emit OwnerRemoved(account); } } pragma solidity ^0.4.24; /** * @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(account != address(0)); require(!has(role, account)); role.bearer[account] = true; } /** * @dev remove an account's access to this role */ function remove(Role storage role, address account) internal { require(account != address(0)); require(has(role, account)); 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)); return role.bearer[account]; } } pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, 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 Integer division of two numbers 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 Subtracts two numbers, 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 Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two numbers 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; } } pragma solidity ^0.4.24; import "./CroupierRole.sol"; import "./SafeMath.sol"; contract BlackJack is CroupierRole { using SafeMath for *; uint constant THIS_DIVISOR = 1000; uint constant LOCK_RATIO = 2500; uint8 constant MAX_CUT_CARD = 15; mapping (address => uint256) private _balances; mapping (address => uint256) private _locked; mapping (address => uint256) private _last_apply_time; mapping (address => uint256) private _apply_amount; uint256 private _totalBalance = 0; uint256 public expireBlocks = 255; uint256 public statedPeriod = 30 minutes; uint256 public maxBet = 1 ether; uint256 public minBet = 0.1 ether; uint256 public feeRatio = 10; struct Bet { // gambler's address, 20 bytes. address gambler; // cut card position, the number range is 0-15. uint8 cutCard; // gambler's action list, per 4-bit representing an action, push-down storage. /** * action encoding rules: * 0 - reserved * 1 - Get * 2 - Hit * 3 - Stand * 4 - Double * 5 - Split * 6 - Insurance * 7 - Surrender * 8 - timeout */ bytes11 actions; // betting amount, 128 bits number is enough. uint128 amount; // block number of deal. uint128 dealBlockNumber; } mapping (uint256 => Bet) public bets; event Deposit(address indexed from, uint256 value); event Withdraw(address indexed from, uint256 value); event Apply(address indexed from, uint256 value); event Deal(uint256 indexed commit); event Settle(uint256 indexed commit); event Refund(uint256 indexed commit, uint128 amount); /** * @dev constructor */ constructor() public payable{ } /** * @dev Fallback function. It's another entry for deposit. While owner transfer ether to * this contract, it means increase the pot. */ function () public payable { if(!isOwner(msg.sender)){ _deposit(msg.sender, msg.value); } } /** * @dev Total number of tokens deposit by gamblers. * @return An uint256 representing the total amount owned by gamblers. */ function totalBalance() public view returns (uint256) { return _totalBalance; } /** * @dev Gets the balance of 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 Gets the locked value of specified address. * @param owner The address to query the locked amount of. * @return An uint256 representing the amount locked by the passed address. */ function lockedOf(address owner) public view returns (uint256) { return _locked[owner]; } /** * @dev Gets the last apply-withdraw time of specified address. * @param owner The address to query the last apply time of. * @return An uint256 representing the last apply time by the passed address. */ function lastApplyTime(address owner) public view returns (uint256) { return _last_apply_time[owner]; } /** * @dev Gets the apply-withdraw amount of specified address. * @param owner The address to query the apply amount of. * @return An uint256 representing the apply amount by the passed address. */ function applyAmount(address owner) public view returns (uint256) { return _apply_amount[owner]; } /** * @dev Deal action to start a new game with proxy mode, submit by croupier bot. * @param gambler gambler's address. * @param commit generated by keccak of 2 256-bit reveals, used to unique identify a deck. * gambler get commit but don't know the deck, dealer can't change the deck because of keccak is one-way irreversible. * @param amount 128-bit number of bet amount. * @param cutCard cut card position, gambler set it after receive the commit, so this process can guarantee fairness. * @param v * @param r * @param s v, r,s are components of ECDSA signature. Ensure the deck is signed by the gambler himself. */ function deal(address gambler, uint256 commit, uint128 amount, uint8 cutCard, uint8 v, bytes32 r, bytes32 s) public onlyCroupier { // verify signature. bytes32 signatureHash = keccak256(abi.encodePacked(amount, cutCard, commit)); require (gambler == ecrecover(signatureHash, v, r, s), "ECDSA signature is not valid."); _dealCore(gambler, commit, amount, cutCard); } /** * @dev Settle a deck by croupier. * @param reveal_1 Per byte of 1-26 bytes in reveal_1, reveal_2 representing a single card, 2 256-bit reveal combine a 52 cards deck. * Single card coding rules: * low 4-bit : 0001-1010 points of single card(1-10). * 5-6 bit : suit, 00 - spades, 01 - hearts, 10 - clubs, 11 - diamonds. * 7-8 bit : face cards, 00 - 10, 01 - Jack, 10 - Queen, 11 - King. * @param reveal_2 same as reveal_1. * @param actions gambler's actions. * @param win true - gambler win, false - lose. * @param amount winnings or losses amount. */ function settle(uint256 reveal_1, uint256 reveal_2, bytes11 actions, bool win, uint128 amount) public onlyCroupier { uint commit = uint(keccak256(abi.encodePacked(reveal_1, reveal_2))); Bet storage bet = bets[commit]; // verify commit. address gambler = bet.gambler; uint256 value = uint256(bet.amount); require(gambler != address(0) && value > 0, "Bet should be in 'active' state."); // verify bet is not expired. require(block.number > bet.dealBlockNumber, "Settle in the same block as placeBet, or before."); require(block.number <= uint256(bet.dealBlockNumber).add(expireBlocks), "Bet expired."); // Store actions. bet.actions = actions; bet.amount = 0; // unlock. uint256 lockValue = value.mul(LOCK_RATIO).div(THIS_DIVISOR); _locked[gambler] = _locked[gambler].sub(lockValue); // calculate balance. if(win) { _balances[gambler] = _balances[gambler].add(uint256(amount)); _totalBalance = _totalBalance.add(uint256(amount)); } else{ _balances[gambler] = _balances[gambler].sub(uint256(amount)); _totalBalance = _totalBalance.sub(uint256(amount)); } emit Settle(commit); } /** * @dev Refund a commit while it's expired. * @param commit which one bet been refunded. */ function refund(uint256 commit) public onlyCroupier { // Verify that bet is in 'active' state. Bet storage bet = bets[commit]; uint256 value = uint256(bet.amount); address gambler = bet.gambler; require(gambler != address(0) && value > 0, "Bet should be in 'active' state."); // Verify that bet has already expired. require (block.number > uint256(bet.dealBlockNumber).add(expireBlocks), "Bet not yet expired."); //unlock. uint256 lockValue = value.mul(LOCK_RATIO).div(THIS_DIVISOR); _locked[gambler] = _locked[gambler].sub(lockValue); bet.amount = 0; emit Refund(commit, uint128(value)); } /** * @dev Deposit in this contract. */ function deposit() public payable returns (bool){ _deposit(msg.sender, msg.value); return true; } /** * @dev apply for withdrawal. * @param amount the amount to apply for withdrawal, should be less than balance subtract locked. */ function apply(uint256 amount) public returns (bool){ require(amount <= _balances[msg.sender].sub(_locked[msg.sender]), "Not enough balance."); _last_apply_time[msg.sender] = now; _apply_amount[msg.sender] = amount; emit Apply(msg.sender, amount); return true; } /** * @dev Withdraw from this contract. Should apply at first, and withdraw after the stated apply period. */ function withdraw() public returns (bool){ require(_apply_amount[msg.sender] > 0, ""); require(now >= _last_apply_time[msg.sender].add(statedPeriod), ""); _withdraw(msg.sender, _apply_amount[msg.sender]); _apply_amount[msg.sender] = 0; return true; } /** * @dev Withdraw all by croupier in special cases, such as contract upgrade. * @param from The address to withdraw. */ function withdrawProxy(address from) public onlyCroupier returns(bool) { uint256 amount = balanceOf(from); _withdraw(from, amount); return true; } /** * @dev Deposit for a specified address, internal function. * @param from The address to deposit. * @param value The amount to be deposited. */ function _deposit(address from, uint256 value) internal { require(from != address(0), "Invalid address."); _balances[from] = _balances[from].add(value); _totalBalance = _totalBalance.add(value); emit Deposit(from, value); } /** * @dev Withdraw for a specified address, internal function. Due to house edge of blackjack can't cover the cost of gas, * platform charges 1% fee while withdraw. * @param from The address to withdraw. * @param value The amount to be withdrawed, should be less than balance subtract locked, and this contract can afford. */ function _withdraw(address from, uint256 value) internal { require(from != address(0), "Invalid address."); require(value <= _balances[from].sub(_locked[from]), "Not enough balance."); _balances[from] = _balances[from].sub(value); _totalBalance = _totalBalance.sub(value); uint256 fee = value.mul(feeRatio).div(THIS_DIVISOR); require(value.sub(fee) <= address(this).balance, "Can't afford."); from.transfer(value.sub(fee)); emit Withdraw(from, value); } /** * @dev Check uint256-uint128 type conversion is safe */ function _safeTypeConversion(uint256 a, uint128 b) internal pure returns(bool) { require(a == uint256(b) && uint128(a) == b, "Not safe type conversion."); return true; } /** * @dev Deal action core. */ function _dealCore(address gambler, uint256 commit, uint128 amount, uint8 cutCard) internal { // verify commit is "Clean". Bet storage bet = bets[commit]; require(bet.gambler == address(0), "Bet should be in 'clean' state."); // verify cut card position. require(cutCard <= MAX_CUT_CARD, "Cut card position is not valid."); //verify bet amount range. uint256 value = uint256(amount); require(_safeTypeConversion(value, amount), "Not safe type conversion"); require(value >= minBet && value <= maxBet, "Bet amount is out of range."); uint256 lockValue = value.mul(LOCK_RATIO).div(THIS_DIVISOR); require(lockValue <= balanceOf(gambler).sub(lockedOf(gambler)), "Balance is not enough for locked."); // Store bet parameters on blockchain. _locked[gambler] = _locked[gambler].add(lockValue); bet.gambler = gambler; bet.cutCard = cutCard; bet.amount = amount; bet.dealBlockNumber = uint128(block.number); emit Deal(commit); } /** * @dev Set max bet amount. * @param input in wei. */ function setMaxBet(uint256 input) public onlyOwner { maxBet = input; } /** * @dev Set min bet amount. * @param input in wei. */ function setMinBet(uint256 input) public onlyOwner { minBet = input; } /** * @dev Set fee ratio. * @param input new fee ratio, div by 1000. */ function setFeeRatio(uint256 input) public onlyOwner { feeRatio = input; } /** * @dev Set expiration blocks. * @param input new number of expiration blocks. */ function setExpireBlocks(uint256 input) public onlyOwner { expireBlocks = input; } /** * @dev Set stated apply period. * @param input new number of stated apply period. */ function setStatedPeriod(uint256 input) public onlyOwner { statedPeriod = input; } /** * @dev Withdraw funds to cover costs of operation. * @param amount should ensure the total balances of palyers. */ function withdrawFunds(uint256 amount) public onlyOwner { require(amount <= address(this).balance.sub(_totalBalance), "Not enough funds."); msg.sender.transfer(amount); } /** * @dev kill this contract while upgraded. */ function kill() public onlyOwner { require(_totalBalance == 0, "All of gambler's balances need to be withdrawn."); selfdestruct(msg.sender); } } pragma solidity ^0.4.24; import "./OwnerRole.sol"; contract CroupierRole is OwnerRole{ using Roles for Roles.Role; event CroupierAdded(address indexed account); event CroupierRemoved(address indexed account); Roles.Role private _croupiers; constructor () internal { } modifier onlyCroupier() { require(isCroupier(msg.sender)); _; } function isCroupier(address account) public view returns (bool) { return _croupiers.has(account); } function addCroupier(address account) public onlyOwner { _addCroupier(account); } function removeCroupier(address account) public onlyOwner { _removeCroupier(account); } function _addCroupier(address account) internal { _croupiers.add(account); emit CroupierAdded(account); } function _removeCroupier(address account) internal { _croupiers.remove(account); emit CroupierRemoved(account); } } pragma solidity ^0.4.24; import "./Roles.sol"; contract OwnerRole { using Roles for Roles.Role; event OwnerAdded(address indexed account); event OwnerRemoved(address indexed account); Roles.Role private _owners; constructor () internal { _addOwner(msg.sender); } modifier onlyOwner() { require(isOwner(msg.sender)); _; } function isOwner(address account) public view returns (bool) { return _owners.has(account); } function addOwner(address account) public onlyOwner { _addOwner(account); } function removeOwner(address account) public onlyOwner{ _removeOwner(account); } function _addOwner(address account) internal { _owners.add(account); emit OwnerAdded(account); } function _removeOwner(address account) internal { _owners.remove(account); emit OwnerRemoved(account); } } pragma solidity ^0.4.24; /** * @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(account != address(0)); require(!has(role, account)); role.bearer[account] = true; } /** * @dev remove an account's access to this role */ function remove(Role storage role, address account) internal { require(account != address(0)); require(has(role, account)); 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)); return role.bearer[account]; } } pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, 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 Integer division of two numbers 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 Subtracts two numbers, 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 Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two numbers 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; } } pragma solidity ^0.4.24; import "./CroupierRole.sol"; import "./SafeMath.sol"; contract BlackJack is CroupierRole { using SafeMath for *; uint constant THIS_DIVISOR = 1000; uint constant LOCK_RATIO = 2500; uint8 constant MAX_CUT_CARD = 15; mapping (address => uint256) private _balances; mapping (address => uint256) private _locked; mapping (address => uint256) private _last_apply_time; mapping (address => uint256) private _apply_amount; uint256 private _totalBalance = 0; uint256 public expireBlocks = 255; uint256 public statedPeriod = 30 minutes; uint256 public maxBet = 1 ether; uint256 public minBet = 0.1 ether; uint256 public feeRatio = 10; struct Bet { // gambler's address, 20 bytes. address gambler; // cut card position, the number range is 0-15. uint8 cutCard; // gambler's action list, per 4-bit representing an action, push-down storage. /** * action encoding rules: * 0 - reserved * 1 - Get * 2 - Hit * 3 - Stand * 4 - Double * 5 - Split * 6 - Insurance * 7 - Surrender * 8 - timeout */ bytes11 actions; // betting amount, 128 bits number is enough. uint128 amount; // block number of deal. uint128 dealBlockNumber; } mapping (uint256 => Bet) public bets; event Deposit(address indexed from, uint256 value); event Withdraw(address indexed from, uint256 value); event Apply(address indexed from, uint256 value); event Deal(uint256 indexed commit); event Settle(uint256 indexed commit); event Refund(uint256 indexed commit, uint128 amount); /** * @dev constructor */ constructor() public payable{ } /** * @dev Fallback function. It's another entry for deposit. While owner transfer ether to * this contract, it means increase the pot. */ function () public payable { if(!isOwner(msg.sender)){ _deposit(msg.sender, msg.value); } } /** * @dev Total number of tokens deposit by gamblers. * @return An uint256 representing the total amount owned by gamblers. */ function totalBalance() public view returns (uint256) { return _totalBalance; } /** * @dev Gets the balance of 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 Gets the locked value of specified address. * @param owner The address to query the locked amount of. * @return An uint256 representing the amount locked by the passed address. */ function lockedOf(address owner) public view returns (uint256) { return _locked[owner]; } /** * @dev Gets the last apply-withdraw time of specified address. * @param owner The address to query the last apply time of. * @return An uint256 representing the last apply time by the passed address. */ function lastApplyTime(address owner) public view returns (uint256) { return _last_apply_time[owner]; } /** * @dev Gets the apply-withdraw amount of specified address. * @param owner The address to query the apply amount of. * @return An uint256 representing the apply amount by the passed address. */ function applyAmount(address owner) public view returns (uint256) { return _apply_amount[owner]; } /** * @dev Deal action to start a new game with proxy mode, submit by croupier bot. * @param gambler gambler's address. * @param commit generated by keccak of 2 256-bit reveals, used to unique identify a deck. * gambler get commit but don't know the deck, dealer can't change the deck because of keccak is one-way irreversible. * @param amount 128-bit number of bet amount. * @param cutCard cut card position, gambler set it after receive the commit, so this process can guarantee fairness. * @param v * @param r * @param s v, r,s are components of ECDSA signature. Ensure the deck is signed by the gambler himself. */ function deal(address gambler, uint256 commit, uint128 amount, uint8 cutCard, uint8 v, bytes32 r, bytes32 s) public onlyCroupier { // verify signature. bytes32 signatureHash = keccak256(abi.encodePacked(amount, cutCard, commit)); require (gambler == ecrecover(signatureHash, v, r, s), "ECDSA signature is not valid."); _dealCore(gambler, commit, amount, cutCard); } /** * @dev Settle a deck by croupier. * @param reveal_1 Per byte of 1-26 bytes in reveal_1, reveal_2 representing a single card, 2 256-bit reveal combine a 52 cards deck. * Single card coding rules: * low 4-bit : 0001-1010 points of single card(1-10). * 5-6 bit : suit, 00 - spades, 01 - hearts, 10 - clubs, 11 - diamonds. * 7-8 bit : face cards, 00 - 10, 01 - Jack, 10 - Queen, 11 - King. * @param reveal_2 same as reveal_1. * @param actions gambler's actions. * @param win true - gambler win, false - lose. * @param amount winnings or losses amount. */ function settle(uint256 reveal_1, uint256 reveal_2, bytes11 actions, bool win, uint128 amount) public onlyCroupier { uint commit = uint(keccak256(abi.encodePacked(reveal_1, reveal_2))); Bet storage bet = bets[commit]; // verify commit. address gambler = bet.gambler; uint256 value = uint256(bet.amount); require(gambler != address(0) && value > 0, "Bet should be in 'active' state."); // verify bet is not expired. require(block.number > bet.dealBlockNumber, "Settle in the same block as placeBet, or before."); require(block.number <= uint256(bet.dealBlockNumber).add(expireBlocks), "Bet expired."); // Store actions. bet.actions = actions; bet.amount = 0; // unlock. uint256 lockValue = value.mul(LOCK_RATIO).div(THIS_DIVISOR); _locked[gambler] = _locked[gambler].sub(lockValue); // calculate balance. if(win) { _balances[gambler] = _balances[gambler].add(uint256(amount)); _totalBalance = _totalBalance.add(uint256(amount)); } else{ _balances[gambler] = _balances[gambler].sub(uint256(amount)); _totalBalance = _totalBalance.sub(uint256(amount)); } emit Settle(commit); } /** * @dev Refund a commit while it's expired. * @param commit which one bet been refunded. */ function refund(uint256 commit) public onlyCroupier { // Verify that bet is in 'active' state. Bet storage bet = bets[commit]; uint256 value = uint256(bet.amount); address gambler = bet.gambler; require(gambler != address(0) && value > 0, "Bet should be in 'active' state."); // Verify that bet has already expired. require (block.number > uint256(bet.dealBlockNumber).add(expireBlocks), "Bet not yet expired."); //unlock. uint256 lockValue = value.mul(LOCK_RATIO).div(THIS_DIVISOR); _locked[gambler] = _locked[gambler].sub(lockValue); bet.amount = 0; emit Refund(commit, uint128(value)); } /** * @dev Deposit in this contract. */ function deposit() public payable returns (bool){ _deposit(msg.sender, msg.value); return true; } /** * @dev apply for withdrawal. * @param amount the amount to apply for withdrawal, should be less than balance subtract locked. */ function apply(uint256 amount) public returns (bool){ require(amount <= _balances[msg.sender].sub(_locked[msg.sender]), "Not enough balance."); _last_apply_time[msg.sender] = now; _apply_amount[msg.sender] = amount; emit Apply(msg.sender, amount); return true; } /** * @dev Withdraw from this contract. Should apply at first, and withdraw after the stated apply period. */ function withdraw() public returns (bool){ require(_apply_amount[msg.sender] > 0, ""); require(now >= _last_apply_time[msg.sender].add(statedPeriod), ""); _withdraw(msg.sender, _apply_amount[msg.sender]); _apply_amount[msg.sender] = 0; return true; } /** * @dev Withdraw all by croupier in special cases, such as contract upgrade. * @param from The address to withdraw. */ function withdrawProxy(address from) public onlyCroupier returns(bool) { uint256 amount = balanceOf(from); _withdraw(from, amount); return true; } /** * @dev Deposit for a specified address, internal function. * @param from The address to deposit. * @param value The amount to be deposited. */ function _deposit(address from, uint256 value) internal { require(from != address(0), "Invalid address."); _balances[from] = _balances[from].add(value); _totalBalance = _totalBalance.add(value); emit Deposit(from, value); } /** * @dev Withdraw for a specified address, internal function. Due to house edge of blackjack can't cover the cost of gas, * platform charges 1% fee while withdraw. * @param from The address to withdraw. * @param value The amount to be withdrawed, should be less than balance subtract locked, and this contract can afford. */ function _withdraw(address from, uint256 value) internal { require(from != address(0), "Invalid address."); require(value <= _balances[from].sub(_locked[from]), "Not enough balance."); _balances[from] = _balances[from].sub(value); _totalBalance = _totalBalance.sub(value); uint256 fee = value.mul(feeRatio).div(THIS_DIVISOR); require(value.sub(fee) <= address(this).balance, "Can't afford."); from.transfer(value.sub(fee)); emit Withdraw(from, value); } /** * @dev Check uint256-uint128 type conversion is safe */ function _safeTypeConversion(uint256 a, uint128 b) internal pure returns(bool) { require(a == uint256(b) && uint128(a) == b, "Not safe type conversion."); return true; } /** * @dev Deal action core. */ function _dealCore(address gambler, uint256 commit, uint128 amount, uint8 cutCard) internal { // verify commit is "Clean". Bet storage bet = bets[commit]; require(bet.gambler == address(0), "Bet should be in 'clean' state."); // verify cut card position. require(cutCard <= MAX_CUT_CARD, "Cut card position is not valid."); //verify bet amount range. uint256 value = uint256(amount); require(_safeTypeConversion(value, amount), "Not safe type conversion"); require(value >= minBet && value <= maxBet, "Bet amount is out of range."); uint256 lockValue = value.mul(LOCK_RATIO).div(THIS_DIVISOR); require(lockValue <= balanceOf(gambler).sub(lockedOf(gambler)), "Balance is not enough for locked."); // Store bet parameters on blockchain. _locked[gambler] = _locked[gambler].add(lockValue); bet.gambler = gambler; bet.cutCard = cutCard; bet.amount = amount; bet.dealBlockNumber = uint128(block.number); emit Deal(commit); } /** * @dev Set max bet amount. * @param input in wei. */ function setMaxBet(uint256 input) public onlyOwner { maxBet = input; } /** * @dev Set min bet amount. * @param input in wei. */ function setMinBet(uint256 input) public onlyOwner { minBet = input; } /** * @dev Set fee ratio. * @param input new fee ratio, div by 1000. */ function setFeeRatio(uint256 input) public onlyOwner { feeRatio = input; } /** * @dev Set expiration blocks. * @param input new number of expiration blocks. */ function setExpireBlocks(uint256 input) public onlyOwner { expireBlocks = input; } /** * @dev Set stated apply period. * @param input new number of stated apply period. */ function setStatedPeriod(uint256 input) public onlyOwner { statedPeriod = input; } /** * @dev Withdraw funds to cover costs of operation. * @param amount should ensure the total balances of palyers. */ function withdrawFunds(uint256 amount) public onlyOwner { require(amount <= address(this).balance.sub(_totalBalance), "Not enough funds."); msg.sender.transfer(amount); } /** * @dev kill this contract while upgraded. */ function kill() public onlyOwner { require(_totalBalance == 0, "All of gambler's balances need to be withdrawn."); selfdestruct(msg.sender); } } pragma solidity ^0.4.24; import "./OwnerRole.sol"; contract CroupierRole is OwnerRole{ using Roles for Roles.Role; event CroupierAdded(address indexed account); event CroupierRemoved(address indexed account); Roles.Role private _croupiers; constructor () internal { } modifier onlyCroupier() { require(isCroupier(msg.sender)); _; } function isCroupier(address account) public view returns (bool) { return _croupiers.has(account); } function addCroupier(address account) public onlyOwner { _addCroupier(account); } function removeCroupier(address account) public onlyOwner { _removeCroupier(account); } function _addCroupier(address account) internal { _croupiers.add(account); emit CroupierAdded(account); } function _removeCroupier(address account) internal { _croupiers.remove(account); emit CroupierRemoved(account); } } pragma solidity ^0.4.24; import "./Roles.sol"; contract OwnerRole { using Roles for Roles.Role; event OwnerAdded(address indexed account); event OwnerRemoved(address indexed account); Roles.Role private _owners; constructor () internal { _addOwner(msg.sender); } modifier onlyOwner() { require(isOwner(msg.sender)); _; } function isOwner(address account) public view returns (bool) { return _owners.has(account); } function addOwner(address account) public onlyOwner { _addOwner(account); } function removeOwner(address account) public onlyOwner{ _removeOwner(account); } function _addOwner(address account) internal { _owners.add(account); emit OwnerAdded(account); } function _removeOwner(address account) internal { _owners.remove(account); emit OwnerRemoved(account); } } pragma solidity ^0.4.24; /** * @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(account != address(0)); require(!has(role, account)); role.bearer[account] = true; } /** * @dev remove an account's access to this role */ function remove(Role storage role, address account) internal { require(account != address(0)); require(has(role, account)); 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)); return role.bearer[account]; } } pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, 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 Integer division of two numbers 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 Subtracts two numbers, 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 Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two numbers 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; } }
Deal action core./ verify commit is "Clean". verify cut card position.verify bet amount range. Store bet parameters on blockchain.
function _dealCore(address gambler, uint256 commit, uint128 amount, uint8 cutCard) internal { Bet storage bet = bets[commit]; require(bet.gambler == address(0), "Bet should be in 'clean' state."); require(cutCard <= MAX_CUT_CARD, "Cut card position is not valid."); uint256 value = uint256(amount); require(_safeTypeConversion(value, amount), "Not safe type conversion"); require(value >= minBet && value <= maxBet, "Bet amount is out of range."); uint256 lockValue = value.mul(LOCK_RATIO).div(THIS_DIVISOR); require(lockValue <= balanceOf(gambler).sub(lockedOf(gambler)), "Balance is not enough for locked."); _locked[gambler] = _locked[gambler].add(lockValue); bet.gambler = gambler; bet.cutCard = cutCard; bet.amount = amount; bet.dealBlockNumber = uint128(block.number); emit Deal(commit); }
15,868,285
pragma solidity 0.4.26; import "../../ConverterBase.sol"; import "../../../token/interfaces/ISmartToken.sol"; /** * @dev Liquid Token Converter * * The liquid token converter is a specialized version of a converter that manages a liquid token. * * The converters govern a token with a single reserve and allow converting between the two. * Liquid tokens usually have fractional reserve (reserve ratio smaller than 100%). */ contract LiquidTokenConverter is ConverterBase { /** * @dev initializes a new LiquidTokenConverter instance * * @param _token liquid token governed by the converter * @param _registry address of a contract registry contract * @param _maxConversionFee maximum conversion fee, represented in ppm */ constructor( ISmartToken _token, IContractRegistry _registry, uint32 _maxConversionFee ) ConverterBase(_token, _registry, _maxConversionFee) public { } /** * @dev returns the converter type * * @return see the converter types in the the main contract doc */ function converterType() public pure returns (uint16) { return 0; } /** * @dev accepts ownership of the anchor after an ownership transfer * also activates the converter * can only be called by the contract owner * note that prior to version 28, you should use 'acceptTokenOwnership' instead */ function acceptAnchorOwnership() public ownerOnly { super.acceptAnchorOwnership(); emit Activation(converterType(), anchor, true); } /** * @dev defines the reserve token for the converter * can only be called by the owner while the converter is inactive and the * reserve wasn't defined yet * * @param _token address of the reserve token * @param _weight reserve weight, represented in ppm, 1-1000000 */ function addReserve(IERC20Token _token, uint32 _weight) public { // verify that the converter doesn't have a reserve yet require(reserveTokenCount() == 0, "ERR_INVALID_RESERVE_COUNT"); super.addReserve(_token, _weight); } /** * @dev returns the expected target amount of converting the source token to the * target token along with the fee * * @param _sourceToken contract address of the source token * @param _targetToken contract address of the target token * @param _amount amount of tokens received from the user * * @return expected target amount * @return expected fee */ function targetAmountAndFee(IERC20Token _sourceToken, IERC20Token _targetToken, uint256 _amount) public view returns (uint256, uint256) { if (_targetToken == ISmartToken(anchor) && reserves[_sourceToken].isSet) return purchaseTargetAmount(_amount); if (_sourceToken == ISmartToken(anchor) && reserves[_targetToken].isSet) return saleTargetAmount(_amount); // invalid input revert("ERR_INVALID_TOKEN"); } /** * @dev converts between the liquid token and its reserve * can only be called by the SovrynSwap network contract * * @param _sourceToken source ERC20 token * @param _targetToken target ERC20 token * @param _amount amount of tokens to convert (in units of the source token) * @param _trader address of the caller who executed the conversion * @param _beneficiary wallet to receive the conversion result * * @return amount of tokens received (in units of the target token) */ function doConvert(IERC20Token _sourceToken, IERC20Token _targetToken, uint256 _amount, address _trader, address _beneficiary) internal returns (uint256) { uint256 targetAmount; IERC20Token reserveToken; if (_targetToken == ISmartToken(anchor) && reserves[_sourceToken].isSet) { reserveToken = _sourceToken; targetAmount = buy(_amount, _trader, _beneficiary); } else if (_sourceToken == ISmartToken(anchor) && reserves[_targetToken].isSet) { reserveToken = _targetToken; targetAmount = sell(_amount, _trader, _beneficiary); } else { // invalid input revert("ERR_INVALID_TOKEN"); } // dispatch rate update for the liquid token uint256 totalSupply = ISmartToken(anchor).totalSupply(); uint32 reserveWeight = reserves[reserveToken].weight; emit TokenRateUpdate(anchor, reserveToken, reserveBalance(reserveToken).mul(WEIGHT_RESOLUTION), totalSupply.mul(reserveWeight)); return targetAmount; } /** * @dev returns the expected target amount of buying with a given amount of tokens * * @param _amount amount of reserve tokens to get the target amount for * * @return amount of liquid tokens that the user will receive * @return amount of liquid tokens that the user will pay as fee */ function purchaseTargetAmount(uint256 _amount) internal view active returns (uint256, uint256) { uint256 totalSupply = ISmartToken(anchor).totalSupply(); // if the current supply is zero, then return the input amount divided by the normalized reserve-weight if (totalSupply == 0) return (_amount.mul(WEIGHT_RESOLUTION).div(reserves[reserveToken].weight), 0); IERC20Token reserveToken = reserveTokens[0]; uint256 amount = ISovrynSwapFormula(addressOf(SOVRYNSWAP_FORMULA)).purchaseTargetAmount( totalSupply, reserveBalance(reserveToken), reserves[reserveToken].weight, _amount ); // return the amount minus the conversion fee and the conversion fee uint256 fee = calculateFee(amount); return (amount - fee, fee); } /** * @dev returns the expected target amount of selling a given amount of tokens * * @param _amount amount of liquid tokens to get the target amount for * * @return expected reserve tokens * @return expected fee */ function saleTargetAmount(uint256 _amount) internal view active returns (uint256, uint256) { uint256 totalSupply = ISmartToken(anchor).totalSupply(); IERC20Token reserveToken = reserveTokens[0]; // special case for selling the entire supply - return the entire reserve if (totalSupply == _amount) return (reserveBalance(reserveToken), 0); uint256 amount = ISovrynSwapFormula(addressOf(SOVRYNSWAP_FORMULA)).saleTargetAmount( totalSupply, reserveBalance(reserveToken), reserves[reserveToken].weight, _amount ); // return the amount minus the conversion fee and the conversion fee uint256 fee = calculateFee(amount); return (amount - fee, fee); } /** * @dev buys the liquid token by depositing in its reserve * * @param _amount amount of reserve token to buy the token for * @param _trader address of the caller who executed the conversion * @param _beneficiary wallet to receive the conversion result * * @return amount of liquid tokens received */ function buy(uint256 _amount, address _trader, address _beneficiary) internal returns (uint256) { // get expected target amount and fee (uint256 amount, uint256 fee) = purchaseTargetAmount(_amount); // ensure the trade gives something in return require(amount != 0, "ERR_ZERO_TARGET_AMOUNT"); IERC20Token reserveToken = reserveTokens[0]; // ensure that the input amount was already deposited if (reserveToken == ETH_RESERVE_ADDRESS) require(msg.value == _amount, "ERR_ETH_AMOUNT_MISMATCH"); else require(msg.value == 0 && reserveToken.balanceOf(this).sub(reserveBalance(reserveToken)) >= _amount, "ERR_INVALID_AMOUNT"); // sync the reserve balance syncReserveBalance(reserveToken); // issue new funds to the beneficiary in the liquid token ISmartToken(anchor).issue(_beneficiary, amount); // dispatch the conversion event dispatchConversionEvent(reserveToken, ISmartToken(anchor), _trader, _amount, amount, fee); return amount; } /** * @dev sells the liquid token by withdrawing from its reserve * * @param _amount amount of liquid tokens to sell * @param _trader address of the caller who executed the conversion * @param _beneficiary wallet to receive the conversion result * * @return amount of reserve tokens received */ function sell(uint256 _amount, address _trader, address _beneficiary) internal returns (uint256) { // ensure that the input amount was already deposited require(_amount <= ISmartToken(anchor).balanceOf(this), "ERR_INVALID_AMOUNT"); // get expected target amount and fee (uint256 amount, uint256 fee) = saleTargetAmount(_amount); // ensure the trade gives something in return require(amount != 0, "ERR_ZERO_TARGET_AMOUNT"); IERC20Token reserveToken = reserveTokens[0]; // ensure that the trade will only deplete the reserve balance if the total supply is depleted as well uint256 tokenSupply = ISmartToken(anchor).totalSupply(); uint256 rsvBalance = reserveBalance(reserveToken); assert(amount < rsvBalance || (amount == rsvBalance && _amount == tokenSupply)); // destroy the tokens from the converter balance in the liquid token ISmartToken(anchor).destroy(this, _amount); // update the reserve balance reserves[reserveToken].balance = reserves[reserveToken].balance.sub(amount); // transfer funds to the beneficiary in the reserve token if (reserveToken == ETH_RESERVE_ADDRESS) _beneficiary.transfer(amount); else safeTransfer(reserveToken, _beneficiary, amount); // dispatch the conversion event dispatchConversionEvent(ISmartToken(anchor), reserveToken, _trader, _amount, amount, fee); return amount; } }
defines the reserve token for the converter can only be called by the owner while the converter is inactive and the reserve wasn't defined yet _token address of the reserve token _weight reserve weight, represented in ppm, 1-1000000/ verify that the converter doesn't have a reserve yet
function addReserve(IERC20Token _token, uint32 _weight) public { require(reserveTokenCount() == 0, "ERR_INVALID_RESERVE_COUNT"); super.addReserve(_token, _weight); }
12,951,862
./full_match/1/0xF66B8c3d9933a8f9362B4D30f2b918CC97E5a31E/sources/home/bugman/Projects/idle-governance/contracts/IdleController.sol
Add markets to idleMarkets, allowing them to earn IDLE in the flywheel idleTokens The addresses of the markets to add/
function _addIdleMarkets(address[] memory idleTokens) public { require(adminOrInitializing(), "only admin can change idle rate"); for (uint256 i = 0; i < idleTokens.length; i++) { _addIdleMarketInternal(idleTokens[i]); } refreshIdleSpeedsInternal(); }
4,845,731
./full_match/5/0xD579767E232A56AFbc1EB0863A1511a175d94D65/sources/contracts/strategies/Default.sol
Unstake tokens from the contract
function unstakeTokens(uint256 amount, uint256 proposalId) external { require(amount > 0, "ChaiLabsStrategy: Amount must be greater than zero"); require(votingStake[msg.sender][proposalId] >= amount, "ChaiLabsStrategy: Not enough staked tokens"); token.safeTransfer(msg.sender, amount); votingStake[msg.sender][proposalId] -= amount; }
1,856,544
pragma solidity ^0.4.23; import "openzeppelin-solidity/contracts/ownership/HasNoEther.sol"; import "openzeppelin-solidity/contracts/ownership/HasNoTokens.sol"; import "openzeppelin-solidity/contracts/ownership/Claimable.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "./TrueUSD.sol"; // This contract allows us to split ownership of the TrueUSD contract (and TrueUSD's Registry) // into two addresses. One, called the "owner" address, has unfettered control of the TrueUSD contract - // it can mint new tokens, transfer ownership of the contract, etc. However to make // extra sure that TrueUSD is never compromised, this owner key will not be used in // day-to-day operations, allowing it to be stored at a heightened level of security. // Instead, the owner appoints an "admin" address. The admin will be used in everyday operation, // but is restricted to performing only a few tasks like updating the Registry and minting // new tokens. Additionally, the admin can // only mint new tokens by calling a pair of functions - `requestMint` // and `finalizeMint` - with (roughly) 24 hours in between the two calls. // This allows us to watch the blockchain and if we discover the admin has been // compromised and there are unauthorized operations underway, we can use the owner key // to replace the admin. Requests initiated by an admin that has since been deposed // cannot be finalized. contract TimeLockedController is HasNoEther, HasNoTokens, Claimable { using SafeMath for uint256; struct MintOperation { address to; uint256 value; address admin; uint256 releaseTimestamp; } uint256 public mintDelay = 1 days; address public admin; TrueUSD public trueUSD; MintOperation[] public mintOperations; modifier onlyAdminOrOwner() { require(msg.sender == admin || msg.sender == owner,"must be admin or owner"); _; } event RequestMint(address indexed to, address indexed admin, uint256 value, uint256 releaseTimestamp, uint256 opIndex); event TransferChild(address indexed child, address indexed newOwner); event RequestReclaimContract(address indexed other); event SetTrueUSD(TrueUSD newContract); event TransferAdminship(address indexed previousAdmin, address indexed newAdmin); event ChangeMintDelay(uint256 newDelay); event RevokeMint(uint256 opIndex); constructor() public { admin = msg.sender; } // admin initiates a request to mint _value TrueUSD for account _to function requestMint(address _to, uint256 _value) public onlyAdminOrOwner { uint256 releaseTimestamp = block.timestamp; if (msg.sender != owner) { releaseTimestamp = releaseTimestamp.add(mintDelay); } MintOperation memory op = MintOperation(_to, _value, admin, releaseTimestamp); emit RequestMint(_to, admin, _value, releaseTimestamp, mintOperations.length); mintOperations.push(op); } // after a day, admin finalizes mint request by providing the // index of the request (visible in the RequestMint event accompanying the original request) function finalizeMint(uint256 _index) public onlyAdminOrOwner { MintOperation memory op = mintOperations[_index]; require(op.admin == admin,"admin revoked"); //checks that the requester's adminship has not been revoked require(op.releaseTimestamp <= block.timestamp,"not enough time elapsed"); //checks that enough time has elapsed address to = op.to; uint256 value = op.value; delete mintOperations[_index]; trueUSD.forceMint(to, value); } function revokeMint(uint256 _index) public onlyOwner { delete mintOperations[_index]; emit RevokeMint(_index); } // Transfer ownership of _child to _newOwner // Can be used e.g. to upgrade this TimeLockedController contract. function transferChild(Ownable _child, address _newOwner) public onlyOwner { emit TransferChild(_child, _newOwner); _child.transferOwnership(_newOwner); } // Transfer ownership of a contract from trueUSD // to this TimeLockedController. Can be used e.g. to reclaim balance sheet // in order to transfer it to an upgraded TrueUSD contract. function requestReclaimContract(Ownable _other) public onlyOwner { emit RequestReclaimContract(_other); trueUSD.reclaimContract(_other); } function requestReclaimEther() public onlyOwner { trueUSD.reclaimEther(owner); } function requestReclaimToken(ERC20Basic _token) public onlyOwner { trueUSD.reclaimToken(_token, owner); } function requestSettleAllBurns() public onlyAdminOrOwner { trueUSD.settleAllBurns(); } function requestTotalDebt() public onlyAdminOrOwner view returns (uint256) { return trueUSD.totalDebt(); } function setTokenPrice(uint256 _price) public onlyAdminOrOwner { trueUSD.setTokenPrice(_price); } // Change the minimum and maximum amounts that TrueUSD users can // burn to newMin and newMax function setBurnBounds(uint256 _min, uint256 _max) public onlyAdminOrOwner { trueUSD.setBurnBounds(_min, _max); } // Change the transaction fees charged on transfer/mint/burn function changeStakingFees(uint256 _transferFeeNumerator, uint256 _transferFeeDenominator, uint256 _mintFeeNumerator, uint256 _mintFeeDenominator, uint256 _mintFeeFlat, uint256 _burnFeeNumerator, uint256 _burnFeeDenominator, uint256 _burnFeeFlat) public onlyOwner { trueUSD.changeStakingFees(_transferFeeNumerator, _transferFeeDenominator, _mintFeeNumerator, _mintFeeDenominator, _mintFeeFlat, _burnFeeNumerator, _burnFeeDenominator, _burnFeeFlat); } // Change the recipient of staking fees to newStaker function changeStaker(address _newStaker) public onlyOwner { trueUSD.changeStaker(_newStaker); } // Future BurnableToken calls to trueUSD will be delegated to _delegate function delegateToNewContract(DelegateBurnable _delegate, Ownable _balanceSheet, Ownable _alowanceSheet, Ownable _burnQueue)public onlyOwner{ //initiate transfer ownership of storage contracts from trueUSD contract requestReclaimContract(_balanceSheet); requestReclaimContract(_alowanceSheet); requestReclaimContract(_burnQueue); //claim ownership of storage contract issueClaimOwnership(_balanceSheet); issueClaimOwnership(_alowanceSheet); issueClaimOwnership(_burnQueue); //initiate transfer ownership of storage contracts to new delegate contract transferChild(_balanceSheet,_delegate); transferChild(_alowanceSheet,_delegate); transferChild(_burnQueue,_delegate); //call to claim the storage contract with the new delegate contract require(address(_delegate).call(bytes4(keccak256("setBalanceSheet(address)")), _balanceSheet)); require(address(_delegate).call(bytes4(keccak256("setAllowanceSheet(address)")), _alowanceSheet)); require(address(_delegate).call(bytes4(keccak256("setBurnQueue(address)")), _burnQueue)); trueUSD.delegateToNewContract(_delegate); } // Incoming delegate* calls from _source will be accepted by trueUSD function setDelegatedFrom(address _source) public onlyOwner { trueUSD.setDelegatedFrom(_source); } // Update this contract's trueUSD pointer to newContract (e.g. if the // contract is upgraded) function setTrueUSD(TrueUSD _newContract) public onlyOwner { emit SetTrueUSD(_newContract); trueUSD = _newContract; } // change trueUSD's name and symbol function changeTokenName(string _name, string _symbol) public onlyOwner { trueUSD.changeTokenName(_name, _symbol); } // Replace the current admin with newAdmin. This should be rare (e.g. if admin // is compromised), and will invalidate all pending mint operations (including // any the owner may have made and not yet finalized) function transferAdminship(address _newAdmin) public onlyOwner { require(_newAdmin != address(0),"new admin cannot be 0x0"); emit TransferAdminship(admin, _newAdmin); admin = _newAdmin; } // Swap out TrueUSD's permissions registry function setRegistry(Registry _registry) onlyOwner public { trueUSD.setRegistry(_registry); } // Update the registry function setAttribute(Registry _registry, address _who, string _attribute, uint256 _value, string _notes) public onlyAdminOrOwner { _registry.setAttribute(_who, _attribute, _value, _notes); } // Claim ownership of an arbitrary Claimable contract function issueClaimOwnership(address _other) public onlyAdminOrOwner { Claimable other = Claimable(_other); other.claimOwnership(); } // Change the delay imposed on admin-initiated mint requests function changeMintDelay(uint256 _newDelay) public onlyOwner { mintDelay = _newDelay; emit ChangeMintDelay(_newDelay); } }
Transfer ownership of _child to _newOwner Can be used e.g. to upgrade this TimeLockedController contract.
function transferChild(Ownable _child, address _newOwner) public onlyOwner { emit TransferChild(_child, _newOwner); _child.transferOwnership(_newOwner); }
5,345,378
./partial_match/5/0xF8244d1177A6f93AAf3770Af9256aC4BF56c869f/sources/MurAllNFTL2.sol
If you're attempting to bring metadata associated with token from L2 to L1, you must implement this method, to be invoked when minting token back on L1, during exit/ This function should decode metadata obtained from L2 and attempt to set it for this `tokenId` Following is just a default implementation, feel free to define your own encoding/ decoding scheme for L2 -> L1 token metadata transfer
function setTokenMetadata(uint256 tokenId, bytes memory data) internal virtual { (bytes32 dataHash, address artist, uint256 name, uint256 metadata) = abi.decode( data, (bytes32, address, uint256, uint256) ); ArtWork memory _artwork = ArtWork(dataHash, artist, name, metadata); artworks[tokenId] = _artwork; }
16,873,862
./full_match/420/0xbb19276AcBC448dC4DD7161d69D33fF2e854a7a0/sources/contracts/coordinape-protocol/contracts/cosoul/CoSoul.sol
Get Base URI used for computing {tokenURI}./
function getBaseURI() external returns (string memory) { return baseUri; }
13,228,456
./full_match/5/0x559385E8728b7d8C98B3910e5531D8C49F861c31/sources/project:/contracts/main/MentaportRegistry.sol
Adds new project to registry _projectRequest Project request/
function addProject( ProjectRequest memory _projectRequest ) external onlySigner registryNotPaused { if(!hasRole(PROJECT_OWNER_ROLE, _projectRequest.owner)){ _grantProjectOwnerRole(_projectRequest.owner); } uint256 projectId = totalProjects; require(projectId < type(uint256).max); require(projectId <= (type(uint256).max/ONE_MILLION)); projects[projectId] = Project({ id: projectId, cost: _projectRequest.cost, maxSupply: _projectRequest.maxSupply, maxMintAmount: _projectRequest.maxMintAmount, paused: false, owner: _projectRequest.owner, name: _projectRequest.name, projectBaseURI: _projectRequest.projectBaseURI, useAllowList: false, merkleRoot: bytes32(0), totalMinted: 0 }); totalProjects = projectId + 1; emit ProjectAdded(projectId, msg.sender); }
1,916,303
pragma solidity ^0.4.18; // File: zeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { 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; } 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; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } // File: zeppelin-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 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; } } // File: zeppelin-solidity/contracts/token/ERC20Basic.sol /** * @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 view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: contracts/TokenVesting.sol /** * @title Vesting contract for SDT * @dev see https://send.sd/token */ contract TokenVesting is Ownable { using SafeMath for uint256; address public ico; bool public initialized; bool public active; ERC20Basic public token; mapping (address => TokenGrant[]) public grants; uint256 public circulatingSupply = 0; struct TokenGrant { uint256 value; uint256 claimed; uint256 vesting; uint256 start; } event NewTokenGrant ( address indexed to, uint256 value, uint256 start, uint256 vesting ); event NewTokenClaim ( address indexed holder, uint256 value ); modifier icoResticted() { require(msg.sender == ico); _; } modifier isActive() { require(active); _; } function TokenVesting() public { active = false; } function init(address _token, address _ico) public onlyOwner { token = ERC20Basic(_token); ico = _ico; initialized = true; active = true; } function stop() public isActive onlyOwner { active = false; } function resume() public onlyOwner { require(!active); require(initialized); active = true; } /** * @dev Grant vested tokens. * @notice Only for ICO contract address. * @param _to Addres to grant tokens to. * @param _value Number of tokens granted. * @param _vesting Vesting finish timestamp. * @param _start Vesting start timestamp. */ function grantVestedTokens( address _to, uint256 _value, uint256 _start, uint256 _vesting ) public icoResticted isActive { require(_value > 0); require(_vesting > _start); require(grants[_to].length < 10); TokenGrant memory grant = TokenGrant(_value, 0, _vesting, _start); grants[_to].push(grant); NewTokenGrant(_to, _value, _start, _vesting); } /** * @dev Claim all vested tokens up to current date for myself */ function claimTokens() public { claim(msg.sender); } /** * @dev Claim all vested tokens up to current date in behaviour of an user * @param _to address Addres to claim tokens */ function claimTokensFor(address _to) public onlyOwner { claim(_to); } /** * @dev Get claimable tokens */ function claimableTokens() public constant returns (uint256) { address _to = msg.sender; uint256 numberOfGrants = grants[_to].length; if (numberOfGrants == 0) { return 0; } uint256 claimable = 0; uint256 claimableFor = 0; for (uint256 i = 0; i < numberOfGrants; i++) { claimableFor = calculateVestedTokens( grants[_to][i].value, grants[_to][i].vesting, grants[_to][i].start, grants[_to][i].claimed ); claimable = claimable.add(claimableFor); } return claimable; } /** * @dev Get all veted tokens */ function totalVestedTokens() public constant returns (uint256) { address _to = msg.sender; uint256 numberOfGrants = grants[_to].length; if (numberOfGrants == 0) { return 0; } uint256 claimable = 0; for (uint256 i = 0; i < numberOfGrants; i++) { claimable = claimable.add( grants[_to][i].value.sub(grants[_to][i].claimed) ); } return claimable; } /** * @dev Calculate vested claimable tokens on current time * @param _tokens Number of tokens granted * @param _vesting Vesting finish timestamp * @param _start Vesting start timestamp * @param _claimed Number of tokens already claimed */ function calculateVestedTokens( uint256 _tokens, uint256 _vesting, uint256 _start, uint256 _claimed ) internal constant returns (uint256) { uint256 time = block.timestamp; if (time < _start) { return 0; } if (time >= _vesting) { return _tokens.sub(_claimed); } uint256 vestedTokens = _tokens.mul(time.sub(_start)).div( _vesting.sub(_start) ); return vestedTokens.sub(_claimed); } /** * @dev Claim all vested tokens up to current date */ function claim(address _to) internal { uint256 numberOfGrants = grants[_to].length; if (numberOfGrants == 0) { return; } uint256 claimable = 0; uint256 claimableFor = 0; for (uint256 i = 0; i < numberOfGrants; i++) { claimableFor = calculateVestedTokens( grants[_to][i].value, grants[_to][i].vesting, grants[_to][i].start, grants[_to][i].claimed ); claimable = claimable.add(claimableFor); grants[_to][i].claimed = grants[_to][i].claimed.add(claimableFor); } token.transfer(_to, claimable); circulatingSupply += claimable; NewTokenClaim(_to, claimable); } }
Get claimable tokens/
function claimableTokens() public constant returns (uint256) { address _to = msg.sender; uint256 numberOfGrants = grants[_to].length; if (numberOfGrants == 0) { return 0; } uint256 claimable = 0; uint256 claimableFor = 0; for (uint256 i = 0; i < numberOfGrants; i++) { claimableFor = calculateVestedTokens( grants[_to][i].value, grants[_to][i].vesting, grants[_to][i].start, grants[_to][i].claimed ); claimable = claimable.add(claimableFor); } return claimable; }
1,147,005
/** * SPDX-License-Identifier: MIT * * Copyright (c) 2020-2021 SCEME SAS * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * copies or substantial portions of the Software. * * 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 OR COPYRIGHT HOLDERS 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. */ pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/presets/ERC20PresetMinterPauserUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/draft-ERC20PermitUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol"; import { Blacklistable } from "./Blacklistable.sol"; contract EURLToken is Initializable, ERC20PresetMinterPauserUpgradeable, ERC20PermitUpgradeable, Blacklistable, UUPSUpgradeable { bytes32 public constant ADMIN = keccak256('ADMIN'); bytes32 public constant MASTER_MINTER = keccak256('MASTER_MINTER'); mapping(address => uint256) public minterAllowed; address private _trustedForwarder; address private _feesFaucet; uint256 private _txfeeRate; uint256 private _gaslessBasefee; uint8 constant DECIMALS = 6; uint256 constant FEE_RATIO = 10000; event Mint(address indexed minter, address indexed to, uint256 amount); event MinterConfigured(address indexed minter, uint256 minterAllowedAmount); event FeeFaucetUpdated(address newFeeFaucet); event TxFeeRateUpdated(uint256 newTxFeeRate); event GaslessBasefeeUpdated(uint256 newGaslessBasefee); event TrustedForwarderUpdated(address newTrustedForwarder); /// @custom:oz-upgrades-unsafe-allow constructor constructor() initializer {} function initialize() initializer public { __ERC20PresetMinterPauser_init("LUGH", "EURL"); __ERC20Permit_init("LUGH"); __UUPSUpgradeable_init(); __Ownable_init(); _setRoleAdmin(MINTER_ROLE, MASTER_MINTER); _setupRole(ADMIN, address(0)); _setupRole(MASTER_MINTER, address(0)); _txfeeRate = 0; _gaslessBasefee = 0; } function decimals() public view virtual override returns (uint8) { return DECIMALS; } /** * @dev Function to update the admin * @param newAdmin The address of the admin */ function setAdministrator(address newAdmin) onlyOwner public virtual { revokeRole(ADMIN, getRoleMember(ADMIN, 0)); revokeRole(PAUSER_ROLE, getRoleMember(PAUSER_ROLE, 0)); grantRole(ADMIN, newAdmin); grantRole(PAUSER_ROLE, newAdmin); updateBlacklister(newAdmin); } /** * @dev Function to update the masterMinter * @param newMasterMinter The address of the masterMinter */ function setMasterMinter(address newMasterMinter) public virtual { revokeRole(MASTER_MINTER, getRoleMember(MASTER_MINTER, 0)); grantRole(MASTER_MINTER, newMasterMinter); } /** * @dev Function to update the DEFAULT_ADMIN_ROLE * @param newOwner The address of the owner */ function setOwner(address newOwner) public virtual { grantRole(DEFAULT_ADMIN_ROLE, newOwner);//_owner revokeRole(DEFAULT_ADMIN_ROLE, getRoleMember(DEFAULT_ADMIN_ROLE, 0)); } function _authorizeUpgrade(address newImplementation) internal onlyRole(DEFAULT_ADMIN_ROLE) override {} /** * @dev Function to set feesFaucet * @param feesFaucet New feesFaucet address */ function setFeeFaucet(address feesFaucet) public onlyRole(ADMIN){ require(feesFaucet != address(0), "EURL: new feesFaucet can't be address 0"); _feesFaucet = feesFaucet; emit FeeFaucetUpdated(feesFaucet); } /** * @dev Function to update tx fee rate * @param newRate The address of the minter */ function updateTxFeeRate(uint256 newRate) public onlyRole(ADMIN){ require(newRate <= FEE_RATIO, "EURL: new rate too high"); //out of 10000 _txfeeRate = newRate; emit TxFeeRateUpdated(_txfeeRate); } /** * @dev Function to update tx fee rate */ function getTxFeeRate() public view returns(uint256){ return _txfeeRate; } /** * @dev Function to calculate fees * @param txAmount amount of the transaction in eurl */ function calculateTxFee(uint256 txAmount) public view returns(uint256){ return txAmount * _txfeeRate / FEE_RATIO; } /** * @dev Function to trigger tx fee payment to feesFaucet (internal) * @param from The address of the payer * @param txAmount amount of the transaction in eurl */ function _payTxFee(address from, uint256 txAmount) internal returns(bool) { uint256 txFees = calculateTxFee(txAmount); require(balanceOf(from) >= txFees + txAmount, "EURL: tx fees"); if (_feesFaucet != address(0)){ _transfer(from, _feesFaucet, txFees); } return true; } /** * @dev Function to update gasless tx basefee * @param newBaseFee new gasless basefee amount */ function updateGaslessBasefee(uint256 newBaseFee) public onlyRole(ADMIN){ _gaslessBasefee = newBaseFee; emit GaslessBasefeeUpdated(newBaseFee); } /** * @dev Function to get gasless basefee */ function getGaslessBasefee() public view returns(uint256){ return _gaslessBasefee; } /** * @dev Function to trigger gaslessBasefee payment from payer to paymaster * Can only be called from trustedForwarder * @param payer Address of basefee payer (meta-tx signer) * @param paymaster Address of paymester (meta-tx executer) */ function payGaslessBasefee(address payer, address paymaster) external { require(isTrustedForwarder(msg.sender), "EURL: only trustedForwarder can process gasless basefee payment"); require(balanceOf(_msgSender()) >= _gaslessBasefee, "EURL: balance too low, can't pay gasless basefee"); uint256 feeRate = _txfeeRate; _txfeeRate = 0; _transfer(payer, paymaster, _gaslessBasefee); _txfeeRate = feeRate; } /** * @dev Function to add/update a new minter * @param minter The address of the minter * @param minterAllowedAmount The minting amount allowed for the minter */ function addMinter(address minter, uint256 minterAllowedAmount) public virtual { minterAllowed[minter] = minterAllowedAmount; grantRole(MINTER_ROLE, minter); } /** * @dev Function to remove a minter * @param minter The address of the minter to remove */ function removeMinter(address minter) public virtual { minterAllowed[minter] = 0; revokeRole(MINTER_ROLE, minter); } /** * @dev Function to update the minting allowance of a minter * @param minter The address of the minter * @param minterAllowedAmount The new minting amount allowed for the minter */ function updateMintingAllowance(address minter, uint256 minterAllowedAmount) public virtual onlyRole(MASTER_MINTER) { minterAllowed[minter] = minterAllowedAmount; } /** * @dev Function to mint tokens * @param to The address that will receive the minted tokens. * @param amount The amount of tokens to mint. Must be less than or equal * to the minterAllowance of the caller. */ function mint(address to, uint256 amount) public whenNotPaused notBlacklisted(to) override { require((hasRole(MASTER_MINTER, msg.sender) || hasRole(MINTER_ROLE, msg.sender)), "EURL: not allowed to mint"); require(amount > 0, "EURL: mint amount not greater than 0"); // MINTER_ROLE allowance management if(hasRole(MINTER_ROLE, msg.sender)) { uint256 mintingAllowedAmount = minterAllowed[msg.sender]; require( amount <= mintingAllowedAmount, "EURL: mint amount exceeds minterAllowance" ); minterAllowed[msg.sender] = mintingAllowedAmount - amount ; } _mint(to, amount); emit Mint(msg.sender, to, amount); } /** * @dev allows a minter to burn some of its own tokens * Validates that caller is a minter and that sender is not blacklisted * amount is less than or equal to the minter's account balance * @param amount uint256 the amount of tokens to be burned */ function burn(uint256 amount) public virtual override whenNotPaused onlyRole(MINTER_ROLE) notBlacklisted(msg.sender) { _burn(msg.sender, amount); } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override(ERC20Upgradeable, ERC20PresetMinterPauserUpgradeable) { require( !blacklisted[from], "Blacklistable: account is blacklisted" ); if(_txfeeRate > 0 && to != _feesFaucet) _payTxFee(from, amount); super._beforeTokenTransfer(from, to, amount); } /** * @dev force a transfer from any account to any account * Validates that caller is the admin * @param from address the account from which to send * @param to address the account that will receive the tokens * @param amount uint256 the amount of token to send */ function forceTransfer(address from, address to, uint256 amount) public virtual onlyRole(ADMIN) { _transfer(from, to, amount); } /** * @dev Function to update trustedForwarder * @param trustedForwarder Address of new trustedForwarder */ function setTrustedForwarder(address trustedForwarder) public onlyRole(ADMIN) { require(trustedForwarder != address(0), "EURL: new trustedForwarder can't be address 0"); _trustedForwarder = trustedForwarder; emit TrustedForwarderUpdated(_trustedForwarder); } /** * @dev Function to check if caller is a trusted Forwarder * @param forwarder The address of the forwarder */ function isTrustedForwarder(address forwarder) public view virtual returns (bool) { return forwarder == _trustedForwarder; } function _msgSender() internal view virtual override returns (address sender) { if (isTrustedForwarder(msg.sender)) { assembly { sender := shr(96, calldataload(sub(calldatasize(), 20))) } } else { return super._msgSender(); } } function _msgData() internal view virtual override returns (bytes calldata) { if (isTrustedForwarder(msg.sender)) { return msg.data[:msg.data.length - 20]; } else { return super._msgData(); } } } /** * SPDX-License-Identifier: MIT * * Copyright (c) 2020-2021 SCEME SAS * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * copies or substantial portions of the Software. * * 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 OR COPYRIGHT HOLDERS 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. */ pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; /** * @title Blacklistable Token * @dev Allows accounts to be blacklisted by a "blacklister" role */ contract Blacklistable is OwnableUpgradeable { address public blacklister; mapping(address => bool) internal blacklisted; event Blacklisted(address indexed _account); event UnBlacklisted(address indexed _account); event BlacklisterChanged(address indexed newBlacklister); /** * @dev Throws if called by any account other than the blacklister */ modifier onlyBlacklister() { require( msg.sender == blacklister, "Blacklistable: caller is not the blacklister" ); _; } /** * @dev Throws if argument account is blacklisted * @param account The address to check */ modifier notBlacklisted(address account) { require( !blacklisted[account], "Blacklistable: account is blacklisted" ); _; } /** * @dev Checks if account is blacklisted * @param account The address to check */ function isBlacklisted(address account) external view returns (bool) { return blacklisted[account]; } /** * @dev Adds account to blacklist * @param account The address to blacklist */ function blacklist(address account) external onlyBlacklister { blacklisted[account] = true; emit Blacklisted(account); } /** * @dev Removes account from blacklist * @param account The address to remove from the blacklist */ function unBlacklist(address account) external onlyBlacklister { blacklisted[account] = false; emit UnBlacklisted(account); } function updateBlacklister(address newBlacklister) internal { require( newBlacklister != address(0), "Blacklistable: new blacklister is the zero address" ); blacklister = newBlacklister; emit BlacklisterChanged(blacklister); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol) 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 EnumerableSetUpgradeable { // 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]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // 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); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // 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)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // 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)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // 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 // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./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 { __ERC165_init_unchained(); } 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; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/cryptography/draft-EIP712.sol) pragma solidity ^0.8.0; import "./ECDSAUpgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data. * * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible, * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding * they need in their contracts using a combination of `abi.encode` and `keccak256`. * * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA * ({_hashTypedDataV4}). * * The implementation of the domain separator was designed to be as efficient as possible while still properly updating * the chain id to protect against replay attacks on an eventual fork of the chain. * * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask]. * * _Available since v3.4._ */ abstract contract EIP712Upgradeable is Initializable { /* solhint-disable var-name-mixedcase */ bytes32 private _HASHED_NAME; bytes32 private _HASHED_VERSION; bytes32 private constant _TYPE_HASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"); /* solhint-enable var-name-mixedcase */ /** * @dev Initializes the domain separator and parameter caches. * * The meaning of `name` and `version` is specified in * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]: * * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol. * - `version`: the current major version of the signing domain. * * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart * contract upgrade]. */ function __EIP712_init(string memory name, string memory version) internal onlyInitializing { __EIP712_init_unchained(name, version); } function __EIP712_init_unchained(string memory name, string memory version) internal onlyInitializing { bytes32 hashedName = keccak256(bytes(name)); bytes32 hashedVersion = keccak256(bytes(version)); _HASHED_NAME = hashedName; _HASHED_VERSION = hashedVersion; } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view returns (bytes32) { return _buildDomainSeparator(_TYPE_HASH, _EIP712NameHash(), _EIP712VersionHash()); } function _buildDomainSeparator( bytes32 typeHash, bytes32 nameHash, bytes32 versionHash ) private view returns (bytes32) { return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this))); } /** * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this * function returns the hash of the fully encoded EIP712 message for this domain. * * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: * * ```solidity * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( * keccak256("Mail(address to,string contents)"), * mailTo, * keccak256(bytes(mailContents)) * ))); * address signer = ECDSA.recover(digest, signature); * ``` */ function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { return ECDSAUpgradeable.toTypedDataHash(_domainSeparatorV4(), structHash); } /** * @dev The hash of the name parameter for the EIP712 domain. * * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs * are a concern. */ function _EIP712NameHash() internal virtual view returns (bytes32) { return _HASHED_NAME; } /** * @dev The hash of the version parameter for the EIP712 domain. * * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs * are a concern. */ function _EIP712VersionHash() internal virtual view returns (bytes32) { return _HASHED_VERSION; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/cryptography/ECDSA.sol) pragma solidity ^0.8.0; import "../StringsUpgradeable.sol"; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSAUpgradeable { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", StringsUpgradeable.toString(s.length), s)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // 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/StorageSlot.sol) pragma solidity ^0.8.0; /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ``` * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ */ library StorageSlotUpgradeable { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) pragma solidity ^0.8.0; /** * @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 CountersUpgradeable { 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; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; 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 { __Context_init_unchained(); } 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; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ 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 * ==== */ 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 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 (token/ERC20/presets/ERC20PresetMinterPauser.sol) pragma solidity ^0.8.0; import "../ERC20Upgradeable.sol"; import "../extensions/ERC20BurnableUpgradeable.sol"; import "../extensions/ERC20PausableUpgradeable.sol"; import "../../../access/AccessControlEnumerableUpgradeable.sol"; import "../../../utils/ContextUpgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @dev {ERC20} token, including: * * - ability for holders to burn (destroy) their tokens * - a minter role that allows for token minting (creation) * - a pauser role that allows to stop all token transfers * * This contract uses {AccessControl} to lock permissioned functions using the * different roles - head to its documentation for details. * * The account that deploys the contract will be granted the minter and pauser * roles, as well as the default admin role, which will let it grant both minter * and pauser roles to other accounts. */ contract ERC20PresetMinterPauserUpgradeable is Initializable, ContextUpgradeable, AccessControlEnumerableUpgradeable, ERC20BurnableUpgradeable, ERC20PausableUpgradeable { function initialize(string memory name, string memory symbol) public virtual initializer { __ERC20PresetMinterPauser_init(name, symbol); } bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); /** * @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the * account that deploys the contract. * * See {ERC20-constructor}. */ function __ERC20PresetMinterPauser_init(string memory name, string memory symbol) internal onlyInitializing { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); __AccessControlEnumerable_init_unchained(); __ERC20_init_unchained(name, symbol); __ERC20Burnable_init_unchained(); __Pausable_init_unchained(); __ERC20Pausable_init_unchained(); __ERC20PresetMinterPauser_init_unchained(name, symbol); } function __ERC20PresetMinterPauser_init_unchained(string memory name, string memory symbol) internal onlyInitializing { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); _setupRole(PAUSER_ROLE, _msgSender()); } /** * @dev Creates `amount` new tokens for `to`. * * See {ERC20-_mint}. * * Requirements: * * - the caller must have the `MINTER_ROLE`. */ function mint(address to, uint256 amount) public virtual { require(hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have minter role to mint"); _mint(to, amount); } /** * @dev Pauses all token transfers. * * See {ERC20Pausable} and {Pausable-_pause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function pause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to pause"); _pause(); } /** * @dev Unpauses all token transfers. * * See {ERC20Pausable} and {Pausable-_unpause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function unpause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to unpause"); _unpause(); } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override(ERC20Upgradeable, ERC20PausableUpgradeable) { super._beforeTokenTransfer(from, to, amount); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20PermitUpgradeable { /** * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens, * given ``owner``'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-ERC20Permit.sol) pragma solidity ^0.8.0; import "./draft-IERC20PermitUpgradeable.sol"; import "../ERC20Upgradeable.sol"; import "../../../utils/cryptography/draft-EIP712Upgradeable.sol"; import "../../../utils/cryptography/ECDSAUpgradeable.sol"; import "../../../utils/CountersUpgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. * * _Available since v3.4._ */ abstract contract ERC20PermitUpgradeable is Initializable, ERC20Upgradeable, IERC20PermitUpgradeable, EIP712Upgradeable { using CountersUpgradeable for CountersUpgradeable.Counter; mapping(address => CountersUpgradeable.Counter) private _nonces; // solhint-disable-next-line var-name-mixedcase bytes32 private _PERMIT_TYPEHASH; /** * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`. * * It's a good idea to use the same `name` that is defined as the ERC20 token name. */ function __ERC20Permit_init(string memory name) internal onlyInitializing { __Context_init_unchained(); __EIP712_init_unchained(name, "1"); __ERC20Permit_init_unchained(name); } function __ERC20Permit_init_unchained(string memory name) internal onlyInitializing { _PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");} /** * @dev See {IERC20Permit-permit}. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual override { require(block.timestamp <= deadline, "ERC20Permit: expired deadline"); bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline)); bytes32 hash = _hashTypedDataV4(structHash); address signer = ECDSAUpgradeable.recover(hash, v, r, s); require(signer == owner, "ERC20Permit: invalid signature"); _approve(owner, spender, value); } /** * @dev See {IERC20Permit-nonces}. */ function nonces(address owner) public view virtual override returns (uint256) { return _nonces[owner].current(); } /** * @dev See {IERC20Permit-DOMAIN_SEPARATOR}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view override returns (bytes32) { return _domainSeparatorV4(); } /** * @dev "Consume a nonce": return the current value and increment. * * _Available since v4.1._ */ function _useNonce(address owner) internal virtual returns (uint256 current) { CountersUpgradeable.Counter storage nonce = _nonces[owner]; current = nonce.current(); nonce.increment(); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; import "../IERC20Upgradeable.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20MetadataUpgradeable is IERC20Upgradeable { /** * @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 // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/ERC20Pausable.sol) pragma solidity ^0.8.0; import "../ERC20Upgradeable.sol"; import "../../../security/PausableUpgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @dev ERC20 token with pausable token transfers, minting and burning. * * Useful for scenarios such as preventing trades until the end of an evaluation * period, or having an emergency switch for freezing all token transfers in the * event of a large bug. */ abstract contract ERC20PausableUpgradeable is Initializable, ERC20Upgradeable, PausableUpgradeable { function __ERC20Pausable_init() internal onlyInitializing { __Context_init_unchained(); __Pausable_init_unchained(); __ERC20Pausable_init_unchained(); } function __ERC20Pausable_init_unchained() internal onlyInitializing { } /** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override { super._beforeTokenTransfer(from, to, amount); require(!paused(), "ERC20Pausable: token transfer while paused"); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/ERC20Burnable.sol) pragma solidity ^0.8.0; import "../ERC20Upgradeable.sol"; import "../../../utils/ContextUpgradeable.sol"; import "../../../proxy/utils/Initializable.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). */ abstract contract ERC20BurnableUpgradeable is Initializable, ContextUpgradeable, ERC20Upgradeable { function __ERC20Burnable_init() internal onlyInitializing { __Context_init_unchained(); __ERC20Burnable_init_unchained(); } function __ERC20Burnable_init_unchained() internal onlyInitializing { } /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 currentAllowance = allowance(account, _msgSender()); require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance"); unchecked { _approve(account, _msgSender(), currentAllowance - amount); } _burn(account, amount); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @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 // OpenZeppelin Contracts v4.4.1 (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; import "./IERC20Upgradeable.sol"; import "./extensions/IERC20MetadataUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../proxy/utils/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 Contracts guidelines: functions revert * instead 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 ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable { 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 default 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. */ function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing { __Context_init_unchained(); __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing { _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"); unchecked { _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"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This 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"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(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: * * - `account` 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); _afterTokenTransfer(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"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(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 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 {} /** * @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, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been 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 _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} uint256[45] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; 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. */ 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 { __Context_init_unchained(); __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() { 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()); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/utils/UUPSUpgradeable.sol) pragma solidity ^0.8.0; import "../ERC1967/ERC1967UpgradeUpgradeable.sol"; import "./Initializable.sol"; /** * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy. * * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing * `UUPSUpgradeable` with a custom implementation of upgrades. * * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism. * * _Available since v4.1._ */ abstract contract UUPSUpgradeable is Initializable, ERC1967UpgradeUpgradeable { function __UUPSUpgradeable_init() internal onlyInitializing { __ERC1967Upgrade_init_unchained(); __UUPSUpgradeable_init_unchained(); } function __UUPSUpgradeable_init_unchained() internal onlyInitializing { } /// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment address private immutable __self = address(this); /** * @dev Check that the execution is being performed through a delegatecall call and that the execution context is * a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a * function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to * fail. */ modifier onlyProxy() { require(address(this) != __self, "Function must be called through delegatecall"); require(_getImplementation() == __self, "Function must be called through active proxy"); _; } /** * @dev Upgrade the implementation of the proxy to `newImplementation`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeTo(address newImplementation) external virtual onlyProxy { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, new bytes(0), false); } /** * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call * encoded in `data`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual onlyProxy { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, data, true); } /** * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by * {upgradeTo} and {upgradeToAndCall}. * * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}. * * ```solidity * function _authorizeUpgrade(address) internal override onlyOwner {} * ``` */ function _authorizeUpgrade(address newImplementation) internal virtual; uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; 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 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 {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 {} * ``` * ==== */ 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. require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); 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() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol) pragma solidity ^0.8.0; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeaconUpgradeable { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function implementation() external view returns (address); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/ERC1967/ERC1967Upgrade.sol) pragma solidity ^0.8.2; import "../beacon/IBeaconUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/StorageSlotUpgradeable.sol"; import "../utils/Initializable.sol"; /** * @dev This abstract contract provides getters and event emitting update functions for * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots. * * _Available since v4.1._ * * @custom:oz-upgrades-unsafe-allow delegatecall */ abstract contract ERC1967UpgradeUpgradeable is Initializable { function __ERC1967Upgrade_init() internal onlyInitializing { __ERC1967Upgrade_init_unchained(); } function __ERC1967Upgrade_init_unchained() internal onlyInitializing { } // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Returns the current implementation address. */ function _getImplementation() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract"); StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Perform implementation upgrade with additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCall( address newImplementation, bytes memory data, bool forceCall ) internal { _upgradeTo(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } } /** * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCallSecure( address newImplementation, bytes memory data, bool forceCall ) internal { address oldImplementation = _getImplementation(); // Initial upgrade and setup call _setImplementation(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } // Perform rollback test if not already in progress StorageSlotUpgradeable.BooleanSlot storage rollbackTesting = StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT); if (!rollbackTesting.value) { // Trigger rollback using upgradeTo from the new implementation rollbackTesting.value = true; _functionDelegateCall( newImplementation, abi.encodeWithSignature("upgradeTo(address)", oldImplementation) ); rollbackTesting.value = false; // Check rollback was effective require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades"); // Finally reset to the new implementation and log the upgrade _upgradeTo(newImplementation); } } /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Returns the current admin. */ function _getAdmin() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value; } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { require(newAdmin != address(0), "ERC1967: new admin is the zero address"); StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. */ function _changeAdmin(address newAdmin) internal { emit AdminChanged(_getAdmin(), newAdmin); _setAdmin(newAdmin); } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. */ bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Emitted when the beacon is upgraded. */ event BeaconUpgraded(address indexed beacon); /** * @dev Returns the current beacon. */ function _getBeacon() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract"); require( AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon; } /** * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). * * Emits a {BeaconUpgraded} event. */ function _upgradeBeaconToAndCall( address newBeacon, bytes memory data, bool forceCall ) internal { _setBeacon(newBeacon); emit BeaconUpgraded(newBeacon); if (data.length > 0 || forceCall) { _functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data); } } /** * @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) private returns (bytes memory) { require(AddressUpgradeable.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 AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed"); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; 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. */ 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 { __Context_init_unchained(); __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() { 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 { _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 { require(newOwner != address(0), "Ownable: new owner is the zero address"); _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); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { /** * @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 {AccessControl-_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 Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @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) external; /** * @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) external; /** * @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) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol) pragma solidity ^0.8.0; import "./IAccessControlUpgradeable.sol"; /** * @dev External interface of AccessControlEnumerable declared to support ERC165 detection. */ interface IAccessControlEnumerableUpgradeable is IAccessControlUpgradeable { /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) external view returns (address); /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/AccessControl.sol) pragma solidity ^0.8.0; import "./IAccessControlUpgradeable.sol"; import "../utils/ContextUpgradeable.sol"; import "../utils/StringsUpgradeable.sol"; import "../utils/introspection/ERC165Upgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @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 AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable { function __AccessControl_init() internal onlyInitializing { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal onlyInitializing { } struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @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]{40}) is missing role (0x[0-9a-f]{64})$/ * * _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(IAccessControlUpgradeable).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]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", StringsUpgradeable.toHexString(uint160(account), 20), " is missing role ", StringsUpgradeable.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 revoked `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}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ 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 { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/AccessControlEnumerable.sol) pragma solidity ^0.8.0; import "./IAccessControlEnumerableUpgradeable.sol"; import "./AccessControlUpgradeable.sol"; import "../utils/structs/EnumerableSetUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Extension of {AccessControl} that allows enumerating the members of each role. */ abstract contract AccessControlEnumerableUpgradeable is Initializable, IAccessControlEnumerableUpgradeable, AccessControlUpgradeable { function __AccessControlEnumerable_init() internal onlyInitializing { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); __AccessControlEnumerable_init_unchained(); } function __AccessControlEnumerable_init_unchained() internal onlyInitializing { } using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) private _roleMembers; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlEnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view override returns (address) { return _roleMembers[role].at(index); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view override returns (uint256) { return _roleMembers[role].length(); } /** * @dev Overload {_grantRole} to track enumerable memberships */ function _grantRole(bytes32 role, address account) internal virtual override { super._grantRole(role, account); _roleMembers[role].add(account); } /** * @dev Overload {_revokeRole} to track enumerable memberships */ function _revokeRole(bytes32 role, address account) internal virtual override { super._revokeRole(role, account); _roleMembers[role].remove(account); } uint256[49] private __gap; }
force a transfer from any account to any account Validates that caller is the admin from address the account from which to send to address the account that will receive the tokens amount uint256 the amount of token to send/
function forceTransfer(address from, address to, uint256 amount) public virtual onlyRole(ADMIN) { _transfer(from, to, amount); }
6,064,676
// File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/solc-0.7/contracts/math/SafeMath.sol // SPDX-License-Identifier: MIT pragma solidity ^0.7.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: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/solc-0.7/contracts/token/ERC20/IERC20.sol pragma solidity ^0.7.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: TokenQUarter.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev A token holder contract that will allow a beneficiary to extract the * tokens after a given release time. * * Useful for simple vesting schedules like "advisors get all of their tokens * after 1 year". */ contract DMODCommunity { using SafeMath for uint256; // ERC20 basic token contract being held IERC20 private _token; // beneficiary of tokens after they are released address private _beneficiary; // total balance of tokens sent to contract uint256 public totalBalance; // timestamp of release date and percent to be released struct VestPeriodInfo { uint256 releaseTime; uint256 percent; bool released; } // array of vesting period VestPeriodInfo[] public vestPeriodInfoArray; uint256 constant PRECISION = 10**25; uint256 constant PERCENT = 100 * PRECISION; constructor( IERC20 token_, address beneficiary_, uint256[] memory releaseTimes_, uint256[] memory percents_, uint256 totalBalance_ ) public { // solhint-disable-next-line not-rely-on-time require( percents_.length == releaseTimes_.length, "DMODCommunity: there should be equal percents and release times values" ); require( beneficiary_ != address(0), "DMODCommunity: beneficiary address should not be zero address" ); require( address(token_) != address(0), "DMODCommunity: token address should not be zero address" ); _token = token_; for (uint256 i = 0; i < releaseTimes_.length; i++) { vestPeriodInfoArray.push( VestPeriodInfo({ percent: percents_[i], releaseTime: releaseTimes_[i], released: false }) ); } _beneficiary = beneficiary_; totalBalance = totalBalance_; } /** * @return the token being held. */ function token() public view virtual returns (IERC20) { return _token; } /** * @return the beneficiary of the tokens. */ function beneficiary() public view virtual returns (address) { return _beneficiary; } /** * @return the time when the tokens are released. */ function releaseTime(uint256 index) public view virtual returns (uint256) { return vestPeriodInfoArray[index].releaseTime; } /** * @return the percent of tokens to be released during a period. */ function releasePercent(uint256 index) public view virtual returns (uint256) { return vestPeriodInfoArray[index].percent; } /** * @notice Transfers tokens held by timelock to beneficiary. */ function release() public virtual { // solhint-disable-next-line not-rely-on-time uint256 amount; for (uint256 i = 0; i < vestPeriodInfoArray.length; i++) { VestPeriodInfo memory vestPeriodInfo = vestPeriodInfoArray[i]; if (vestPeriodInfo.releaseTime < block.timestamp) { if (!vestPeriodInfo.released) { vestPeriodInfoArray[i].released = true; amount = amount.add( vestPeriodInfo .percent .mul(PRECISION) .mul(totalBalance) .div(PERCENT) ); } } else { break; } } require(amount > 0, "TokenTimelock: no tokens to release"); token().transfer(_beneficiary, amount); } }
return the beneficiary of the tokens./
function beneficiary() public view virtual returns (address) { return _beneficiary; }
19,885
pragma solidity ^0.4.24; interface PlayerBookReceiverInterface { function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) external; function receivePlayerNameList(uint256 _pID, bytes32 _name) external; } interface TeamAnonymousInterface { function requiredSignatures() external view returns(uint256); function requiredDevSignatures() external view returns(uint256); function adminCount() external view returns(uint256); function devCount() external view returns(uint256); function adminName(address _who) external view returns(bytes32); function isAdmin(address _who) external view returns(bool); function isDev(address _who) external view returns(bool); } contract PlayerBook { using NameFilter for string; using SafeMath for uint256; // TO DO: TEAM ADDRESS TeamAnonymousInterface constant private TeamAnonymous = TeamAnonymousInterface(0x5073Fa31039F19557e085e86fa80CdF40eC7593A); MSFun.Data private msData; function multiSigDev(bytes32 _whatFunction) private returns (bool) {return(MSFun.multiSig(msData, TeamAnonymous.requiredDevSignatures(), _whatFunction));} function deleteProposal(bytes32 _whatFunction) private {MSFun.deleteProposal(msData, _whatFunction);} function deleteAnyProposal(bytes32 _whatFunction) onlyDevs() public {MSFun.deleteProposal(msData, _whatFunction);} function checkData(bytes32 _whatFunction) onlyDevs() public view returns(bytes32, uint256) {return(MSFun.checkMsgData(msData, _whatFunction), MSFun.checkCount(msData, _whatFunction));} function checkSignersByAddress(bytes32 _whatFunction, uint256 _signerA, uint256 _signerB, uint256 _signerC) onlyDevs() public view returns(address, address, address) {return(MSFun.checkSigner(msData, _whatFunction, _signerA), MSFun.checkSigner(msData, _whatFunction, _signerB), MSFun.checkSigner(msData, _whatFunction, _signerC));} function checkSignersByName(bytes32 _whatFunction, uint256 _signerA, uint256 _signerB, uint256 _signerC) onlyDevs() public view returns(bytes32, bytes32, bytes32) {return(TeamAnonymous.adminName(MSFun.checkSigner(msData, _whatFunction, _signerA)), TeamAnonymous.adminName(MSFun.checkSigner(msData, _whatFunction, _signerB)), TeamAnonymous.adminName(MSFun.checkSigner(msData, _whatFunction, _signerC)));} address constant private team = 0xBd01103c36f400344b427Cb51934B765007e16f6; uint256 public registrationFee_ = 1 finney; // price to register a name mapping(uint256 => PlayerBookReceiverInterface) public games_; // mapping of our game interfaces for sending your account info to games mapping(address => bytes32) public gameNames_; // lookup a games name mapping(address => uint256) public gameIDs_; // lokup a games ID uint256 public gID_; // total number of games uint256 public pID_; // total number of players mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name mapping (uint256 => Player) public plyr_; // (pID => data) player data mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amoungst any name you own) mapping (uint256 => mapping (uint256 => bytes32)) public plyrNameList_; // (pID => nameNum => name) list of names a player owns struct Player { address addr; bytes32 name; uint256 laff; uint256 names; } //============================================================================== // _ _ _ __|_ _ __|_ _ _ . // (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy) //============================================================================== constructor() public { // premine the dev names (sorry not sorry) // No keys are purchased with this method, it's simply locking our addresses, // PID's and names for referral codes. //管理员地址 plyr_[1].addr = 0x3C21550C76B9C0Eb32ceA5f7ea71d54f366961a1; plyr_[1].name = "creator"; plyr_[1].names = 1; pIDxAddr_[0x3C21550C76B9C0Eb32ceA5f7ea71d54f366961a1] = 1; pIDxName_["creator"] = 1; plyrNames_[1]["creator"] = true; plyrNameList_[1][1] = "creator"; plyr_[2].addr = 0x3123AD3e691bC320aaCC8ab91A0E32A7eE4C4b9a; plyr_[2].name = "admin"; plyr_[2].names = 1; pIDxAddr_[0x3123AD3e691bC320aaCC8ab91A0E32A7eE4C4b9a] = 2; pIDxName_["admin"] = 2; plyrNames_[2]["admin"] = true; plyrNameList_[2][1] = "admin"; pID_ = 2; } //============================================================================== // _ _ _ _|. |`. _ _ _ . // | | |(_)(_||~|~|(/_| _\ . (these are safety checks) //============================================================================== /** * @dev prevents contracts from interacting with fomo3d */ modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "sorry humans only"); _; } modifier onlyDevs() { require(TeamAnonymous.isDev(msg.sender) == true, "msg sender is not a dev"); _; } modifier isRegisteredGame() { require(gameIDs_[msg.sender] != 0); _; } //============================================================================== // _ _ _ _|_ _ . // (/_\/(/_| | | _\ . //============================================================================== // fired whenever a player registers a name event onNewName ( uint256 indexed playerID, address indexed playerAddress, bytes32 indexed playerName, bool isNewPlayer, uint256 affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 amountPaid, uint256 timeStamp ); //============================================================================== // _ _ _|__|_ _ _ _ . // (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan) //=====_|======================================================================= function checkIfNameValid(string _nameStr) public view returns(bool) { bytes32 _name = _nameStr.nameFilter(); if (pIDxName_[_name] == 0) return (true); else return (false); } //============================================================================== // _ |_ |. _ |` _ __|_. _ _ _ . // |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract) //====|========================================================================= /** * @dev registers a name. UI will always display the last name you registered. * but you will still own all previously registered names to use as affiliate * links. * - must pay a registration fee. * - name must be unique * - names will be converted to lowercase * - name cannot start or end with a space * - cannot have more than 1 space in a row * - cannot be only numbers * - cannot start with 0x * - name must be at least 1 char * - max length of 32 characters long * - allowed characters: a-z, 0-9, and space * -functionhash- 0x921dec21 (using ID for affiliate) * -functionhash- 0x3ddd4698 (using address for affiliate) * -functionhash- 0x685ffd83 (using name for affiliate) * @param _nameString players desired name * @param _affCode affiliate ID, address, or name of who refered you * @param _all set to true if you want this to push your info to all games * (this might cost a lot of gas) */ function registerNameXID(string _nameString, uint256 _affCode, bool _all) isHuman() public payable { // make sure name fees paid require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // filter name + condition checks bytes32 _name = NameFilter.nameFilter(_nameString); // set up address address _addr = msg.sender; // set up our tx event data and determine if player is new or not bool _isNewPlayer = determinePID(_addr); // fetch player id uint256 _pID = pIDxAddr_[_addr]; // manage affiliate residuals // if no affiliate code was given, no new affiliate code was given, or the // player tried to use their own pID as an affiliate code, lolz if (_affCode != 0 && _affCode != plyr_[_pID].laff && _affCode != _pID) { // update last affiliate plyr_[_pID].laff = _affCode; } else if (_affCode == _pID) { _affCode = 0; } // register name registerNameCore(_pID, _addr, _affCode, _name, _isNewPlayer, _all); } function registerNameXaddr(string _nameString, address _affCode, bool _all) isHuman() public payable { // make sure name fees paid require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // filter name + condition checks bytes32 _name = NameFilter.nameFilter(_nameString); // set up address address _addr = msg.sender; // set up our tx event data and determine if player is new or not bool _isNewPlayer = determinePID(_addr); // fetch player id uint256 _pID = pIDxAddr_[_addr]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz uint256 _affID; if (_affCode != address(0) && _affCode != _addr) { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // register name registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all); } function registerNameXname(string _nameString, bytes32 _affCode, bool _all) isHuman() public payable { // make sure name fees paid require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // filter name + condition checks bytes32 _name = NameFilter.nameFilter(_nameString); // set up address address _addr = msg.sender; // set up our tx event data and determine if player is new or not bool _isNewPlayer = determinePID(_addr); // fetch player id uint256 _pID = pIDxAddr_[_addr]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz uint256 _affID; if (_affCode != "" && _affCode != _name) { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // register name registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all); } /** * @dev players, if you registered a profile, before a game was released, or * set the all bool to false when you registered, use this function to push * your profile to a single game. also, if you've updated your name, you * can use this to push your name to games of your choosing. * -functionhash- 0x81c5b206 * @param _gameID game id */ function addMeToGame(uint256 _gameID) isHuman() public { require(_gameID <= gID_, "silly player, that game doesn't exist yet"); address _addr = msg.sender; uint256 _pID = pIDxAddr_[_addr]; require(_pID != 0, "hey there buddy, you dont even have an account"); uint256 _totalNames = plyr_[_pID].names; // add players profile and most recent name games_[_gameID].receivePlayerInfo(_pID, _addr, plyr_[_pID].name, plyr_[_pID].laff); // add list of all names if (_totalNames > 1) for (uint256 ii = 1; ii <= _totalNames; ii++) games_[_gameID].receivePlayerNameList(_pID, plyrNameList_[_pID][ii]); } /** * @dev players, use this to push your player profile to all registered games. * -functionhash- 0x0c6940ea */ function addMeToAllGames() isHuman() public { address _addr = msg.sender; uint256 _pID = pIDxAddr_[_addr]; require(_pID != 0, "hey there buddy, you dont even have an account"); uint256 _laff = plyr_[_pID].laff; uint256 _totalNames = plyr_[_pID].names; bytes32 _name = plyr_[_pID].name; for (uint256 i = 1; i <= gID_; i++) { games_[i].receivePlayerInfo(_pID, _addr, _name, _laff); if (_totalNames > 1) for (uint256 ii = 1; ii <= _totalNames; ii++) games_[i].receivePlayerNameList(_pID, plyrNameList_[_pID][ii]); } } /** * @dev players use this to change back to one of your old names. tip, you'll * still need to push that info to existing games. * -functionhash- 0xb9291296 * @param _nameString the name you want to use */ function useMyOldName(string _nameString) isHuman() public { // filter name, and get pID bytes32 _name = _nameString.nameFilter(); uint256 _pID = pIDxAddr_[msg.sender]; // make sure they own the name require(plyrNames_[_pID][_name] == true, "umm... thats not a name you own"); // update their current name plyr_[_pID].name = _name; } //============================================================================== // _ _ _ _ | _ _ . _ . // (_(_)| (/_ |(_)(_||(_ . //=====================_|======================================================= function registerNameCore(uint256 _pID, address _addr, uint256 _affID, bytes32 _name, bool _isNewPlayer, bool _all) private { // if names already has been used, require that current msg sender owns the name if (pIDxName_[_name] != 0) require(plyrNames_[_pID][_name] == true, "sorry that names already taken"); // add name to player profile, registry, and name book plyr_[_pID].name = _name; pIDxName_[_name] = _pID; if (plyrNames_[_pID][_name] == false) { plyrNames_[_pID][_name] = true; plyr_[_pID].names++; plyrNameList_[_pID][plyr_[_pID].names] = _name; } // registration fee goes directly to community rewards team.transfer(address(this).balance); // push player info to games if (_all == true) for (uint256 i = 1; i <= gID_; i++) games_[i].receivePlayerInfo(_pID, _addr, _name, _affID); // fire event emit onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, msg.value, now); } //============================================================================== // _|_ _ _ | _ . // | (_)(_)|_\ . //============================================================================== function determinePID(address _addr) private returns (bool) { if (pIDxAddr_[_addr] == 0) { pID_++; pIDxAddr_[_addr] = pID_; plyr_[pID_].addr = _addr; // set the new player bool to true return (true); } else { return (false); } } //============================================================================== // _ _|_ _ _ _ _ | _ _ || _ . // (/_>< | (/_| | |(_|| (_(_|||_\ . //============================================================================== function getPlayerID(address _addr) isRegisteredGame() external returns (uint256) { determinePID(_addr); return (pIDxAddr_[_addr]); } function getPlayerName(uint256 _pID) external view returns (bytes32) { return (plyr_[_pID].name); } function getPlayerLAff(uint256 _pID) external view returns (uint256) { return (plyr_[_pID].laff); } function getPlayerAddr(uint256 _pID) external view returns (address) { return (plyr_[_pID].addr); } function getNameFee() external view returns (uint256) { return(registrationFee_); } function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) isRegisteredGame() external payable returns(bool, uint256) { // make sure name fees paid require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // set up our tx event data and determine if player is new or not bool _isNewPlayer = determinePID(_addr); // fetch player id uint256 _pID = pIDxAddr_[_addr]; // manage affiliate residuals // if no affiliate code was given, no new affiliate code was given, or the // player tried to use their own pID as an affiliate code, lolz uint256 _affID = _affCode; if (_affID != 0 && _affID != plyr_[_pID].laff && _affID != _pID) { // update last affiliate plyr_[_pID].laff = _affID; } else if (_affID == _pID) { _affID = 0; } // register name registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all); return(_isNewPlayer, _affID); } function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) isRegisteredGame() external payable returns(bool, uint256) { // make sure name fees paid require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // set up our tx event data and determine if player is new or not bool _isNewPlayer = determinePID(_addr); // fetch player id uint256 _pID = pIDxAddr_[_addr]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz uint256 _affID; if (_affCode != address(0) && _affCode != _addr) { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // register name registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all); return(_isNewPlayer, _affID); } function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) isRegisteredGame() external payable returns(bool, uint256) { // make sure name fees paid require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // set up our tx event data and determine if player is new or not bool _isNewPlayer = determinePID(_addr); // fetch player id uint256 _pID = pIDxAddr_[_addr]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz uint256 _affID; if (_affCode != "" && _affCode != _name) { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // register name registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all); return(_isNewPlayer, _affID); } //============================================================================== // _ _ _|_ _ . // _\(/_ | |_||_) . //=============|================================================================ function addGame(address _gameAddress, string _gameNameStr) onlyDevs() public { require(gameIDs_[_gameAddress] == 0, "derp, that games already been registered"); gID_++; bytes32 _name = _gameNameStr.nameFilter(); gameIDs_[_gameAddress] = gID_; gameNames_[_gameAddress] = _name; games_[gID_] = PlayerBookReceiverInterface(_gameAddress); games_[gID_].receivePlayerInfo(1, plyr_[1].addr, plyr_[1].name, 0); games_[gID_].receivePlayerInfo(2, plyr_[2].addr, plyr_[2].name, 0); } // MASK: SET 设置改名费 function setRegistrationFee(uint256 _fee) onlyDevs() public { registrationFee_ = _fee; } } library NameFilter { /** * @dev filters name strings * -converts uppercase to lower case. * -makes sure it does not start/end with a space * -makes sure it does not contain multiple spaces in a row * -cannot be only numbers * -cannot start with 0x * -restricts characters to A-Z, a-z, 0-9, and space. * @return reprocessed string in bytes32 format */ function nameFilter(string _input) internal pure returns(bytes32) { bytes memory _temp = bytes(_input); uint256 _length = _temp.length; //sorry limited to 32 characters require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters"); // make sure it doesnt start with or end with space require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space"); // make sure first two characters are not 0x if (_temp[0] == 0x30) { require(_temp[1] != 0x78, "string cannot start with 0x"); require(_temp[1] != 0x58, "string cannot start with 0X"); } // create a bool to track if we have a non number character bool _hasNonNumber; // convert & check for (uint256 i = 0; i < _length; i++) { // if its uppercase A-Z if (_temp[i] > 0x40 && _temp[i] < 0x5b) { // convert to lower case a-z _temp[i] = byte(uint(_temp[i]) + 32); // we have a non number if (_hasNonNumber == false) _hasNonNumber = true; } else { require ( // require character is a space _temp[i] == 0x20 || // OR lowercase a-z (_temp[i] > 0x60 && _temp[i] < 0x7b) || // or 0-9 (_temp[i] > 0x2f && _temp[i] < 0x3a), "string contains invalid characters" ); // make sure theres not 2x spaces in a row if (_temp[i] == 0x20) require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces"); // see if we have a character other than a number if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39)) _hasNonNumber = true; } } require(_hasNonNumber == true, "string cannot be only numbers"); bytes32 _ret; assembly { _ret := mload(add(_temp, 32)) } return (_ret); } } /** * @title SafeMath v0.1.9 * @dev Math operations with safety checks that throw on error * change notes: original SafeMath library from OpenZeppelin modified by Inventor * - added sqrt * - added sq * - added pwr * - changed asserts to requires with error log outputs * - removed div, its useless */ 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; require(c / a == b, "SafeMath mul failed"); return c; } /** * @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) { require(b <= a, "SafeMath sub failed"); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "SafeMath add failed"); return c; } /** * @dev gives square root of given x. */ function sqrt(uint256 x) internal pure returns (uint256 y) { uint256 z = ((add(x,1)) / 2); y = x; while (z < y) { y = z; z = ((add((x / z),z)) / 2); } } /** * @dev gives square. multiplies x by x */ function sq(uint256 x) internal pure returns (uint256) { return (mul(x,x)); } /** * @dev x to the power of y */ function pwr(uint256 x, uint256 y) internal pure returns (uint256) { if (x==0) return (0); else if (y==0) return (1); else { uint256 z = x; for (uint256 i=1; i < y; i++) z = mul(z,x); return (z); } } } library MSFun { //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // DATA SETS //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // contact data setup struct Data { mapping (bytes32 => ProposalData) proposal_; } struct ProposalData { // a hash of msg.data bytes32 msgData; // number of signers uint256 count; // tracking of wither admins have signed mapping (address => bool) admin; // list of admins who have signed mapping (uint256 => address) log; } //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // MULTI SIG FUNCTIONS //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ function multiSig(Data storage self, uint256 _requiredSignatures, bytes32 _whatFunction) internal returns(bool) { // our proposal key will be a hash of our function name + our contracts address // by adding our contracts address to this, we prevent anyone trying to circumvent // the proposal's security via external calls. bytes32 _whatProposal = whatProposal(_whatFunction); // this is just done to make the code more readable. grabs the signature count uint256 _currentCount = self.proposal_[_whatProposal].count; // store the address of the person sending the function call. we use msg.sender // here as a layer of security. in case someone imports our contract and tries to // circumvent function arguments. still though, our contract that imports this // library and calls multisig, needs to use onlyAdmin modifiers or anyone who // calls the function will be a signer. address _whichAdmin = msg.sender; // prepare our msg data. by storing this we are able to verify that all admins // are approving the same argument input to be executed for the function. we hash // it and store in bytes32 so its size is known and comparable bytes32 _msgData = keccak256(msg.data); // check to see if this is a new execution of this proposal or not if (_currentCount == 0) { // if it is, lets record the original signers data self.proposal_[_whatProposal].msgData = _msgData; // record original senders signature self.proposal_[_whatProposal].admin[_whichAdmin] = true; // update log (used to delete records later, and easy way to view signers) // also useful if the calling function wants to give something to a // specific signer. self.proposal_[_whatProposal].log[_currentCount] = _whichAdmin; // track number of signatures self.proposal_[_whatProposal].count += 1; // if we now have enough signatures to execute the function, lets // return a bool of true. we put this here in case the required signatures // is set to 1. if (self.proposal_[_whatProposal].count == _requiredSignatures) { return(true); } // if its not the first execution, lets make sure the msgData matches } else if (self.proposal_[_whatProposal].msgData == _msgData) { // msgData is a match // make sure admin hasnt already signed if (self.proposal_[_whatProposal].admin[_whichAdmin] == false) { // record their signature self.proposal_[_whatProposal].admin[_whichAdmin] = true; // update log (used to delete records later, and easy way to view signers) self.proposal_[_whatProposal].log[_currentCount] = _whichAdmin; // track number of signatures self.proposal_[_whatProposal].count += 1; } // if we now have enough signatures to execute the function, lets // return a bool of true. // we put this here for a few reasons. (1) in normal operation, if // that last recorded signature got us to our required signatures. we // need to return bool of true. (2) if we have a situation where the // required number of signatures was adjusted to at or lower than our current // signature count, by putting this here, an admin who has already signed, // can call the function again to make it return a true bool. but only if // they submit the correct msg data if (self.proposal_[_whatProposal].count == _requiredSignatures) { return(true); } } } // deletes proposal signature data after successfully executing a multiSig function function deleteProposal(Data storage self, bytes32 _whatFunction) internal { //done for readability sake bytes32 _whatProposal = whatProposal(_whatFunction); address _whichAdmin; //delete the admins votes & log. i know for loops are terrible. but we have to do this //for our data stored in mappings. simply deleting the proposal itself wouldn't accomplish this. for (uint256 i=0; i < self.proposal_[_whatProposal].count; i++) { _whichAdmin = self.proposal_[_whatProposal].log[i]; delete self.proposal_[_whatProposal].admin[_whichAdmin]; delete self.proposal_[_whatProposal].log[i]; } //delete the rest of the data in the record delete self.proposal_[_whatProposal]; } //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // HELPER FUNCTIONS //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ function whatProposal(bytes32 _whatFunction) private view returns(bytes32) { return(keccak256(abi.encodePacked(_whatFunction,this))); } //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // VANITY FUNCTIONS //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // returns a hashed version of msg.data sent by original signer for any given function function checkMsgData (Data storage self, bytes32 _whatFunction) internal view returns (bytes32 msg_data) { bytes32 _whatProposal = whatProposal(_whatFunction); return (self.proposal_[_whatProposal].msgData); } // returns number of signers for any given function function checkCount (Data storage self, bytes32 _whatFunction) internal view returns (uint256 signature_count) { bytes32 _whatProposal = whatProposal(_whatFunction); return (self.proposal_[_whatProposal].count); } // returns address of an admin who signed for any given function function checkSigner (Data storage self, bytes32 _whatFunction, uint256 _signer) internal view returns (address signer) { require(_signer > 0, "MSFun checkSigner failed - 0 not allowed"); bytes32 _whatProposal = whatProposal(_whatFunction); return (self.proposal_[_whatProposal].log[_signer - 1]); } }
deletes proposal signature data after successfully executing a multiSig functiondone for readability sakedelete the admins votes & log. i know for loops are terrible. but we have to do thisfor our data stored in mappings. simply deleting the proposal itself wouldn't accomplish this.
function deleteProposal(Data storage self, bytes32 _whatFunction) internal { bytes32 _whatProposal = whatProposal(_whatFunction); address _whichAdmin; for (uint256 i=0; i < self.proposal_[_whatProposal].count; i++) { _whichAdmin = self.proposal_[_whatProposal].log[i]; delete self.proposal_[_whatProposal].admin[_whichAdmin]; delete self.proposal_[_whatProposal].log[i]; } }
271,055
./partial_match/42/0x96567CA7b90a28CF16Bb24EB68f582A5660CBd9c/sources/Vault.sol
Indicates that the strategy update will happen in the future/
function announceStrategyUpdate(address _strategy, address _bridgeStrategy, uint256 when) external { onlyControllerOrGovernance(); require(_strategy != address(0), "V:8"); require(IBridgeStrategy(bridgeStrategy).underlying(strategy) == address(underlying), "V:9"); require(IBridgeStrategy(bridgeStrategy).vault(strategy) == address(this), "V:10"); require(when > 0, "V:11"); strategyUpdateTime = when; futureStrategy = _strategy; futureBridgeStrategy = _bridgeStrategy; }
3,479,703
pragma solidity ^0.4.24; import 'openzeppelin-solidity/contracts/math/SafeMath.sol'; import 'openzeppelin-solidity/contracts/math/Math.sol'; import 'openzeppelin-solidity/contracts/ownership/Ownable.sol'; import 'openzeppelin-solidity/contracts/lifecycle/Pausable.sol'; import 'openzeppelin-solidity/contracts/lifecycle/Destructible.sol'; import './libraries/strings.sol'; import './libraries/Array256Lib.sol'; import './BadgesLedger.sol'; /** * @title Mecenas * The main mecenas contract. Here is all the main logic to register * content creators and be able to support then via prepaid monthly * subscriptions. There is a percent fee + fixed fee per every subs * that goes to the contract owner to support development. Content * creators can withdraw their wage monthly. */ contract Mecenas is Ownable, Pausable, Destructible { using SafeMath for uint256; using Math for uint256; using Array256Lib for uint256[]; using strings for *; address public owner; uint256 public ownerBalance; BadgesLedger public badgesLedger; uint public feePercent; uint public fixedFee; struct PriceTierSuggestion { uint256 price; string title; string description; } struct MecenasMessage { bytes32 mecenasNick; address mecenasAddress; address contentCreatorAddress; string message; uint subscriptions; uint priceTier; } struct MecenasSupport { bytes32 nickname; address[] supportsContentCreators; } struct ContentCreator { bytes32 nickname; string description; uint256 creationTimestamp; uint256 subscriptionIndex; uint256 payday; uint256 balance; string ipfsAvatar; address[] mecenasAddresses; mapping (uint => uint256[]) mecenasSubscriptions; } struct Badge { uint256 tokenId; address contentCreatorAddress; } mapping (address => PriceTierSuggestion[3]) public suggestPriceTiers; mapping (address => MecenasMessage[]) public messageInbox; mapping (address => ContentCreator) public contentCreators; mapping (address => MecenasSupport) public mecenas; mapping (address => Badge[]) public mecenasBadges; mapping (bytes32 => address) public contentCreatorAddresses; /** * @dev Emits a new subscription message, from the mecenas to the content creator. * It can be showed in the main website or integrated into a streaming platform, * to show in live and see the content creator reaction. * * An integration with Twitch could be possible. */ event newSubscriptionMessage(address contentCreatorAddress, bytes32 mecenasNickname, string mecenasMessage); /** * Emits a new content creator. This can be consumed in the webapp to show latest content creators. */ event newContentCreator(address contentCreatorAddress, bytes32 nickname, string ipfsAvatar); /** * @dev Initialize the contract, sets an owner, a default feePercent and fixedFee. */ constructor() public { owner = msg.sender; feePercent = 1; fixedFee = 0.0006 ether; } /** @dev Set the badges ledger contract address * @param badgesLedgerAddress the Badges ledger deployed address */ function setBadgesLedgerContract(address badgesLedgerAddress) public onlyOwner { badgesLedger = BadgesLedger(badgesLedgerAddress); } /** * @dev Modifier to throw when msg.value is less than contract owner fee; */ modifier minimumAmount { require(msg.value > getMinimumAmount()); _; } /** * @dev Calculate and returns the minimum amount possible to surpass owner fees. * @return uint The minimum possible amount to surpass fees. */ function getMinimumAmount() public view returns(uint) { return fixedFee.add(fixedFee.mul(feePercent).div(100)); } /** * @dev Function that returns true if first argument is greater than minimum owner fee. * @param amount Test if amount is greater than minimum amount. * @return boolean */ function greaterThanMinimumAmount(uint amount) public view returns (bool) { return amount > getMinimumAmount(); } /** Owner functions **/ /** * @dev Set percent fee per content creator subscription. * @param newFee The new percent fee to be set */ function setPercentFee(uint256 newFee) public onlyOwner { feePercent = newFee; } /** * @dev Set fixed fee per content creator subscription. * @param newFee The new fixed fee to be set. */ function setFixedFee(uint256 newFee) public onlyOwner { fixedFee = newFee; } /** * @dev Pay the fee to the contract owner. Returns the remain amount to support the content creator. * @return uint256 Returns the remaining amount after fees. */ function payFee() private returns(uint256) { require(msg.value > getMinimumAmount()); uint256 currentAmount = msg.value; uint256 fee = fixedFee.add(currentAmount.mul(feePercent).div(100)); uint256 amountAfterFee = currentAmount - fee; require(amountAfterFee > 0); ownerBalance = ownerBalance + fee; return amountAfterFee; } /** @dev Withdraw owner fees, only callable by owner. */ function withdrawFees() public onlyOwner { // Remember to substract the pending withdraw before // sending to prevent re-entrancy attacks uint256 transferAmount = ownerBalance; ownerBalance -= transferAmount; msg.sender.transfer(transferAmount); } /** * Content creator functions */ /** @dev Get content creator tiers length, to be able to iterate it later. * @param contentCreatorAddress The content creator address. * @return The length of the array. */ function getTiersLength(address contentCreatorAddress) public view returns (uint) { return suggestPriceTiers[contentCreatorAddress].length; } /** @dev Get content creator tier content, by index. * @param contentCreatorAddress The content creator address. * @param index The index of the array. * @return title The title of the tier. * @return description The description of the tier. * @return price The price of the tier. */ function getTier(address contentCreatorAddress, uint index) public view returns ( string title, string description, uint price ) { PriceTierSuggestion memory tier = suggestPriceTiers[contentCreatorAddress][index]; title = tier.title; description = tier.description; price = tier.price; } /** @dev Content creator getter * @param addressInput The content creator address. * @return nickname The content creator name. * @return description Content creator description. * @return creationTimestamp Creation timestamp * @return payday Next content creator payday date * @return balance Current content creator balance * @return ipfsAvatar Current content creator Avatar IPFS hash * @return totalMecenas The number of subscriptions * @return contentCreatorAddress Address * @return wage The next wage value. */ function getContentCreator(address addressInput) public view returns ( bytes32 nickname, string description, uint256 creationTimestamp, uint256 payday, uint256 balance, string ipfsAvatar, uint256 totalMecenas, address contentCreatorAddress, uint256 wage ) { ContentCreator memory contentCreator = contentCreators[addressInput]; nickname = contentCreator.nickname; description = contentCreator.description; creationTimestamp = contentCreator.creationTimestamp; payday = contentCreator.payday; balance = contentCreator.balance; ipfsAvatar = contentCreator.ipfsAvatar; totalMecenas = contentCreator.mecenasAddresses.length; contentCreatorAddress = addressInput; wage = calculateNextWage(addressInput); } /** @dev Content creator getter * @param nickname The content creator nickname. * @return contentCreatorAddress address of content creator. */ function getContentCreatorAddress(bytes32 nickname) public view returns ( address contentCreatorAddress ) { contentCreatorAddress = contentCreatorAddresses[nickname]; } /** @dev Content creator getter * @param nick The content creator nickname. * @return nickname The content creator name. * @return description Content creator description. * @return creationTimestamp Creation timestamp * @return payday Next content creator payday date * @return balance Current content creator balance * @return ipfsAvatar Current content creator Avatar IPFS hash * @return totalMecenas The number of subscriptions * @return contentCreatorAddress Address * @return wage The next wage value. */ function getContentCreatorByNickname(bytes32 nick) public view returns ( bytes32 nickname, string description, uint256 creationTimestamp, uint256 payday, uint256 balance, string ipfsAvatar, uint256 totalMecenas, address contentCreatorAddress, uint256 wage ) { contentCreatorAddress = getContentCreatorAddress(nick); require(contentCreatorAddress != address(0)); ContentCreator memory contentCreator = contentCreators[contentCreatorAddress]; nickname = contentCreator.nickname; description = contentCreator.description; creationTimestamp = contentCreator.creationTimestamp; payday = contentCreator.payday; balance = contentCreator.balance; ipfsAvatar = contentCreator.ipfsAvatar; totalMecenas = contentCreator.mecenasAddresses.length; wage = calculateNextWage(contentCreatorAddress); } /** * @dev Sets the default price tiers to the current msg.sender */ function setDefaultPriceTiers() private { // Default tiers PriceTierSuggestion memory tierSilver = PriceTierSuggestion({ title: "Silver", description: "You will receive a Silver badge token in compensation, ocassional extra content like making-off videos or photos. And a lot of love.", price: getMinimumAmount() + 0.01 ether }); PriceTierSuggestion memory tierGold = PriceTierSuggestion({ title: "Gold", description: "You will receive a Gold badge token in compensation, extra video content and audio commentary of new and old videos. And a lot of love.", price: getMinimumAmount() + 0.02 ether }); PriceTierSuggestion memory tierPlatinum = PriceTierSuggestion({ title: "Platinum", description: "You will receive a Gold badge token in compensation, all of above and access to an exclusive forum, where i will reply to any question you want to ask to me. And a lot of love.", price: getMinimumAmount() + 0.05 ether }); suggestPriceTiers[msg.sender][0] = tierSilver; suggestPriceTiers[msg.sender][1] = tierGold; suggestPriceTiers[msg.sender][2] = tierPlatinum; } /** * @dev Gets the Mecenas Badge name for adding it to the Token URI * @param amount uint256 with the amount. * @param priceTiers The tiers of the content creator. */ function getSubscriberLevel(uint256 amount, PriceTierSuggestion[3] priceTiers) private pure returns (string){ bool levelFound = false; uint priceTierIndex = 0; uint currentLevel = 0; for(uint counter = 0; counter < 3; counter++){ if(amount > uint(priceTiers[counter].price)) { if (uint(priceTiers[counter].price) > currentLevel) { currentLevel = priceTiers[counter].price; priceTierIndex = counter; if (levelFound == false) { levelFound = true; } } } } if (levelFound == false) { return "Subscriber"; } return priceTiers[priceTierIndex].title; } /** @dev Content creator getter * @param nickname The content creator name. * @param description Content creator description. * @param ipfsAvatar Current content creator Avatar IPFS hash */ function contentCreatorFactory(bytes32 nickname, string description, string ipfsAvatar) public whenNotPaused { ContentCreator storage contentCreator = contentCreators[msg.sender]; // At least nickname must be greater than zero chars, be unique, and content creator must not exists require(nickname.length > 0 && contentCreatorAddresses[nickname] == address(0) && contentCreator.payday == 0); // Initialize a new content creator contentCreatorAddresses[nickname] = msg.sender; contentCreator.nickname = nickname; contentCreator.description = description; contentCreator.creationTimestamp = now; contentCreator.payday = now + 30 days; contentCreator.balance = 0; contentCreator.ipfsAvatar = ipfsAvatar; contentCreator.subscriptionIndex = 1; setDefaultPriceTiers(); // Emit content creator event emit newContentCreator(msg.sender, nickname, ipfsAvatar); } /** * @dev Change the content creator address, only allowed by content creator itself. * @param newAddress The new address to be set. */ function changeContentCreatorAddress(address newAddress) public whenNotPaused { ContentCreator memory current = contentCreators[msg.sender]; require(current.payday > 0); delete contentCreators[msg.sender]; delete contentCreatorAddresses[current.nickname]; contentCreators[newAddress] = current; contentCreatorAddresses[current.nickname] = newAddress; } /** * @dev Change the content creator avatar, only allowed by content creator itself. * @param avatarHash The new avatar IPFS hash to be set. */ function changeAvatar(string avatarHash) public whenNotPaused { ContentCreator storage current = contentCreators[msg.sender]; require(current.payday > 0); current.ipfsAvatar = avatarHash; } /** * @dev Change the content creator tier, by index, only allowed by content creator itself. * @param tierIndex The tier index to change. * @param title The new title name to be set. * @param description The new description to be set. * @param price The new price to be set. */ function changeContentCreatorTiers(uint tierIndex, string title, string description, uint256 price) public whenNotPaused { ContentCreator storage current = contentCreators[msg.sender]; // Check if content creator is initialized, price is greater than minimum amount and string params are not empty. require(current.payday > 0 && price > getMinimumAmount() && bytes(title).length > 0 && bytes(description).length > 0); // Replace value in global map variable suggestPriceTiers[msg.sender][tierIndex] = PriceTierSuggestion({ title: title, description: description, price: price }); } /** * @dev Change the content creator description, only allowed by content creator itself. * @param description The new description to be set. */ function changeDescription(string description) public whenNotPaused { ContentCreator storage current = contentCreators[msg.sender]; require(current.payday > 0); current.description = description; } /** * @dev Calculate next content creator wage. * @param contentCreatorAddress Content creator address * @return uint with the next content creator wage. */ function calculateNextWage(address contentCreatorAddress) public view returns (uint256){ ContentCreator storage contentCreator = contentCreators[contentCreatorAddress]; return contentCreator.mecenasSubscriptions[contentCreator.subscriptionIndex].sumElements(); } /** * @dev Allow content creator to withdraw once the payload date is greater or equal than today. If contract * is paused, this function is still reachable for content creators. */ function monthlyWithdraw() public { ContentCreator storage current = contentCreators[msg.sender]; uint nextWage = current.mecenasSubscriptions[current.subscriptionIndex].sumElements(); // Allow withdraw only after payday require(now >= current.payday && current.balance > 0); // If the current balance is less than the theorical monthly withdraw, withdraw that lower amount. uint transferAmount = current.balance.min256(nextWage); // Remember to lock the withdraw function until next month current.payday = current.payday + 30 days; // Point to the next subscription index current.subscriptionIndex = current.subscriptionIndex + 1; // Remember to substract the pending withdraw before // sending to prevent re-entrancy attacks current.balance = current.balance - transferAmount; msg.sender.transfer(transferAmount); } /** Mecenas functions **/ /** * @dev Emit a Mecenas Message event to be consumed in a stream or website. Show the support from the mecenas to the content creator. * @param mecenasNickname Mecenas nickname. * @param contentCreatorAddress Content creator address subscription. * @param message Mecenas message. * @param subscriptions Number of months subbed. * @param priceTier The subscription price per month. */ function broadcastNewSubscription(bytes32 mecenasNickname, address contentCreatorAddress, string message, uint256 subscriptions, uint256 priceTier) private { MecenasMessage memory newSubMessage = MecenasMessage({ mecenasNick: mecenasNickname, mecenasAddress: msg.sender, contentCreatorAddress: contentCreatorAddress, message: message, subscriptions: subscriptions, priceTier: priceTier }); // Save message into storage messageInbox[contentCreatorAddress].push(newSubMessage); // Send a new subscription event emit newSubscriptionMessage(newSubMessage.contentCreatorAddress, newSubMessage.mecenasNick, newSubMessage.message); } /** * @dev Support a determined content creator, via a prepaid monthly subscription. * You can set any price, regarding the suggested price tiers, and add a support message to the content creator. * @param mecenasNickname Mecenas nickname. * @param contentCreatorAddress Content creator address subscription. * @param message Mecenas message. * @param subscriptions Number of months subbed. */ function supportContentCreator(address contentCreatorAddress, uint256 subscriptions, string message, bytes32 mecenasNickname) public payable whenNotPaused{ require(contentCreatorAddress != address(0) && msg.value > 0); // Calculate fee and sum to contract owner balance uint256 amountAfterFees = payFee(); // Calculate price per month subscription (totalAmount / months = priceTier) uint256 priceTier = amountAfterFees.div(subscriptions); ContentCreator storage contentCreator = contentCreators[contentCreatorAddress]; require(contentCreator.subscriptionIndex >= 1); // Add the subscriptions to the content creator for (uint newSub = 0; newSub < subscriptions; newSub++) { contentCreator.mecenasSubscriptions[contentCreator.subscriptionIndex + newSub].push(priceTier); contentCreator.balance = contentCreator.balance + priceTier; } // Add the mecenas address to the content creator contentCreator.mecenasAddresses.push(msg.sender); // Save mecenas into global variable mecenas[msg.sender].nickname = mecenasNickname; mecenas[msg.sender].supportsContentCreators.push(contentCreatorAddress); // Mint SubscriptionBadge to Mecenas uint tokenId = badgesLedger.totalSupply() + 1; string memory subscriptionLevel = getSubscriberLevel(priceTier, suggestPriceTiers[contentCreatorAddress]); // Token uri contains "level" string string memory tokenUri = subscriptionLevel; badgesLedger.mintSubscriptionBadge(msg.sender, tokenId, tokenUri); // Save token into separate map, that contains tokenId and contentCreator address, mapped by mecenas address. Badge[] storage mecenasTokens = mecenasBadges[msg.sender]; mecenasTokens.push(Badge({tokenId: tokenId, contentCreatorAddress: contentCreatorAddress})); // Send message to the content creator inbox and emit event broadcastNewSubscription(mecenasNickname, contentCreatorAddress, message, subscriptions, priceTier); } }
Get content creator tier content, by index. contentCreatorAddress The content creator address. index The index of the array. return title The title of the tier. return description The description of the tier. return price The price of the tier./
function getTier(address contentCreatorAddress, uint index) public view returns ( string title, string description, uint price ) { PriceTierSuggestion memory tier = suggestPriceTiers[contentCreatorAddress][index]; title = tier.title; description = tier.description; price = tier.price; }
7,284,489
pragma solidity ^0.4.24; contract Utils { function stringToBytes32(string memory source) internal pure returns (bytes32 result) { assembly { result := mload(add(source, 32)) } } function bytes32ToString(bytes32 x) internal pure returns (string) { bytes memory bytesString = new bytes(32); uint charCount = 0; for (uint j = 0; j < 32; j++) { byte char = byte(bytes32(uint(x) * 2 ** (8 * j))); if (char != 0) { bytesString[charCount] = char; charCount++; } } bytes memory bytesStringTrimmed = new bytes(charCount); for (j = 0; j < charCount; j++) { bytesStringTrimmed[j] = bytesString[j]; } return string(bytesStringTrimmed); } } contract Score is Utils { address owner; //合约的拥有者,银行 uint issuedScoreAmount; //银行已经发行的积分总数 uint settledScoreAmount; //银行已经清算的积分总数 struct Customer { address customerAddr; //客户address bytes32 password; //客户密码 uint scoreAmount; //积分余额 bytes32[] buyGoods; //购买的商品数组 } struct Merchant { address merchantAddr; //商户address bytes32 password; //商户密码 uint scoreAmount; //积分余额 bytes32[] sellGoods; //发布的商品数组 } struct Good { bytes32 goodId; //商品Id; uint price; //价格; address belong; //商品属于哪个商户address; } mapping(address => Customer) customer; mapping(address => Merchant) merchant; mapping(bytes32 => Good) good; //根据商品Id查找该件商品 address[] customers; //已注册的客户数组 address[] merchants; //已注册的商户数组 bytes32[] goods; //已经上线的商品数组 //增加权限控制,某些方法只能由合约的创建者调用 modifier onlyOwner(){ if (msg.sender == owner) _; } //构造函数 constructor() public { owner = msg.sender; } //返回合约调用者地址 function getOwner() constant public returns (address) { return owner; } //注册一个客户 event NewCustomer(address sender, bool isSuccess, string password); function newCustomer(address _customerAddr, string _password) public { //判断是否已经注册 if (!isCustomerAlreadyRegister(_customerAddr)) { //还未注册 customer[_customerAddr].customerAddr = _customerAddr; customer[_customerAddr].password = stringToBytes32(_password); customers.push(_customerAddr); emit NewCustomer(msg.sender, true, _password); return; } else { emit NewCustomer(msg.sender, false, _password); return; } } //注册一个商户 event NewMerchant(address sender, bool isSuccess, string message); function newMerchant(address _merchantAddr, string _password) public { //判断是否已经注册 if (!isMerchantAlreadyRegister(_merchantAddr)) { //还未注册 merchant[_merchantAddr].merchantAddr = _merchantAddr; merchant[_merchantAddr].password = stringToBytes32(_password); merchants.push(_merchantAddr); emit NewMerchant(msg.sender, true, "注册成功"); return; } else { emit NewMerchant(msg.sender, false, "该账户已经注册"); return; } } //判断一个客户是否已经注册 function isCustomerAlreadyRegister(address _customerAddr) internal view returns (bool) { for (uint i = 0; i < customers.length; i++) { if (customers[i] == _customerAddr) { return true; } } return false; } //判断一个商户是否已经注册 function isMerchantAlreadyRegister(address _merchantAddr) public view returns (bool) { for (uint i = 0; i < merchants.length; i++) { if (merchants[i] == _merchantAddr) { return true; } } return false; } //查询用户密码 function getCustomerPassword(address _customerAddr) constant public returns (bool, bytes32) { //先判断该用户是否注册 if (isCustomerAlreadyRegister(_customerAddr)) { return (true, customer[_customerAddr].password); } else { return (false, ""); } } //查询商户密码 function getMerchantPassword(address _merchantAddr) constant public returns (bool, bytes32) { //先判断该商户是否注册 if (isMerchantAlreadyRegister(_merchantAddr)) { return (true, merchant[_merchantAddr].password); } else { return (false, ""); } } //银行发送积分给客户,只能被银行调用,且只能发送给客户 event SendScoreToCustomer(address sender, string message); function sendScoreToCustomer(address _receiver, uint _amount) onlyOwner public { if (isCustomerAlreadyRegister(_receiver)) { //已经注册 issuedScoreAmount += _amount; customer[_receiver].scoreAmount += _amount; emit SendScoreToCustomer(msg.sender, "发行积分成功"); return; } else { //还没注册 emit SendScoreToCustomer(msg.sender, "该账户未注册,发行积分失败"); return; } } //根据客户address查找余额 function getScoreWithCustomerAddr(address customerAddr) constant public returns (uint) { return customer[customerAddr].scoreAmount; } //根据商户address查找余额 function getScoreWithMerchantAddr(address merchantAddr) constant public returns (uint) { return merchant[merchantAddr].scoreAmount; } //两个账户转移积分,任意两个账户之间都可以转移,客户商户都调用该方法 //_senderType表示调用者类型,0表示客户,1表示商户 event TransferScoreToAnother(address sender, string message); function transferScoreToAnother(uint _senderType, address _sender, address _receiver, uint _amount) public { if (!isCustomerAlreadyRegister(_receiver) && !isMerchantAlreadyRegister(_receiver)) { //目的账户不存在 emit TransferScoreToAnother(msg.sender, "目的账户不存在,请确认后再转移!"); return; } if (_senderType == 0) { //客户转移 if (customer[_sender].scoreAmount >= _amount) { customer[_sender].scoreAmount -= _amount; if (isCustomerAlreadyRegister(_receiver)) { //目的地址是客户 customer[_receiver].scoreAmount += _amount; } else { merchant[_receiver].scoreAmount += _amount; } emit TransferScoreToAnother(msg.sender, "积分转让成功!"); return; } else { emit TransferScoreToAnother(msg.sender, "你的积分余额不足,转让失败!"); return; } } else { //商户转移 if (merchant[_sender].scoreAmount >= _amount) { merchant[_sender].scoreAmount -= _amount; if (isCustomerAlreadyRegister(_receiver)) { //目的地址是客户 customer[_receiver].scoreAmount += _amount; } else { merchant[_receiver].scoreAmount += _amount; } emit TransferScoreToAnother(msg.sender, "积分转让成功!"); return; } else { emit TransferScoreToAnother(msg.sender, "你的积分余额不足,转让失败!"); return; } } } //银行查找已经发行的积分总数 function getIssuedScoreAmount() constant public returns (uint) { return issuedScoreAmount; } //银行查找已经清算的积分总数 function getSettledScoreAmount() constant public returns (uint) { return settledScoreAmount; } //商户添加一件商品 event AddGood(address sender, bool isSuccess, string message); function addGood(address _merchantAddr, string _goodId, uint _price) public { bytes32 tempId = stringToBytes32(_goodId); //首先判断该商品Id是否已经存在 if (!isGoodAlreadyAdd(tempId)) { good[tempId].goodId = tempId; good[tempId].price = _price; good[tempId].belong = _merchantAddr; goods.push(tempId); merchant[_merchantAddr].sellGoods.push(tempId); emit AddGood(msg.sender, true, "创建商品成功"); return; } else { emit AddGood(msg.sender, false, "该件商品已经添加,请确认后操作"); return; } } //商户查找自己的商品数组 function getGoodsByMerchant(address _merchantAddr) constant public returns (bytes32[]) { return merchant[_merchantAddr].sellGoods; } //用户用积分购买一件商品 event BuyGood(address sender, bool isSuccess, string message); function buyGood(address _customerAddr, string _goodId) public { //首先判断输入的商品Id是否存在 bytes32 tempId = stringToBytes32(_goodId); if (isGoodAlreadyAdd(tempId)) { //该件商品已经添加,可以购买 if (customer[_customerAddr].scoreAmount < good[tempId].price) { emit BuyGood(msg.sender, false, "余额不足,购买商品失败"); return; } else { //对这里的方法抽取 customer[_customerAddr].scoreAmount -= good[tempId].price; merchant[good[tempId].belong].scoreAmount += good[tempId].price; customer[_customerAddr].buyGoods.push(tempId); emit BuyGood(msg.sender, true, "购买商品成功"); return; } } else { //没有这个Id的商品 emit BuyGood(msg.sender, false, "输入商品Id不存在,请确定后购买"); return; } } //客户查找自己的商品数组 function getGoodsByCustomer(address _customerAddr) constant public returns (bytes32[]) { return customer[_customerAddr].buyGoods; } //首先判断输入的商品Id是否存在 function isGoodAlreadyAdd(bytes32 _goodId) internal view returns (bool) { for (uint i = 0; i < goods.length; i++) { if (goods[i] == _goodId) { return true; } } return false; } //商户和银行清算积分 event SettleScoreWithBank(address sender, string message); function settleScoreWithBank(address _merchantAddr, uint _amount) public { if (merchant[_merchantAddr].scoreAmount >= _amount) { merchant[_merchantAddr].scoreAmount -= _amount; settledScoreAmount += _amount; emit SettleScoreWithBank(msg.sender, "积分清算成功"); return; } else { emit SettleScoreWithBank(msg.sender, "您的积分余额不足,清算失败"); return; } } }
目的账户不存在客户转移目的地址是客户商户转移目的地址是客户
function transferScoreToAnother(uint _senderType, address _sender, address _receiver, uint _amount) public { if (!isCustomerAlreadyRegister(_receiver) && !isMerchantAlreadyRegister(_receiver)) { emit TransferScoreToAnother(msg.sender, "目的账户不存在,请确认后再转移!"); return; } if (_senderType == 0) { if (customer[_sender].scoreAmount >= _amount) { customer[_sender].scoreAmount -= _amount; if (isCustomerAlreadyRegister(_receiver)) { customer[_receiver].scoreAmount += _amount; merchant[_receiver].scoreAmount += _amount; } emit TransferScoreToAnother(msg.sender, "积分转让成功!"); return; emit TransferScoreToAnother(msg.sender, "你的积分余额不足,转让失败!"); return; } if (merchant[_sender].scoreAmount >= _amount) { merchant[_sender].scoreAmount -= _amount; if (isCustomerAlreadyRegister(_receiver)) { customer[_receiver].scoreAmount += _amount; merchant[_receiver].scoreAmount += _amount; } emit TransferScoreToAnother(msg.sender, "积分转让成功!"); return; emit TransferScoreToAnother(msg.sender, "你的积分余额不足,转让失败!"); return; } } }
12,970,607
./partial_match/4/0xfEA88eF98dd313B5c52c814BE5CA1aeFCCDbc796/sources/REVVInventory.sol
See {IERC721-approve(address,uint256)}.
function approve(address to, uint256 nftId) external virtual override { address tokenOwner = ownerOf(nftId); require(to != tokenOwner, "Inventory: self-approval"); address sender = _msgSender(); require((sender == tokenOwner) || _operators[tokenOwner][sender], "Inventory: non-approved sender"); _owners[nftId] = uint256(tokenOwner) | _APPROVAL_BIT_TOKEN_OWNER_; _nftApprovals[nftId] = to; emit Approval(tokenOwner, to, nftId); }
8,622,817
pragma solidity ^0.4.10; import "Ownable.sol"; import "Administrator.sol"; import "Identified.sol"; contract IDChain is Ownable { address public partiesContract; address public storageContract; //Data store Administrator public admin; Identified public identified; mapping (bytes32 => mapping (bytes32 => address )) MHash1; mapping (address => mapping (bytes32 => bool )) MTokenPerm; event eHashAdded(bytes32 _hash); //event eAnswer(address _to, bytes32 _token, bool _result); //event eIdentified(bytes32 token, bytes32 hash); event eTokenGiven(address _to, bytes32 _token); event eAddCustomerHash(bytes32 _token, bytes32 _hash, address _address, uint8 _role); /* Initialization*/ function IDChain() { } function SetAdminContract(address _address) onlyOwner { partiesContract = _address; admin = Administrator(partiesContract); } //function SetStorageContract(address _address) onlyOwner { // storageContract = _address; // //idstorage = idStorage(_address); //} function SetIdentifiedContract(address _address) onlyOwner { identified = Identified(_address); } function GetPartyRole(address _address) constant returns (uint8){ //admin = Administrator(partiesContract); return admin.GetParticipantRole(_address); } function addCustomerHash(bytes32 _token, bytes32 _hash) returns (bool result){ //bool result = false; uint8 crole = GetPartyRole(msg.sender); eAddCustomerHash(_token, _hash, msg.sender, crole); if ( crole == 0 || crole == 1 || crole == 3){ return false; } if (_token.length == 0 || _hash.length ==0){ return false; } MHash1[_token][_hash] = msg.sender; eHashAdded(_hash); //idstorage.setParticipantHash(_token, _hash, msg.sender, true); return true; } function GiveTokenPerm(address _address, bytes32 _token) returns (bool result){ uint8 crole = GetPartyRole(msg.sender); if (_address == msg.sender){ return false; } if (crole == 0 || crole == 1 || crole == 3){ return false; } MTokenPerm[_address][_token] = true; //idstorage.setTokenPermission(_address, _token, true); eTokenGiven(_address, _token); return true; } function RequestP(bytes32 _token, bytes32 _hash) returns(bool hres1){ //if (!idstorage.getTokenPermission(msg.sender, _token)){ // return; //} //if ( idstorage.getParticipantHashAddress(_token, _hash) != address(0x0) // && idstorage.getParticipantHashBool(_token, _hash) // ){ if (!MTokenPerm[msg.sender][_token]){ return; } address _donor = MHash1[_token][_hash]; if ( _donor != address(0x0) ){ hres1 = true; //eIdentified(_token, _hash); identified.identified(_donor, msg.sender, _hash); } else { hres1 = false; } } function RequestTest(bytes32 _token, bytes32 _hash) onlyOwner constant returns(address){ //return (idstorage.getParticipantHashAddress(_token, _hash), // idstorage.getParticipantHashBool(_token, _hash) // ); return (MHash1[_token][_hash] ); } function RequestC(bytes32 _token, bytes32 _hash) constant returns(bool hres){ //if ( idstorage.getParticipantHashAddress(_token, _hash) != address(0x0) // && idstorage.getParticipantHashBool(_token, _hash) // ){ if ( MHash1[_token][_hash] != address(0x0) ){ hres = true; } else { hres = false; } } /* This unnamed function is called whenever someone tries to send ether to it */ function () { throw; // Prevents accidental sending of ether } }
bool result = false;
function addCustomerHash(bytes32 _token, bytes32 _hash) returns (bool result){ uint8 crole = GetPartyRole(msg.sender); eAddCustomerHash(_token, _hash, msg.sender, crole); if ( crole == 0 || crole == 1 || crole == 3){ return false; } if (_token.length == 0 || _hash.length ==0){ return false; } MHash1[_token][_hash] = msg.sender; eHashAdded(_hash); return true; }
7,303,011
./full_match/80001/0x784665Fb071C433CA4d2c9Fe413c93FA07Ca036B/sources/src/GameAccessControl.sol
Function to check goal id claim _goalId Unique identifier of the goal/
function _checkVerifierClaims(uint256 _goalId) internal view onlyVerifier(_msgSender()) { _checkClaim(_msgSender(), GOAL_ID_CLAIM, keccak256(abi.encodePacked(_goalId))); }
9,465,609
pragma solidity ^0.4.21; /// @title ERC-165 Standard Interface Detection /// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md interface ERC165 { function supportsInterface(bytes4 interfaceID) external view returns (bool); } /** * @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)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /// @title ERC-721 Non-Fungible Token Standard /// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md contract ERC721 is ERC165 { 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) external view returns (uint256); function ownerOf(uint256 _tokenId) external view returns (address); function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) public payable; function safeTransferFrom(address _from, address _to, uint256 _tokenId) public payable; function transferFrom(address _from, address _to, uint256 _tokenId) external payable; function approve(address _approved, uint256 _tokenId) external payable; function setApprovalForAll(address _operator, bool _approved) external; function getApproved(uint256 _tokenId) external view returns (address); function isApprovedForAll(address _owner, address _operator) external view returns (bool); } /// @title ERC-721 Non-Fungible Token Standard interface ERC721TokenReceiver { function onERC721Received(address _from, uint256 _tokenId, bytes data) external returns(bytes4); } /// @title ERC-721 Non-Fungible Token Standard, optional metadata extension interface ERC721Metadata /* is ERC721 */ { function name() external pure returns (string _name); function symbol() external pure returns (string _symbol); function tokenURI(uint256 _tokenId) external view returns (string); } /// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension interface ERC721Enumerable /* is ERC721 */ { function totalSupply() external view returns (uint256); function tokenByIndex(uint256 _index) external view returns (uint256); function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256); } /// @title A reusable contract to comply with ERC-165 /// @author William Entriken (https://phor.net) contract PublishInterfaces is ERC165 { /// @dev Every interface that we support mapping(bytes4 => bool) internal supportedInterfaces; function PublishInterfaces() internal { supportedInterfaces[0x01ffc9a7] = true; // 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. /// @return `true` if the contract implements `interfaceID` and /// `interfaceID` is not 0xffffffff, `false` otherwise function supportsInterface(bytes4 interfaceID) external view returns (bool) { return supportedInterfaces[interfaceID] && (interfaceID != 0xffffffff); } } /// @title The external contract that is responsible for generating metadata for GanTokens, /// it has one function that will return the data as bytes. contract Metadata { /// @dev Given a token Id, returns a string with metadata function getMetadata(uint256 _tokenId, string) public pure returns (bytes32[4] buffer, uint256 count) { if (_tokenId == 1) { buffer[0] = "Hello World! :D"; count = 15; } else if (_tokenId == 2) { buffer[0] = "I would definitely choose a medi"; buffer[1] = "um length string."; count = 49; } else if (_tokenId == 3) { buffer[0] = "Lorem ipsum dolor sit amet, mi e"; buffer[1] = "st accumsan dapibus augue lorem,"; buffer[2] = " tristique vestibulum id, libero"; buffer[3] = " suscipit varius sapien aliquam."; count = 128; } } } contract GanNFT is ERC165, ERC721, ERC721Enumerable, PublishInterfaces, Ownable { function GanNFT() internal { supportedInterfaces[0x80ac58cd] = true; // ERC721 supportedInterfaces[0x5b5e139f] = true; // ERC721Metadata supportedInterfaces[0x780e9d63] = true; // ERC721Enumerable supportedInterfaces[0x8153916a] = true; // ERC721 + 165 (not needed) } bytes4 private constant ERC721_RECEIVED = bytes4(keccak256("onERC721Received(address,uint256,bytes)")); // @dev claim price taken for each new GanToken // generating a new token will be free in the beinging and later changed uint256 public claimPrice = 0; // @dev max supply for token uint256 public maxSupply = 300; // The contract that will return tokens metadata Metadata public erc721Metadata; /// @dev list of all owned token ids uint256[] public tokenIds; /// @dev a mpping for all tokens mapping(uint256 => address) public tokenIdToOwner; /// @dev mapping to keep owner balances mapping(address => uint256) public ownershipCounts; /// @dev mapping to owners to an array of tokens that they own mapping(address => uint256[]) public ownerBank; /// @dev mapping to approved ids mapping(uint256 => address) public tokenApprovals; /// @dev The authorized operators for each address mapping (address => mapping (address => bool)) internal operatorApprovals; /// @notice A descriptive name for a collection of NFTs in this contract function name() external pure returns (string) { return "GanToken"; } /// @notice An abbreviated name for NFTs in this contract function symbol() external pure returns (string) { return "GT"; } /// @dev Set the address of the sibling contract that tracks metadata. /// Only the contract creater can call this. /// @param _contractAddress The location of the contract with meta data function setMetadataAddress(address _contractAddress) public onlyOwner { erc721Metadata = Metadata(_contractAddress); } modifier canTransfer(uint256 _tokenId, address _from, address _to) { address owner = tokenIdToOwner[_tokenId]; require(tokenApprovals[_tokenId] == _to || owner == _from || operatorApprovals[_to][_to]); _; } /// @notice checks to see if a sender owns a _tokenId /// @param _tokenId The identifier for an NFT modifier owns(uint256 _tokenId) { require(tokenIdToOwner[_tokenId] == msg.sender); _; } /// @dev This emits any time the ownership of a GanToken changes. event Transfer(address indexed _from, address indexed _to, uint256 _value); /// @dev This emits when the approved addresses for a GanToken is changed or reaffirmed. /// The zero address indicates there is no owner and it get reset on a transfer event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); /// @dev This emits when an operator is enabled or disabled for an owner. /// The operator can manage all NFTs of the owner. event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); /// @notice allow the owner to set the supply max function setMaxSupply(uint max) external payable onlyOwner { require(max > tokenIds.length); maxSupply = max; } /// @notice allow the owner to set a new fee for creating a GanToken function setClaimPrice(uint256 price) external payable onlyOwner { claimPrice = price; } /// @dev Required for ERC-721 compliance. function balanceOf(address _owner) external view returns (uint256 balance) { balance = ownershipCounts[_owner]; } /// @notice Gets the onwner of a an NFT /// @param _tokenId The identifier for an NFT /// @dev Required for ERC-721 compliance. function ownerOf(uint256 _tokenId) external view returns (address owner) { owner = tokenIdToOwner[_tokenId]; } /// @notice returns all owners&#39; tokens will return an empty array /// if the address has no tokens /// @param _owner The address of the owner in question function tokensOfOwner(address _owner) external view returns (uint256[]) { uint256 tokenCount = ownershipCounts[_owner]; if (tokenCount == 0) { return new uint256[](0); } uint256[] memory result = new uint256[](tokenCount); for (uint256 i = 0; i < tokenCount; i++) { result[i] = ownerBank[_owner][i]; } return result; } /// @dev creates a list of all the tokenIds function getAllTokenIds() external view returns (uint256[]) { uint256[] memory result = new uint256[](tokenIds.length); for (uint i = 0; i < result.length; i++) { result[i] = tokenIds[i]; } return result; } /// @notice Create a new GanToken with a id and attaches an owner /// @param _noise The id of the token that&#39;s being created function newGanToken(uint256 _noise) external payable { require(msg.sender != address(0)); require(tokenIdToOwner[_noise] == 0x0); require(tokenIds.length < maxSupply); require(msg.value >= claimPrice); tokenIds.push(_noise); ownerBank[msg.sender].push(_noise); tokenIdToOwner[_noise] = msg.sender; ownershipCounts[msg.sender]++; emit Transfer(address(0), msg.sender, 0); } /// @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,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) public payable { _safeTransferFrom(_from, _to, _tokenId, data); } /// @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) public payable { _safeTransferFrom(_from, _to, _tokenId, ""); } /// @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(_to != 0x0); require(_to != address(this)); require(tokenApprovals[_tokenId] == msg.sender); require(tokenIdToOwner[_tokenId] == _from); _transfer(_tokenId, _to); } /// @notice Grant another address the right to transfer a specific token via /// transferFrom(). This is the preferred flow for transfering NFTs to contracts. /// @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. /// @dev Required for ERC-721 compliance. /// @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, uint256 _tokenId) external owns(_tokenId) payable { // Register the approval (replacing any previous approval). tokenApprovals[_tokenId] = _to; emit Approval(msg.sender, _to, _tokenId); } /// @notice Enable or disable approval for a third party ("operator") to manage /// all your asset. /// @dev Emits the ApprovalForAll event /// @param _operator Address to add to the set of authorized operators. /// @param _approved True if the operators is approved, false to revoke approval function setApprovalForAll(address _operator, bool _approved) external { operatorApprovals[msg.sender][_operator] = _approved; emit ApprovalForAll(msg.sender, _operator, _approved); } /// @notice Get the approved address for a single 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 operatorApprovals[_owner][_operator]; } /// @notice Count NFTs tracked by this contract /// @return A count of valid NFTs tracked by this contract, where each one of /// them has an assigned and queryable owner not equal to the zero address /// @dev Required for ERC-721 compliance. function totalSupply() external view returns (uint256) { return tokenIds.length; } /// @notice Enumerate valid NFTs /// @param _index A counter less than `totalSupply()` /// @return The token identifier for index the `_index`th NFT 0 if it doesn&#39;t exist, function tokenByIndex(uint256 _index) external view returns (uint256) { return tokenIds[_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 _tokenId) { require(_owner != address(0)); require(_index < ownerBank[_owner].length); _tokenId = ownerBank[_owner][_index]; } function _transfer(uint256 _tokenId, address _to) internal { require(_to != address(0)); address from = tokenIdToOwner[_tokenId]; uint256 tokenCount = ownershipCounts[from]; // remove from ownerBank and replace the deleted token id for (uint256 i = 0; i < tokenCount; i++) { uint256 ownedId = ownerBank[from][i]; if (_tokenId == ownedId) { delete ownerBank[from][i]; if (i != tokenCount) { ownerBank[from][i] = ownerBank[from][tokenCount - 1]; } break; } } ownershipCounts[from]--; ownershipCounts[_to]++; ownerBank[_to].push(_tokenId); tokenIdToOwner[_tokenId] = _to; tokenApprovals[_tokenId] = address(0); emit Transfer(from, _to, 1); } /// @dev Actually perform the safeTransferFrom function _safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) private canTransfer(_tokenId, _from, _to) { address owner = tokenIdToOwner[_tokenId]; require(owner == _from); require(_to != address(0)); require(_to != address(this)); _transfer(_tokenId, _to); // Do the callback after everything is done to avoid reentrancy attack uint256 codeSize; assembly { codeSize := extcodesize(_to) } if (codeSize == 0) { return; } bytes4 retval = ERC721TokenReceiver(_to).onERC721Received(_from, _tokenId, data); require(retval == ERC721_RECEIVED); } /// @dev Adapted from memcpy() by @arachnid (Nick Johnson <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d5b4a7b4b6bdbbbcb195bbbaa1b1baa1fbbbb0a1">[email&#160;protected]</a>>) /// This method is licenced under the Apache License. /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol function _memcpy(uint _dest, uint _src, uint _len) private pure { // Copy word-length chunks while possible for(; _len >= 32; _len -= 32) { assembly { mstore(_dest, mload(_src)) } _dest += 32; _src += 32; } // Copy remaining bytes uint256 mask = 256 ** (32 - _len) - 1; assembly { let srcpart := and(mload(_src), not(mask)) let destpart := and(mload(_dest), mask) mstore(_dest, or(destpart, srcpart)) } } /// @dev Adapted from toString(slice) by @arachnid (Nick Johnson <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b1d0c3d0d2d9dfd8d5f1dfdec5d5dec59fdfd4c5">[email&#160;protected]</a>>) /// This method is licenced under the Apache License. /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol function _toString(bytes32[4] _rawBytes, uint256 _stringLength) private pure returns (string) { string memory outputString = new string(_stringLength); uint256 outputPtr; uint256 bytesPtr; assembly { outputPtr := add(outputString, 32) bytesPtr := _rawBytes } _memcpy(outputPtr, bytesPtr, _stringLength); return outputString; } /// @notice Returns a URI pointing to a metadata package for this token conforming to /// ERC-721 (https://github.com/ethereum/EIPs/issues/721) /// @param _tokenId The ID number of the GanToken whose metadata should be returned. function tokenMetadata(uint256 _tokenId, string _preferredTransport) external view returns (string infoUrl) { require(erc721Metadata != address(0)); uint256 count; bytes32[4] memory buffer; (buffer, count) = erc721Metadata.getMetadata(_tokenId, _preferredTransport); return _toString(buffer, count); } } contract GanTokenMain is GanNFT { struct Offer { bool isForSale; uint256 tokenId; address seller; uint value; // in ether address onlySellTo; // specify to sell only to a specific person } struct Bid { bool hasBid; uint256 tokenId; address bidder; uint value; } /// @dev mapping of balances for address mapping(address => uint256) public pendingWithdrawals; /// @dev mapping of tokenId to to an offer mapping(uint256 => Offer) public ganTokenOfferedForSale; /// @dev mapping bids to tokenIds mapping(uint256 => Bid) public tokenBids; event BidForGanTokenOffered(uint256 tokenId, uint256 value, address sender); event BidWithdrawn(uint256 tokenId, uint256 value, address bidder); event GanTokenOfferedForSale(uint256 tokenId, uint256 minSalePriceInWei, address onlySellTo); event GanTokenNoLongerForSale(uint256 tokenId); /// @notice Allow a token owner to pull sale /// @param tokenId The id of the token that&#39;s created function ganTokenNoLongerForSale(uint256 tokenId) public payable owns(tokenId) { ganTokenOfferedForSale[tokenId] = Offer(false, tokenId, msg.sender, 0, 0x0); emit GanTokenNoLongerForSale(tokenId); } /// @notice Put a token up for sale /// @param tokenId The id of the token that&#39;s created /// @param minSalePriceInWei desired price of token function offerGanTokenForSale(uint tokenId, uint256 minSalePriceInWei) external payable owns(tokenId) { ganTokenOfferedForSale[tokenId] = Offer(true, tokenId, msg.sender, minSalePriceInWei, 0x0); emit GanTokenOfferedForSale(tokenId, minSalePriceInWei, 0x0); } /// @notice Create a new GanToken with a id and attaches an owner /// @param tokenId The id of the token that&#39;s being created function offerGanTokenForSaleToAddress(uint tokenId, address sendTo, uint256 minSalePriceInWei) external payable { require(tokenIdToOwner[tokenId] == msg.sender); ganTokenOfferedForSale[tokenId] = Offer(true, tokenId, msg.sender, minSalePriceInWei, sendTo); emit GanTokenOfferedForSale(tokenId, minSalePriceInWei, sendTo); } /// @notice Allows an account to buy a NFT gan token that is up for offer /// the token owner must set onlySellTo to the sender /// @param id the id of the token function buyGanToken(uint256 id) public payable { Offer memory offer = ganTokenOfferedForSale[id]; require(offer.isForSale); require(offer.onlySellTo == msg.sender && offer.onlySellTo != 0x0); require(msg.value == offer.value); require(tokenIdToOwner[id] == offer.seller); safeTransferFrom(offer.seller, offer.onlySellTo, id); ganTokenOfferedForSale[id] = Offer(false, id, offer.seller, 0, 0x0); pendingWithdrawals[offer.seller] += msg.value; } /// @notice Allows an account to enter a higher bid on a toekn /// @param tokenId the id of the token function enterBidForGanToken(uint256 tokenId) external payable { Bid memory existing = tokenBids[tokenId]; require(tokenIdToOwner[tokenId] != msg.sender); require(tokenIdToOwner[tokenId] != 0x0); require(msg.value > existing.value); if (existing.value > 0) { // Refund the failing bid pendingWithdrawals[existing.bidder] += existing.value; } tokenBids[tokenId] = Bid(true, tokenId, msg.sender, msg.value); emit BidForGanTokenOffered(tokenId, msg.value, msg.sender); } /// @notice Allows the owner of a token to accept an outstanding bid for that token /// @param tokenId The id of the token that&#39;s being created /// @param price The desired price of token in wei function acceptBid(uint256 tokenId, uint256 price) external payable { require(tokenIdToOwner[tokenId] == msg.sender); Bid memory bid = tokenBids[tokenId]; require(bid.value != 0); require(bid.value == price); safeTransferFrom(msg.sender, bid.bidder, tokenId); tokenBids[tokenId] = Bid(false, tokenId, address(0), 0); pendingWithdrawals[msg.sender] += bid.value; } /// @notice Check is a given id is on sale /// @param tokenId The id of the token in question /// @return a bool whether of not the token is on sale function isOnSale(uint256 tokenId) external view returns (bool) { return ganTokenOfferedForSale[tokenId].isForSale; } /// @notice Gets all the sale data related to a token /// @param tokenId The id of the token /// @return sale information function getSaleData(uint256 tokenId) public view returns (bool isForSale, address seller, uint value, address onlySellTo) { Offer memory offer = ganTokenOfferedForSale[tokenId]; isForSale = offer.isForSale; seller = offer.seller; value = offer.value; onlySellTo = offer.onlySellTo; } /// @notice Gets all the bid data related to a token /// @param tokenId The id of the token /// @return bid information function getBidData(uint256 tokenId) view public returns (bool hasBid, address bidder, uint value) { Bid memory bid = tokenBids[tokenId]; hasBid = bid.hasBid; bidder = bid.bidder; value = bid.value; } /// @notice Allows a bidder to withdraw their bid /// @param tokenId The id of the token function withdrawBid(uint256 tokenId) external payable { Bid memory bid = tokenBids[tokenId]; require(tokenIdToOwner[tokenId] != msg.sender); require(tokenIdToOwner[tokenId] != 0x0); require(bid.bidder == msg.sender); emit BidWithdrawn(tokenId, bid.value, msg.sender); uint amount = bid.value; tokenBids[tokenId] = Bid(false, tokenId, 0x0, 0); // Refund the bid money msg.sender.transfer(amount); } /// @notice Allows a sender to withdraw any amount in the contrat function withdraw() external { uint256 amount = pendingWithdrawals[msg.sender]; // Remember to zero the pending refund before // sending to prevent re-entrancy attacks pendingWithdrawals[msg.sender] = 0; msg.sender.transfer(amount); } }
Enable or disable approval for a third party ("operator") to manage all your asset. Emits the ApprovalForAll event _operator Address to add to the set of authorized operators. _approved True if the operators is approved, false to revoke approval
function setApprovalForAll(address _operator, bool _approved) external { operatorApprovals[msg.sender][_operator] = _approved; emit ApprovalForAll(msg.sender, _operator, _approved); }
7,691,916
pragma solidity ^0.4.18; // File: zeppelin-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) { 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: zeppelin-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 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; } } // File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev 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: zeppelin-solidity/contracts/token/ERC20/BasicToken.sol /** * @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]); // 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 view returns (uint256 balance) { return balances[_owner]; } } // File: zeppelin-solidity/contracts/token/ERC20/BurnableToken.sol /** * @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 { require(_value <= balances[msg.sender]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply_ = totalSupply_.sub(_value); Burn(burner, _value); } } // File: zeppelin-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: zeppelin-solidity/contracts/token/ERC20/StandardToken.sol /** * @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)) 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 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, uint _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, uint _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/ForestingToken.sol /* * ForestingToken is a standard ERC20 token with some additional functionalities: * - Transfers are only enabled after contract owner enables it (after the ICO) * - Contract sets 40% of the total supply as allowance for ICO contract * * Note: Token Offering == Initial Coin Offering(ICO) */ contract ForestingToken is StandardToken, BurnableToken, Ownable { string public constant symbol = "PTON"; string public constant name = "Foresting Token"; uint8 public constant decimals = 18; uint256 public constant INITIAL_SUPPLY = 24000000000 * (10 ** uint256(decimals)); uint256 public constant TOKEN_OFFERING_ALLOWANCE = 9600000000 * (10 ** uint256(decimals)); uint256 public constant ADMIN_ALLOWANCE = INITIAL_SUPPLY - TOKEN_OFFERING_ALLOWANCE; // Address of token admin address public adminAddr; // Address of token offering address public tokenOfferingAddr; // Enable transfers after conclusion of token offering bool public transferEnabled = false; /** * Check if transfer is allowed * * Permissions: * Owner Admin OfferingContract Others * transfer (before transferEnabled is true) x x x x * transferFrom (before transferEnabled is true) x o o x * transfer/transferFrom(after transferEnabled is true) o x x o */ modifier onlyWhenTransferAllowed() { require(transferEnabled || msg.sender == adminAddr || msg.sender == tokenOfferingAddr); _; } /** * Check if token offering address is set or not */ modifier onlyTokenOfferingAddrNotSet() { require(tokenOfferingAddr == address(0x0)); _; } /** * Check if address is a valid destination to transfer tokens to * - must not be zero address * - must not be the token address * - must not be the owner's address * - must not be the admin's address * - must not be the token offering contract address */ modifier validDestination(address to) { require(to != address(0x0)); require(to != address(this)); require(to != owner); require(to != address(adminAddr)); require(to != address(tokenOfferingAddr)); _; } /** * Token contract constructor * * @param admin Address of admin account */ function ForestingToken(address admin) public { totalSupply_ = INITIAL_SUPPLY; // Mint tokens balances[msg.sender] = totalSupply_; Transfer(address(0x0), msg.sender, totalSupply_); // Approve allowance for admin account adminAddr = admin; approve(adminAddr, ADMIN_ALLOWANCE); } /** * Set token offering to approve allowance for offering contract to distribute tokens * * @param offeringAddr Address of token offering contract * @param amountForSale Amount of tokens for sale, set 0 to max out */ function setTokenOffering(address offeringAddr, uint256 amountForSale) external onlyOwner onlyTokenOfferingAddrNotSet { require(!transferEnabled); uint256 amount = (amountForSale == 0) ? TOKEN_OFFERING_ALLOWANCE : amountForSale; require(amount <= TOKEN_OFFERING_ALLOWANCE); approve(offeringAddr, amount); tokenOfferingAddr = offeringAddr; } /** * Enable transfers */ function enableTransfer() external onlyOwner { transferEnabled = true; // End the offering approve(tokenOfferingAddr, 0); } /** * Transfer from sender to another account * * @param to Destination address * @param value Amount of forestingtokens to send */ function transfer(address to, uint256 value) public onlyWhenTransferAllowed validDestination(to) returns (bool) { return super.transfer(to, value); } /** * Transfer from `from` account to `to` account using allowance in `from` account to the sender * * @param from Origin address * @param to Destination address * @param value Amount of forestingtokens to send */ function transferFrom(address from, address to, uint256 value) public onlyWhenTransferAllowed validDestination(to) returns (bool) { return super.transferFrom(from, to, value); } /** * Burn token, only owner is allowed to do this * * @param value Amount of tokens to burn */ function burn(uint256 value) public { require(transferEnabled || msg.sender == owner); super.burn(value); } }
Burn token, only owner is allowed to do this value Amount of tokens to burn/
function burn(uint256 value) public { require(transferEnabled || msg.sender == owner); super.burn(value); }
396,603
./full_match/100/0x2327dB49Af92d468F00127AA9037334CFed3CB38/sources/contracts/TokenSale.sol
View-only function to return this contract's Ether balance in WEI. As Buys are made, this contract receives Ether and sends out our custom token based on the math conversion rate. return This contract's default Ether balance in ETH format
function getContractEtherBalanceWholeTokens() external view returns(uint256){ uint256 fullBalance = getContractEtherBalance(); if(fullBalance > 0) { return convertWeiToWholeTokens(fullBalance); } else { return 0; } }
14,291,244
./full_match/43114/0x3428aa6424E65a174bB78EDe122f39301c626a44/sources/Divident/WAVAX.sol
Initialize the contract _stakedToken: staked token address _rewardToken: reward token address _rewardPerBlock: reward per block (in rewardToken) _startBlock: start block _bonusEndBlock: end block _poolLimitPerUser: pool limit per user in stakedToken (if any, else 0) _withdrawalInterval: the withdrawal interval for stakedToken (if any, else 0) _admin: admin address with ownership/ Make this contract initialized
function initialize( IBEP20 _stakedToken, IBEP20 _rewardToken, uint256 _rewardPerBlock, uint256 _startBlock, uint256 _bonusEndBlock, uint256 _poolLimitPerUser, uint256 _withdrawalInterval, address _admin ) external { require(!isInitialized, "Already initialized"); require(msg.sender == deployer, "Not deployer"); require(_withdrawalInterval <= MAXIMUM_WITHDRAWAL_INTERVAL, "Invalid withdrawal interval"); isInitialized = true; stakedToken = _stakedToken; rewardToken = _rewardToken; rewardPerBlock = _rewardPerBlock; startBlock = _startBlock; bonusEndBlock = _bonusEndBlock; withdrawalInterval = _withdrawalInterval; if (_poolLimitPerUser > 0) { hasUserLimit = true; poolLimitPerUser = _poolLimitPerUser; } uint256 decimalsRewardToken = uint256(rewardToken.decimals()); require(decimalsRewardToken < 30, "Must be inferior to 30"); PRECISION_FACTOR = uint256(10 ** (uint256(30).sub(decimalsRewardToken))); }
4,513,526
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; import "hardhat/console.sol"; import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import "@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /// @title An Auction Contract for bidding and selling single and batched NFTs /// @author Avo Labs GmbH /// @notice This contract can be used for auctioning any NFTs, and accepts any ERC20 token as payment contract NFTERC721Auction is Ownable{ enum MARKETSTATE{CLOSEALL,OPENALL, OPENAUCTION, OPENLIMITORDER } enum ORDERTYPE{ AUCTION, LIMITORDER} address[] private payTokens = [0x0000000000000000000000000000000000001000]; address[] public feeRecipients = [0x0000000000000000000000000000000000001000]; uint32[] public feePercentages = [500]; mapping(address => mapping(uint256 => Auction)) public nftContractAuctions; mapping(address => mapping(uint256 => address)) public nftOwner; mapping(address => uint256) failedTransferCredits; //Each Auction is unique to each NFT (contract + id pairing). struct Auction { //map token ID to uint256 orderType; uint256 minPrice; uint256 buyNowPrice; uint256 auctionBidPeriod; //Increments the length of time the auction is open in which a new bid can be made after each bid. uint256 auctionEnd; uint256 nftHighestBid; uint256 bidIncreasePercentage; uint256[] batchTokenIds; // The first token in the batch is used to identify the auction (contract + id pairing). address nftHighestBidder; address nftSeller; address whitelistedBuyer; //The seller can specify a whitelisted address for a sale (this is effectively a direct sale). address nftRecipient; //The bidder can specify a recipient for the NFT if their bid is successful. address ERC20Token; // The seller can specify an ERC20 token that can be used to bid or purchase the NFT. address[] feeRecipients; uint32[] feePercentages; } /* * Default values that are used if not specified by the NFT seller. */ uint256 public defaultBidIncreasePercentage; uint256 public defaultAuctionBidPeriod; uint256 public minimumSettableIncreasePercentage; uint256 public maximumMinPricePercentage; uint256 public marketState = uint(MARKETSTATE.OPENLIMITORDER); /*╔═════════════════════════════╗ ║ EVENTS ║ ╚═════════════════════════════╝*/ event NftAuctionCreated( uint256 orderType, address nftContractAddress, uint256 tokenId, address nftSeller, address erc20Token, uint256 minPrice, uint256 buyNowPrice, uint256 auctionBidPeriod, uint256 bidIncreasePercentage, address[] feeRecipients, uint32[] feePercentages ); event NftBatchAuctionCreated( uint256 orderType, address nftContractAddress, uint256 masterTokenId, uint256[] batchTokens, address nftSeller, address erc20Token, uint256 minPrice, uint256 buyNowPrice, uint256 auctionBidPeriod, uint256 bidIncreasePercentage, address[] feeRecipients, uint32[] feePercentages ); event SaleCreated( uint256 orderType, address nftContractAddress, uint256 tokenId, address nftSeller, address erc20Token, uint256 buyNowPrice, address whitelistedBuyer, address[] feeRecipients, uint32[] feePercentages ); event BatchSaleCreated( uint256 orderType, address nftContractAddress, uint256 masterTokenId, uint256[] batchTokens, address nftSeller, address erc20Token, uint256 buyNowPrice, address whitelistedBuyer, address[] feeRecipients, uint32[] feePercentages ); event BidMade( address nftContractAddress, uint256 tokenId, address bidder, uint256 ethAmount, address erc20Token, uint256 tokenAmount ); event AuctionPeriodUpdated( address nftContractAddress, uint256 tokenId, uint256 auctionEndPeriod ); event NFTTransferredAndSellerPaid( address nftContractAddress, uint256 tokenId, address nftSeller, uint256 nftHighestBid, address nftHighestBidder, address nftRecipient ); event AuctionSettled( address nftContractAddress, uint256 tokenId, address auctionSettler ); event NFTWithdrawn( address nftContractAddress, uint256 tokenId, address nftSeller ); event BidWithdrawn( address nftContractAddress, uint256 tokenId, address highestBidder ); event WhitelistedBuyerUpdated( address nftContractAddress, uint256 tokenId, address newWhitelistedBuyer ); event MinimumPriceUpdated( address nftContractAddress, uint256 tokenId, uint256 newMinPrice ); event BuyNowPriceUpdated( address nftContractAddress, uint256 tokenId, uint256 newBuyNowPrice ); event HighestBidTaken(address nftContractAddress, uint256 tokenId); /**********************************/ /*╔═════════════════════════════╗ ║ END ║ ║ EVENTS ║ ╚═════════════════════════════╝*/ /**********************************/ /*╔═════════════════════════════╗ ║ MODIFIERS ║ ╚═════════════════════════════╝*/ modifier _onSale(address _nftContractAddress, uint256 _tokenId) { require( address(0) != nftContractAuctions[_nftContractAddress][_tokenId].nftSeller, "No sale" ); _; } modifier auctionOngoing(address _nftContractAddress, uint256 _tokenId) { require( _isAuctionOngoing(_nftContractAddress, _tokenId), "Auction has ended" ); _; } modifier priceGreaterThanZero(uint256 _price) { require(_price > 0, "Price cannot be 0"); _; } /* * The minimum price must be 80% of the buyNowPrice(if set). */ modifier minPriceDoesNotExceedLimit( uint256 _buyNowPrice, uint256 _minPrice ) { require( _buyNowPrice == 0 || _getPortionOfBid(_buyNowPrice, maximumMinPricePercentage) >= _minPrice, "Min price cannot exceed 80% of buyNowPrice" ); _; } modifier notNftSeller(address _nftContractAddress, uint256 _tokenId) { require( msg.sender != nftContractAuctions[_nftContractAddress][_tokenId].nftSeller, "Owner cannot bid on own NFT" ); _; } modifier onlyNftSeller(address _nftContractAddress, uint256 _tokenId) { require( msg.sender == nftContractAuctions[_nftContractAddress][_tokenId].nftSeller, "Only the owner can call this function" ); _; } /* * The bid amount was either equal the buyNowPrice or it must be higher than the previous * bid by the specified bid increase percentage. */ modifier bidAmountMeetsBidRequirements( address _nftContractAddress, uint256 _tokenId, uint256 _tokenAmount ) { require( _doesBidMeetBidRequirements( _nftContractAddress, _tokenId, _tokenAmount ), "Not enough funds to bid on NFT" ); _; } // check if the highest bidder can purchase this NFT. modifier onlyApplicableBuyer( address _nftContractAddress, uint256 _tokenId ) { require( !_isWhitelistedSale(_nftContractAddress, _tokenId) || nftContractAuctions[_nftContractAddress][_tokenId] .whitelistedBuyer == msg.sender, "only the whitelisted buyer can bid on this NFT" ); _; } modifier minimumBidNotMade(address _nftContractAddress, uint256 _tokenId) { require( !_isMinimumBidMade(_nftContractAddress, _tokenId), "The auction has a valid bid made" ); _; } /* * NFTs in a batch must contain between 2 and 100 NFTs */ modifier batchWithinLimits(uint256 _batchTokenIdsLength) { require( _batchTokenIdsLength > 1 && _batchTokenIdsLength <= 100, "Number of NFTs not applicable for batch sale/auction" ); _; } /* * Payment is accepted if the payment is made in the ERC20 token or ETH specified by the seller. * Early bids on NFTs not yet up for auction must be made in ETH. */ modifier paymentAccepted( address _nftContractAddress, uint256 _tokenId, address _erc20Token, uint256 _tokenAmount ) { require( _isPaymentAccepted( _nftContractAddress, _tokenId, _erc20Token, _tokenAmount ), "Bid to be made in quantities of specified token or eth" ); _; } modifier isAuctionOver(address _nftContractAddress, uint256 _tokenId) { require( !_isAuctionOngoing(_nftContractAddress, _tokenId), "Auction is not yet over" ); _; } modifier notZeroAddress(address _address) { require(_address != address(0), "cannot specify 0 address"); _; } modifier increasePercentageAboveMinimum(uint256 _bidIncreasePercentage) { require( _bidIncreasePercentage >= minimumSettableIncreasePercentage, "Bid increase percentage must be greater than minimum settable increase percentage" ); _; } modifier isFeePercentagesLessThanMaximum(uint32[] memory _feePercentages) { uint32 totalPercent; for (uint256 i = 0; i < _feePercentages.length; i++) { totalPercent = totalPercent + _feePercentages[i]; } require(totalPercent <= 10000, "fee percentages exceed maximum"); _; } modifier correctFeeRecipientsAndPercentages( uint256 _recipientsLength, uint256 _percentagesLength ) { require( _recipientsLength == _percentagesLength, "mismatched fee recipients and percentages" ); _; } modifier isNotASale(address _nftContractAddress, uint256 _tokenId) { require( !_isASale(_nftContractAddress, _tokenId), "Not applicable for a sale" ); _; } /**********************************/ /*╔═════════════════════════════╗ ║ END ║ ║ MODIFIERS ║ ╚═════════════════════════════╝*/ /**********************************/ // constructor constructor() { defaultBidIncreasePercentage = 1000; defaultAuctionBidPeriod = 86400; //1 day minimumSettableIncreasePercentage = 500; maximumMinPricePercentage = 8000; } /*╔══════════════════════════════╗ ║ AUCTION CHECK FUNCTIONS ║ ╚══════════════════════════════╝*/ function _isAuctionOngoing(address _nftContractAddress, uint256 _tokenId) internal view returns (bool) { uint256 auctionEndTimestamp = nftContractAuctions[_nftContractAddress][ _tokenId ].auctionEnd; //if the auctionEnd is set to 0, the auction is technically on-going, however //the minimum bid price (minPrice) has not yet been met. return (auctionEndTimestamp == 0 || block.timestamp < auctionEndTimestamp); } /* * Check if a bid has been made. This is applicable in the early bid scenario * to ensure that if an auction is created after an early bid, the auction * begins appropriately or is settled if the buy now price is met. */ function _isABidMade(address _nftContractAddress, uint256 _tokenId) internal view returns (bool) { return (nftContractAuctions[_nftContractAddress][_tokenId] .nftHighestBid > 0); } /* *if the minPrice is set by the seller, check that the highest bid meets or exceeds that price. */ function _isMinimumBidMade(address _nftContractAddress, uint256 _tokenId) internal view returns (bool) { uint256 minPrice = nftContractAuctions[_nftContractAddress][_tokenId] .minPrice; return minPrice > 0 && (nftContractAuctions[_nftContractAddress][_tokenId].nftHighestBid >= minPrice); } /* * If the buy now price is set by the seller, check that the highest bid meets that price. */ function _isBuyNowPriceMet(address _nftContractAddress, uint256 _tokenId) internal view returns (bool) { uint256 buyNowPrice = nftContractAuctions[_nftContractAddress][_tokenId] .buyNowPrice; return buyNowPrice > 0 && nftContractAuctions[_nftContractAddress][_tokenId].nftHighestBid >= buyNowPrice; } /* * Check that a bid is applicable for the purchase of the NFT. * In the case of a sale: the bid needs to meet the buyNowPrice. * In the case of an auction: the bid needs to be a % higher than the previous bid. */ function _doesBidMeetBidRequirements( address _nftContractAddress, uint256 _tokenId, uint256 _tokenAmount ) internal view returns (bool) { uint256 buyNowPrice = nftContractAuctions[_nftContractAddress][_tokenId] .buyNowPrice; //if buyNowPrice is met, ignore increase percentage if ( buyNowPrice > 0 && (msg.value >= buyNowPrice || _tokenAmount >= buyNowPrice) ) { return true; } //if the NFT is up for auction, the bid needs to be a % higher than the previous bid uint256 bidIncreaseAmount = (nftContractAuctions[_nftContractAddress][ _tokenId ].nftHighestBid * (10000 + _getBidIncreasePercentage(_nftContractAddress, _tokenId))) / 10000; return (msg.value >= bidIncreaseAmount || _tokenAmount >= bidIncreaseAmount); } /* * An NFT is up for sale if the buyNowPrice is set, but the minPrice is not set. * Therefore the only way to conclude the NFT sale is to meet the buyNowPrice. */ function _isASale(address _nftContractAddress, uint256 _tokenId) internal view returns (bool) { return (nftContractAuctions[_nftContractAddress][_tokenId].buyNowPrice > 0 && nftContractAuctions[_nftContractAddress][_tokenId].minPrice == 0); } function _isWhitelistedSale(address _nftContractAddress, uint256 _tokenId) internal view returns (bool) { return (nftContractAuctions[_nftContractAddress][_tokenId] .whitelistedBuyer != address(0)); } /* * The highest bidder is allowed to purchase the NFT if * no whitelisted buyer is set by the NFT seller. * Otherwise, the highest bidder must equal the whitelisted buyer. */ function _isHighestBidderAllowedToPurchaseNFT( address _nftContractAddress, uint256 _tokenId ) internal view returns (bool) { return (!_isWhitelistedSale(_nftContractAddress, _tokenId)) || _isHighestBidderWhitelisted(_nftContractAddress, _tokenId); } function _isHighestBidderWhitelisted( address _nftContractAddress, uint256 _tokenId ) internal view returns (bool) { return (nftContractAuctions[_nftContractAddress][_tokenId] .nftHighestBidder == nftContractAuctions[_nftContractAddress][_tokenId] .whitelistedBuyer); } /** * Payment is accepted in the following scenarios: * (1) Auction already created - can accept ETH or Specified Token * --------> Cannot bid with ETH & an ERC20 Token together in any circumstance<------ * (2) Auction not created - only ETH accepted (cannot early bid with an ERC20 Token * (3) Cannot make a zero bid (no ETH or Token amount) */ function _isPaymentAccepted( address _nftContractAddress, uint256 _tokenId, address _bidERC20Token, uint256 _tokenAmount ) internal view returns (bool) { address auctionERC20Token = nftContractAuctions[_nftContractAddress][ _tokenId ].ERC20Token; if (_isERC20Auction(auctionERC20Token)) { return msg.value == 0 && auctionERC20Token == _bidERC20Token && _tokenAmount > 0; } else { return msg.value != 0 && _bidERC20Token == address(0) && _tokenAmount == 0; } } function _isERC20Auction(address _auctionERC20Token) internal view returns (bool) { bool support = false; for (uint256 i = 0; i < payTokens.length; i++) { if(payTokens[i] == _auctionERC20Token) { support = true; break; } } return _auctionERC20Token != address(0) && support == true; } /* * Returns the percentage of the total bid (used to calculate fee payments) */ function _getPortionOfBid(uint256 _totalBid, uint256 _percentage) internal pure returns (uint256) { return (_totalBid * (_percentage)) / 10000; } /**********************************/ /*╔══════════════════════════════╗ ║ END ║ ║ AUCTION CHECK FUNCTIONS ║ ╚══════════════════════════════╝*/ /**********************************/ /*╔══════════════════════════════╗ ║ DEFAULT GETTER FUNCTIONS ║ ╚══════════════════════════════╝*/ /***************************************************************** * These functions check if the applicable auction parameter has * * been set by the NFT seller. If not, return the default value. * *****************************************************************/ function _getBidIncreasePercentage( address _nftContractAddress, uint256 _tokenId ) internal view returns (uint256) { uint256 bidIncreasePercentage = nftContractAuctions[ _nftContractAddress ][_tokenId].bidIncreasePercentage; if (bidIncreasePercentage == 0) { return defaultBidIncreasePercentage; } else { return bidIncreasePercentage; } } function _getAuctionBidPeriod(address _nftContractAddress, uint256 _tokenId) internal view returns (uint256) { uint256 auctionBidPeriod = nftContractAuctions[_nftContractAddress][ _tokenId ].auctionBidPeriod; if (auctionBidPeriod == 0) { return defaultAuctionBidPeriod; } else { return auctionBidPeriod; } } /* * The default value for the NFT recipient is the highest bidder */ function _getNftRecipient(address _nftContractAddress, uint256 _tokenId) internal view returns (address) { address nftRecipient = nftContractAuctions[_nftContractAddress][ _tokenId ].nftRecipient; if (nftRecipient == address(0)) { return nftContractAuctions[_nftContractAddress][_tokenId] .nftHighestBidder; } else { return nftRecipient; } } /**********************************/ /*╔══════════════════════════════╗ ║ END ║ ║ DEFAULT GETTER FUNCTIONS ║ ╚══════════════════════════════╝*/ /**********************************/ /*╔══════════════════════════════╗ ║ TRANSFER NFTS TO CONTRACT ║ ╚══════════════════════════════╝*/ function _transferNftToAuctionContract( address _nftContractAddress, uint256 _tokenId ) internal { IERC721(_nftContractAddress).transferFrom( msg.sender, address(this), _tokenId ); } function _transferNftBatchToAuctionContract( address _nftContractAddress, uint256[] memory _batchTokenIds ) internal { for (uint256 i = 0; i < _batchTokenIds.length; i++) { IERC721(_nftContractAddress).transferFrom( msg.sender, address(this), _batchTokenIds[i] ); if (i != 0) { //Don't set the first one because we set this later as the NFTSeller parameter in the struct nftOwner[_nftContractAddress][_batchTokenIds[i]] = msg.sender; } } _reverseAndResetPreviousBid(_nftContractAddress, _batchTokenIds[0]); nftContractAuctions[_nftContractAddress][_batchTokenIds[0]] .batchTokenIds = _batchTokenIds; } /**********************************/ /*╔══════════════════════════════╗ ║ END ║ ║ TRANSFER NFTS TO CONTRACT ║ ╚══════════════════════════════╝*/ /**********************************/ /*╔══════════════════════════════╗ ║ AUCTION CREATION ║ ╚══════════════════════════════╝*/ /** * Setup parameters applicable to all auctions and whitelised sales: * -> ERC20 Token for payment (if specified by the seller) : _erc20Token * -> minimum price : _minPrice * -> buy now price : _buyNowPrice * -> the nft seller: msg.sender * -> The fee recipients & their respective percentages for a sucessful auction/sale */ function _setupAuction( address _nftContractAddress, uint256 _tokenId, address _erc20Token, uint256 _minPrice, uint256 _buyNowPrice, uint256 _orderType ) internal minPriceDoesNotExceedLimit(_buyNowPrice, _minPrice) correctFeeRecipientsAndPercentages( feeRecipients.length, feePercentages.length ) isFeePercentagesLessThanMaximum(feePercentages) { if (_erc20Token != address(0)) { nftContractAuctions[_nftContractAddress][_tokenId] .ERC20Token = _erc20Token; } nftContractAuctions[_nftContractAddress][_tokenId] .orderType =_orderType==0? uint(ORDERTYPE.AUCTION):uint(ORDERTYPE.LIMITORDER); nftContractAuctions[_nftContractAddress][_tokenId] .feeRecipients = feeRecipients; nftContractAuctions[_nftContractAddress][_tokenId] .feePercentages = feePercentages; nftContractAuctions[_nftContractAddress][_tokenId] .buyNowPrice = _buyNowPrice; nftContractAuctions[_nftContractAddress][_tokenId].minPrice = _minPrice; nftContractAuctions[_nftContractAddress][_tokenId].nftSeller = msg .sender; } function _createNewNftAuction( address _nftContractAddress, uint256 _tokenId, address _erc20Token, uint256 _minPrice, uint256 _buyNowPrice, uint256 _orderType ) internal { // Sending the NFT to this contract _transferNftToAuctionContract(_nftContractAddress, _tokenId); _setupAuction( _nftContractAddress, _tokenId, _erc20Token, _minPrice, _buyNowPrice, _orderType ); emit NftAuctionCreated( uint(ORDERTYPE.AUCTION), _nftContractAddress, _tokenId, msg.sender, _erc20Token, _minPrice, _buyNowPrice, _getAuctionBidPeriod(_nftContractAddress, _tokenId), _getBidIncreasePercentage(_nftContractAddress, _tokenId), feeRecipients, feePercentages ); _updateOngoingAuction(_nftContractAddress, _tokenId); } /** * Create an auction that uses the default bid increase percentage * & the default auction bid period. */ function createDefaultNftAuction( address _nftContractAddress, uint256 _tokenId, address _erc20Token, uint256 _minPrice, uint256 _buyNowPrice ) external priceGreaterThanZero(_minPrice) { require(marketState != uint(MARKETSTATE.CLOSEALL) && (marketState == uint(MARKETSTATE.OPENALL)||(marketState == uint(MARKETSTATE.OPENAUCTION))), "The market is not open"); _createNewNftAuction( _nftContractAddress, _tokenId, _erc20Token, _minPrice, _buyNowPrice, uint(ORDERTYPE.AUCTION) ); } function createNewNftAuction( address _nftContractAddress, uint256 _tokenId, address _erc20Token, uint256 _minPrice, uint256 _buyNowPrice, uint256 _auctionBidPeriod, //this is the time that the auction lasts until another bid occurs uint256 _bidIncreasePercentage ) external priceGreaterThanZero(_minPrice) increasePercentageAboveMinimum(_bidIncreasePercentage) { require(marketState != uint(MARKETSTATE.CLOSEALL) && (marketState == uint(MARKETSTATE.OPENALL)||(marketState == uint(MARKETSTATE.OPENAUCTION))), "The market is not open"); nftContractAuctions[_nftContractAddress][_tokenId] .auctionBidPeriod = _auctionBidPeriod; nftContractAuctions[_nftContractAddress][_tokenId] .bidIncreasePercentage = _bidIncreasePercentage; _createNewNftAuction( _nftContractAddress, _tokenId, _erc20Token, _minPrice, _buyNowPrice, uint(ORDERTYPE.AUCTION) ); } function _createBatchNftAuction( address _nftContractAddress, uint256[] memory _batchTokenIds, address _erc20Token, uint256 _minPrice, uint256 _buyNowPrice, uint256 _orderType ) internal { _transferNftBatchToAuctionContract(_nftContractAddress, _batchTokenIds); _setupAuction( _nftContractAddress, _batchTokenIds[0], _erc20Token, _minPrice, _buyNowPrice, _orderType ); uint256 auctionBidPeriod = _getAuctionBidPeriod( _nftContractAddress, _batchTokenIds[0] ); uint256 bidIncreasePercentage = _getBidIncreasePercentage( _nftContractAddress, _batchTokenIds[0] ); emit NftBatchAuctionCreated( uint(ORDERTYPE.AUCTION), _nftContractAddress, _batchTokenIds[0], _batchTokenIds, msg.sender, _erc20Token, _minPrice, _buyNowPrice, auctionBidPeriod, bidIncreasePercentage, feeRecipients, feePercentages ); } function createDefaultBatchNftAuction( address _nftContractAddress, uint256[] memory _batchTokenIds, address _erc20Token, uint256 _minPrice, uint256 _buyNowPrice ) external priceGreaterThanZero(_minPrice) batchWithinLimits(_batchTokenIds.length) { require(marketState != uint(MARKETSTATE.CLOSEALL) && (marketState == uint(MARKETSTATE.OPENALL)||(marketState == uint(MARKETSTATE.OPENAUCTION))), "The market is not open"); _createBatchNftAuction( _nftContractAddress, _batchTokenIds, _erc20Token, _minPrice, _buyNowPrice, uint(ORDERTYPE.AUCTION) ); } /* * Create an auction for multiple NFTs in a batch. * The first token in the batch is used as the identifier for the auction. * Users must be aware of this tokenId when creating a batch auction. */ function createBatchNftAuction( address _nftContractAddress, uint256[] memory _batchTokenIds, address _erc20Token, uint256 _minPrice, uint256 _buyNowPrice, uint256 _auctionBidPeriod, //this is the time that the auction lasts until another bid occurs uint256 _bidIncreasePercentage ) external priceGreaterThanZero(_minPrice) batchWithinLimits(_batchTokenIds.length) increasePercentageAboveMinimum(_bidIncreasePercentage) { require(marketState != uint(MARKETSTATE.CLOSEALL) && (marketState == uint(MARKETSTATE.OPENALL)||(marketState == uint(MARKETSTATE.OPENAUCTION))), "The market is not open"); nftContractAuctions[_nftContractAddress][_batchTokenIds[0]] .auctionBidPeriod = _auctionBidPeriod; nftContractAuctions[_nftContractAddress][_batchTokenIds[0]] .bidIncreasePercentage = _bidIncreasePercentage; _createBatchNftAuction( _nftContractAddress, _batchTokenIds, _erc20Token, _minPrice, _buyNowPrice, uint(ORDERTYPE.AUCTION) ); } /**********************************/ /*╔══════════════════════════════╗ ║ END ║ ║ AUCTION CREATION ║ ╚══════════════════════════════╝*/ /**********************************/ /*╔══════════════════════════════╗ ║ SALES ║ ╚══════════════════════════════╝*/ /******************************************************************** * Allows for a standard sale mechanism where the NFT seller can * * can select an address to be whitelisted. This address is then * * allowed to make a bid on the NFT. No other address can bid on * * the NFT. * ********************************************************************/ function _setupSale( address _nftContractAddress, uint256 _tokenId, address _erc20Token, uint256 _buyNowPrice, address _whitelistedBuyer, uint256 _orderType ) internal correctFeeRecipientsAndPercentages( feeRecipients.length, feePercentages.length ) isFeePercentagesLessThanMaximum(feePercentages) { if (_erc20Token != address(0)) { nftContractAuctions[_nftContractAddress][_tokenId] .ERC20Token = _erc20Token; } nftContractAuctions[_nftContractAddress][_tokenId] .orderType =_orderType==0? uint(ORDERTYPE.AUCTION):uint(ORDERTYPE.LIMITORDER); nftContractAuctions[_nftContractAddress][_tokenId] .feeRecipients = feeRecipients; nftContractAuctions[_nftContractAddress][_tokenId] .feePercentages = feePercentages; nftContractAuctions[_nftContractAddress][_tokenId] .buyNowPrice = _buyNowPrice; nftContractAuctions[_nftContractAddress][_tokenId] .whitelistedBuyer = _whitelistedBuyer; nftContractAuctions[_nftContractAddress][_tokenId].nftSeller = msg .sender; } function createSale( address _nftContractAddress, uint256 _tokenId, address _erc20Token, uint256 _buyNowPrice, address _whitelistedBuyer ) external priceGreaterThanZero(_buyNowPrice) { require(marketState != uint(MARKETSTATE.CLOSEALL) && (marketState == uint(MARKETSTATE.OPENALL)||(marketState == uint(MARKETSTATE.OPENAUCTION))), "The market is not open"); _transferNftToAuctionContract(_nftContractAddress, _tokenId); //min price = 0 _setupSale( _nftContractAddress, _tokenId, _erc20Token, _buyNowPrice, _whitelistedBuyer, uint(ORDERTYPE.AUCTION) ); emit SaleCreated( uint(ORDERTYPE.AUCTION), _nftContractAddress, _tokenId, msg.sender, _erc20Token, _buyNowPrice, _whitelistedBuyer, feeRecipients, feePercentages ); //check if buyNowPrice is meet and conclude sale, otherwise reverse the early bid if (_isABidMade(_nftContractAddress, _tokenId)) { if ( //we only revert the underbid if the seller specifies a different //whitelisted buyer to the highest bidder _isHighestBidderAllowedToPurchaseNFT( _nftContractAddress, _tokenId ) ) { if (_isBuyNowPriceMet(_nftContractAddress, _tokenId)) { _transferNftAndPaySeller(_nftContractAddress, _tokenId); } } else { _reverseAndResetPreviousBid(_nftContractAddress, _tokenId); } } } function createBatchSale( address _nftContractAddress, uint256[] memory _batchTokenIds, address _erc20Token, uint256 _buyNowPrice, address _whitelistedBuyer ) external priceGreaterThanZero(_buyNowPrice) batchWithinLimits(_batchTokenIds.length) { require(marketState != uint(MARKETSTATE.CLOSEALL) && (marketState == uint(MARKETSTATE.OPENALL)||(marketState == uint(MARKETSTATE.OPENAUCTION))), "The market is not open"); _transferNftBatchToAuctionContract(_nftContractAddress, _batchTokenIds); _setupSale( _nftContractAddress, _batchTokenIds[0], _erc20Token, _buyNowPrice, _whitelistedBuyer, uint(ORDERTYPE.AUCTION) ); emit BatchSaleCreated( uint(ORDERTYPE.AUCTION), _nftContractAddress, _batchTokenIds[0], _batchTokenIds, msg.sender, _erc20Token, _buyNowPrice, _whitelistedBuyer, feeRecipients, feePercentages ); } function createSaleLimitOrder( address _nftContractAddress, uint256 _tokenId, address _erc20Token, uint256 _buyNowPrice, address _whitelistedBuyer ) external priceGreaterThanZero(_buyNowPrice) { require(marketState != uint(MARKETSTATE.CLOSEALL) && (marketState == uint(MARKETSTATE.OPENALL)||(marketState == uint(MARKETSTATE.OPENLIMITORDER))), "The market is not open"); _transferNftToAuctionContract(_nftContractAddress, _tokenId); //min price = 0 _setupSale( _nftContractAddress, _tokenId, _erc20Token, _buyNowPrice, _whitelistedBuyer, uint(ORDERTYPE.LIMITORDER) ); emit SaleCreated( uint(ORDERTYPE.LIMITORDER), _nftContractAddress, _tokenId, msg.sender, _erc20Token, _buyNowPrice, _whitelistedBuyer, feeRecipients, feePercentages ); //check if buyNowPrice is meet and conclude sale, otherwise reverse the early bid if (_isABidMade(_nftContractAddress, _tokenId)) { if ( //we only revert the underbid if the seller specifies a different //whitelisted buyer to the highest bidder _isHighestBidderAllowedToPurchaseNFT( _nftContractAddress, _tokenId ) ) { if (_isBuyNowPriceMet(_nftContractAddress, _tokenId)) { _transferNftAndPaySeller(_nftContractAddress, _tokenId); } } else { _reverseAndResetPreviousBid(_nftContractAddress, _tokenId); } } } function createBatchSaleLimitOrder( address _nftContractAddress, uint256[] memory _batchTokenIds, address _erc20Token, uint256 _buyNowPrice, address _whitelistedBuyer ) external priceGreaterThanZero(_buyNowPrice) batchWithinLimits(_batchTokenIds.length) { require(marketState != uint(MARKETSTATE.CLOSEALL) && (marketState == uint(MARKETSTATE.OPENALL)||(marketState == uint(MARKETSTATE.OPENLIMITORDER))), "The market is not open"); _transferNftBatchToAuctionContract(_nftContractAddress, _batchTokenIds); _setupSale( _nftContractAddress, _batchTokenIds[0], _erc20Token, _buyNowPrice, _whitelistedBuyer, uint(ORDERTYPE.LIMITORDER) ); emit BatchSaleCreated( uint(ORDERTYPE.LIMITORDER), _nftContractAddress, _batchTokenIds[0], _batchTokenIds, msg.sender, _erc20Token, _buyNowPrice, _whitelistedBuyer, feeRecipients, feePercentages ); } /**********************************/ /*╔══════════════════════════════╗ ║ END ║ ║ SALES ║ ╚══════════════════════════════╝*/ /**********************************/ /*╔═════════════════════════════╗ ║ BID FUNCTIONS ║ ╚═════════════════════════════╝*/ /******************************************************************** * Make bids with ETH or an ERC20 Token specified by the NFT seller.* * Additionally, a buyer can pay the asking price to conclude a sale* * of an NFT. * ********************************************************************/ function _makeBid( address _nftContractAddress, uint256 _tokenId, address _erc20Token, uint256 _tokenAmount ) internal notNftSeller(_nftContractAddress, _tokenId) paymentAccepted( _nftContractAddress, _tokenId, _erc20Token, _tokenAmount ) bidAmountMeetsBidRequirements( _nftContractAddress, _tokenId, _tokenAmount ) { if(nftContractAuctions[_nftContractAddress][_tokenId].orderType == uint(ORDERTYPE.LIMITORDER) && nftContractAuctions[_nftContractAddress][_tokenId].ERC20Token != address(0)) _tokenAmount = nftContractAuctions[_nftContractAddress][_tokenId].buyNowPrice; if(nftContractAuctions[_nftContractAddress][_tokenId].orderType == uint(ORDERTYPE.LIMITORDER) && nftContractAuctions[_nftContractAddress][_tokenId].ERC20Token == address(0)) { require( msg.value>=nftContractAuctions[_nftContractAddress][_tokenId].buyNowPrice, "Insufficient amount" ); } _reversePreviousBidAndUpdateHighestBid( _nftContractAddress, _tokenId, _tokenAmount ); emit BidMade( _nftContractAddress, _tokenId, msg.sender, msg.value, _erc20Token, _tokenAmount ); _updateOngoingAuction(_nftContractAddress, _tokenId); } function makeBid( address _nftContractAddress, uint256 _tokenId, address _erc20Token, uint256 _tokenAmount ) external payable _onSale(_nftContractAddress, _tokenId) auctionOngoing(_nftContractAddress, _tokenId) onlyApplicableBuyer(_nftContractAddress, _tokenId) { _makeBid(_nftContractAddress, _tokenId, _erc20Token, _tokenAmount); } function makeCustomBid( address _nftContractAddress, uint256 _tokenId, address _erc20Token, uint256 _tokenAmount, address _nftRecipient ) external payable _onSale(_nftContractAddress, _tokenId) auctionOngoing(_nftContractAddress, _tokenId) notZeroAddress(_nftRecipient) onlyApplicableBuyer(_nftContractAddress, _tokenId) { nftContractAuctions[_nftContractAddress][_tokenId] .nftRecipient = _nftRecipient; _makeBid(_nftContractAddress, _tokenId, _erc20Token, _tokenAmount); } /**********************************/ /*╔══════════════════════════════╗ ║ END ║ ║ BID FUNCTIONS ║ ╚══════════════════════════════╝*/ /**********************************/ /*╔══════════════════════════════╗ ║ UPDATE AUCTION ║ ╚══════════════════════════════╝*/ /*************************************************************** * Settle an auction or sale if the buyNowPrice is met or set * * auction period to begin if the minimum price has been met. * ***************************************************************/ function _updateOngoingAuction( address _nftContractAddress, uint256 _tokenId ) internal { if (_isBuyNowPriceMet(_nftContractAddress, _tokenId)) { _transferNftAndPaySeller(_nftContractAddress, _tokenId); return; } //min price not set, nft not up for auction yet if (_isMinimumBidMade(_nftContractAddress, _tokenId)) { _updateAuctionEnd(_nftContractAddress, _tokenId); } } function _updateAuctionEnd(address _nftContractAddress, uint256 _tokenId) internal { //the auction end is always set to now + the bid period nftContractAuctions[_nftContractAddress][_tokenId].auctionEnd = _getAuctionBidPeriod(_nftContractAddress, _tokenId) + block.timestamp; emit AuctionPeriodUpdated( _nftContractAddress, _tokenId, nftContractAuctions[_nftContractAddress][_tokenId].auctionEnd ); } /**********************************/ /*╔══════════════════════════════╗ ║ END ║ ║ UPDATE AUCTION ║ ╚══════════════════════════════╝*/ /**********************************/ /*╔══════════════════════════════╗ ║ RESET FUNCTIONS ║ ╚══════════════════════════════╝*/ /* * Reset all auction related parameters for an NFT. * This effectively removes an EFT as an item up for auction */ function _resetAuction(address _nftContractAddress, uint256 _tokenId) internal { nftContractAuctions[_nftContractAddress][_tokenId].orderType = 0; nftContractAuctions[_nftContractAddress][_tokenId].minPrice = 0; nftContractAuctions[_nftContractAddress][_tokenId].buyNowPrice = 0; nftContractAuctions[_nftContractAddress][_tokenId].auctionEnd = 0; nftContractAuctions[_nftContractAddress][_tokenId].auctionBidPeriod = 0; nftContractAuctions[_nftContractAddress][_tokenId] .bidIncreasePercentage = 0; nftContractAuctions[_nftContractAddress][_tokenId].nftSeller = address( 0 ); nftContractAuctions[_nftContractAddress][_tokenId] .whitelistedBuyer = address(0); delete nftContractAuctions[_nftContractAddress][_tokenId].batchTokenIds; nftContractAuctions[_nftContractAddress][_tokenId].ERC20Token = address( 0 ); } /* * Reset all bid related parameters for an NFT. * This effectively sets an NFT as having no active bids */ function _resetBids(address _nftContractAddress, uint256 _tokenId) internal { nftContractAuctions[_nftContractAddress][_tokenId] .nftHighestBidder = address(0); nftContractAuctions[_nftContractAddress][_tokenId].nftHighestBid = 0; nftContractAuctions[_nftContractAddress][_tokenId] .nftRecipient = address(0); } /**********************************/ /*╔══════════════════════════════╗ ║ END ║ ║ RESET FUNCTIONS ║ ╚══════════════════════════════╝*/ /**********************************/ /*╔══════════════════════════════╗ ║ UPDATE BIDS ║ ╚══════════════════════════════╝*/ /****************************************************************** * Internal functions that update bid parameters and reverse bids * * to ensure contract only holds the highest bid. * ******************************************************************/ function _updateHighestBid( address _nftContractAddress, uint256 _tokenId, uint256 _tokenAmount ) internal { address auctionERC20Token = nftContractAuctions[_nftContractAddress][ _tokenId ].ERC20Token; if (_isERC20Auction(auctionERC20Token)) { IERC20(auctionERC20Token).transferFrom( msg.sender, address(this), _tokenAmount ); nftContractAuctions[_nftContractAddress][_tokenId] .nftHighestBid = _tokenAmount; } else { nftContractAuctions[_nftContractAddress][_tokenId] .nftHighestBid = msg.value; } nftContractAuctions[_nftContractAddress][_tokenId] .nftHighestBidder = msg.sender; } function _reverseAndResetPreviousBid( address _nftContractAddress, uint256 _tokenId ) internal { address nftHighestBidder = nftContractAuctions[_nftContractAddress][ _tokenId ].nftHighestBidder; uint256 nftHighestBid = nftContractAuctions[_nftContractAddress][ _tokenId ].nftHighestBid; _resetBids(_nftContractAddress, _tokenId); _payout(_nftContractAddress, _tokenId, nftHighestBidder, nftHighestBid); } function _reversePreviousBidAndUpdateHighestBid( address _nftContractAddress, uint256 _tokenId, uint256 _tokenAmount ) internal { address prevNftHighestBidder = nftContractAuctions[_nftContractAddress][ _tokenId ].nftHighestBidder; uint256 prevNftHighestBid = nftContractAuctions[_nftContractAddress][ _tokenId ].nftHighestBid; _updateHighestBid(_nftContractAddress, _tokenId, _tokenAmount); if (prevNftHighestBidder != address(0)) { _payout( _nftContractAddress, _tokenId, prevNftHighestBidder, prevNftHighestBid ); } } /**********************************/ /*╔══════════════════════════════╗ ║ END ║ ║ UPDATE BIDS ║ ╚══════════════════════════════╝*/ /**********************************/ /*╔══════════════════════════════╗ ║ TRANSFER NFT & PAY SELLER ║ ╚══════════════════════════════╝*/ function _transferNftAndPaySeller( address _nftContractAddress, uint256 _tokenId ) internal { address _nftSeller = nftContractAuctions[_nftContractAddress][_tokenId] .nftSeller; address _nftHighestBidder = nftContractAuctions[_nftContractAddress][ _tokenId ].nftHighestBidder; address _nftRecipient = _getNftRecipient(_nftContractAddress, _tokenId); uint256 _nftHighestBid = nftContractAuctions[_nftContractAddress][ _tokenId ].nftHighestBid; _resetBids(_nftContractAddress, _tokenId); _payFeesAndSeller( _nftContractAddress, _tokenId, _nftSeller, _nftHighestBid ); //reset bid and transfer nft last to avoid reentrancy uint256[] memory batchTokenIds = nftContractAuctions[ _nftContractAddress ][_tokenId].batchTokenIds; uint256 numberOfTokens = batchTokenIds.length; if (numberOfTokens > 0) { for (uint256 i = 0; i < numberOfTokens; i++) { IERC721(_nftContractAddress).transferFrom( address(this), _nftRecipient, batchTokenIds[i] ); nftOwner[_nftContractAddress][batchTokenIds[i]] = address(0); } } else { IERC721(_nftContractAddress).transferFrom( address(this), _nftRecipient, _tokenId ); } _resetAuction(_nftContractAddress, _tokenId); emit NFTTransferredAndSellerPaid( _nftContractAddress, _tokenId, _nftSeller, _nftHighestBid, _nftHighestBidder, _nftRecipient ); } function _payFeesAndSeller( address _nftContractAddress, uint256 _tokenId, address _nftSeller, uint256 _highestBid ) internal { uint256 feesPaid; for ( uint256 i = 0; i < nftContractAuctions[_nftContractAddress][_tokenId] .feeRecipients .length; i++ ) { uint256 fee = _getPortionOfBid( _highestBid, nftContractAuctions[_nftContractAddress][_tokenId] .feePercentages[i] ); feesPaid = feesPaid + fee; _payout( _nftContractAddress, _tokenId, nftContractAuctions[_nftContractAddress][_tokenId] .feeRecipients[i], fee ); } _payout( _nftContractAddress, _tokenId, _nftSeller, (_highestBid - feesPaid) ); } function _payout( address _nftContractAddress, uint256 _tokenId, address _recipient, uint256 _amount ) internal { address auctionERC20Token = nftContractAuctions[_nftContractAddress][ _tokenId ].ERC20Token; if (_isERC20Auction(auctionERC20Token)) { IERC20(auctionERC20Token).transfer(_recipient, _amount); } else { // attempt to send the funds to the recipient (bool success, ) = payable(_recipient).call{value: _amount}(""); // if it failed, update their credit balance so they can pull it later if (!success) { failedTransferCredits[_recipient] = failedTransferCredits[_recipient] + _amount; } } } /**********************************/ /*╔══════════════════════════════╗ ║ END ║ ║ TRANSFER NFT & PAY SELLER ║ ╚══════════════════════════════╝*/ /**********************************/ /*╔══════════════════════════════╗ ║ SETTLE & WITHDRAW ║ ╚══════════════════════════════╝*/ function settleAuction(address _nftContractAddress, uint256 _tokenId) external isAuctionOver(_nftContractAddress, _tokenId) { _transferNftAndPaySeller(_nftContractAddress, _tokenId); emit AuctionSettled(_nftContractAddress, _tokenId, msg.sender); } function withdrawNft(address _nftContractAddress, uint256 _tokenId) external minimumBidNotMade(_nftContractAddress, _tokenId) onlyNftSeller(_nftContractAddress, _tokenId) { uint256[] memory batchTokenIds = nftContractAuctions[ _nftContractAddress ][_tokenId].batchTokenIds; uint256 numberOfTokens = batchTokenIds.length; if (numberOfTokens > 0) { for (uint256 i = 0; i < numberOfTokens; i++) { IERC721(_nftContractAddress).transferFrom( address(this), nftContractAuctions[_nftContractAddress][_tokenId] .nftSeller, batchTokenIds[i] ); nftOwner[_nftContractAddress][batchTokenIds[i]] = address(0); } } else { IERC721(_nftContractAddress).transferFrom( address(this), nftContractAuctions[_nftContractAddress][_tokenId].nftSeller, _tokenId ); } _resetAuction(_nftContractAddress, _tokenId); emit NFTWithdrawn(_nftContractAddress, _tokenId, msg.sender); } function withdrawBid(address _nftContractAddress, uint256 _tokenId) external minimumBidNotMade(_nftContractAddress, _tokenId) { address nftHighestBidder = nftContractAuctions[_nftContractAddress][ _tokenId ].nftHighestBidder; require(msg.sender == nftHighestBidder, "Cannot withdraw funds"); uint256 nftHighestBid = nftContractAuctions[_nftContractAddress][ _tokenId ].nftHighestBid; _resetBids(_nftContractAddress, _tokenId); _payout(_nftContractAddress, _tokenId, nftHighestBidder, nftHighestBid); emit BidWithdrawn(_nftContractAddress, _tokenId, msg.sender); } /**********************************/ /*╔══════════════════════════════╗ ║ END ║ ║ SETTLE & WITHDRAW ║ ╚══════════════════════════════╝*/ /**********************************/ /*╔══════════════════════════════╗ ║ UPDATE AUCTION ║ ╚══════════════════════════════╝*/ function updateWhitelistedBuyer( address _nftContractAddress, uint256 _tokenId, address _newWhitelistedBuyer ) external onlyNftSeller(_nftContractAddress, _tokenId) { require(_isASale(_nftContractAddress, _tokenId), "Not a sale"); nftContractAuctions[_nftContractAddress][_tokenId] .whitelistedBuyer = _newWhitelistedBuyer; //if an underbid is by a non whitelisted buyer,reverse that bid address nftHighestBidder = nftContractAuctions[_nftContractAddress][ _tokenId ].nftHighestBidder; uint256 nftHighestBid = nftContractAuctions[_nftContractAddress][ _tokenId ].nftHighestBid; if (nftHighestBid > 0 && !(nftHighestBidder == _newWhitelistedBuyer)) { //we only revert the underbid if the seller specifies a different //whitelisted buyer to the highest bider _resetBids(_nftContractAddress, _tokenId); _payout( _nftContractAddress, _tokenId, nftHighestBidder, nftHighestBid ); } emit WhitelistedBuyerUpdated( _nftContractAddress, _tokenId, _newWhitelistedBuyer ); } function updateMinimumPrice( address _nftContractAddress, uint256 _tokenId, uint256 _newMinPrice ) external onlyNftSeller(_nftContractAddress, _tokenId) minimumBidNotMade(_nftContractAddress, _tokenId) isNotASale(_nftContractAddress, _tokenId) priceGreaterThanZero(_newMinPrice) minPriceDoesNotExceedLimit( nftContractAuctions[_nftContractAddress][_tokenId].buyNowPrice, _newMinPrice ) { nftContractAuctions[_nftContractAddress][_tokenId] .minPrice = _newMinPrice; emit MinimumPriceUpdated(_nftContractAddress, _tokenId, _newMinPrice); if (_isMinimumBidMade(_nftContractAddress, _tokenId)) { _updateAuctionEnd(_nftContractAddress, _tokenId); } } function updateBuyNowPrice( address _nftContractAddress, uint256 _tokenId, uint256 _newBuyNowPrice ) external onlyNftSeller(_nftContractAddress, _tokenId) priceGreaterThanZero(_newBuyNowPrice) minPriceDoesNotExceedLimit( _newBuyNowPrice, nftContractAuctions[_nftContractAddress][_tokenId].minPrice ) { nftContractAuctions[_nftContractAddress][_tokenId] .buyNowPrice = _newBuyNowPrice; emit BuyNowPriceUpdated(_nftContractAddress, _tokenId, _newBuyNowPrice); if (_isBuyNowPriceMet(_nftContractAddress, _tokenId)) { _transferNftAndPaySeller(_nftContractAddress, _tokenId); } } /* * The NFT seller can opt to end an auction by taking the current highest bid. */ function takeHighestBid(address _nftContractAddress, uint256 _tokenId) external onlyNftSeller(_nftContractAddress, _tokenId) { require( _isABidMade(_nftContractAddress, _tokenId), "cannot payout 0 bid" ); _transferNftAndPaySeller(_nftContractAddress, _tokenId); emit HighestBidTaken(_nftContractAddress, _tokenId); } /* * Query the owner of an NFT deposited for auction */ function ownerOfNFT(address _nftContractAddress, uint256 _tokenId) external view returns (address) { address nftSeller = nftContractAuctions[_nftContractAddress][_tokenId] .nftSeller; if (nftSeller != address(0)) { return nftSeller; } address ownerAddr = nftOwner[_nftContractAddress][_tokenId]; require(ownerAddr != address(0), "NFT not deposited"); return ownerAddr; } /* * If the transfer of a bid has failed, allow the recipient to reclaim their amount later. */ function withdrawAllFailedCredits() external { uint256 amount = failedTransferCredits[msg.sender]; require(amount != 0, "no credits to withdraw"); failedTransferCredits[msg.sender] = 0; (bool successfulWithdraw, ) = msg.sender.call{value: amount}(""); require(successfulWithdraw, "withdraw failed"); } /**********************************/ /*╔══════════════════════════════╗ ║ END ║ ║ UPDATE AUCTION ║ ╚══════════════════════════════╝*/ /**********************************/ function getPayTokens() external view returns (address[] memory) { return payTokens; } function setMarketState(uint256 _marketState) onlyOwner external { marketState = _marketState ; } function setPayTokens(address[] memory _payTokens) onlyOwner external { if(_payTokens.length!=0) payTokens = _payTokens; } function setFee(address[] memory _feeRecipients,uint32[] memory _feePercentages) onlyOwner external { if(_feeRecipients.length!=0) feeRecipients = _feeRecipients; if(_feePercentages.length!=0) feePercentages = _feePercentages; } receive() external payable {} function _transferEth(address _to, uint256 _amount) internal { (bool success, ) = _to.call{value: _amount}(''); require(success, "_transferEth: Eth transfer failed"); } // Emergency function: In case any ETH get stuck in the contract unintentionally // Only owner can retrieve the asset balance to a recipient address function rescueETH(address recipient) onlyOwner external { _transferEth(recipient, address(this).balance); } // Emergency function: In case any ERC20 tokens get stuck in the contract unintentionally // Only owner can retrieve the asset balance to a recipient address function rescueERC20(address asset, address recipient) onlyOwner external { IERC20(asset).transfer(recipient, IERC20(asset).balanceOf(address(this))); } // Emergency function: In case any ERC721 tokens get stuck in the contract unintentionally // Only owner can retrieve the asset balance to a recipient address function rescueERC721(address asset, uint256[] calldata ids, address recipient) onlyOwner external { for (uint256 i = 0; i < ids.length; i++) { IERC721(asset).transferFrom(address(this), recipient, ids[i]); } } // Emergency function: In case any ERC1155 tokens get stuck in the contract unintentionally // Only owner can retrieve the asset balance to a recipient address function rescueERC1155(address asset, uint256[] calldata ids, uint256[] calldata amounts, address recipient) onlyOwner external { for (uint256 i = 0; i < ids.length; i++) { IERC1155(asset).safeTransferFrom(address(this), recipient, ids[i], amounts[i], ""); } } }
the auction end is always set to now + the bid period
function _updateAuctionEnd(address _nftContractAddress, uint256 _tokenId) internal { nftContractAuctions[_nftContractAddress][_tokenId].auctionEnd = _getAuctionBidPeriod(_nftContractAddress, _tokenId) + block.timestamp; emit AuctionPeriodUpdated( _nftContractAddress, _tokenId, nftContractAuctions[_nftContractAddress][_tokenId].auctionEnd ); } ║ UPDATE AUCTION ║ ╚══════════════════════════════╝*/ ╚══════════════════════════════╝*/
5,506,309
// SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.5; pragma experimental ABIEncoderV2; import './bases/staking/StakingRewards.sol'; import './bases/BaseTokenUpgradeable.sol'; import './bases/staking/interfaces/IOriginatorStaking.sol'; import '../reserve/IReserve.sol'; import '../utils/SafeMathUint128.sol'; import '@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol'; import '@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol'; import '@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/proxy/Initializable.sol'; /** * @title OriginatorStaking * @notice Contract to stake Originator Hub tokens, tokenize the position and get rewards, inheriting from a distribution manager contract * @author Aave / Ethichub **/ contract OriginatorStaking is Initializable, StakingRewards, BaseTokenUpgradeable, IStaking, IProjectFundedRewards, IOriginatorManager { using SafeERC20Upgradeable for IERC20Upgradeable; using SafeMathUpgradeable for uint256; using SafeMathUint128 for uint128; enum OriginatorStakingState { UNINITIALIZED, STAKING, STAKING_END, DEFAULT } OriginatorStakingState public state; IERC20Upgradeable public STAKED_TOKEN; /// @notice IReserve to pull from the rewards, needs to have this contract as WITHDRAW role IReserve public REWARDS_VAULT; bytes32 public constant GOVERNANCE_ROLE = keccak256('GOVERNANCE_ROLE'); uint256 public stakingGoal; uint256 public defaultedAmount; mapping(address => uint256) public stakerRewardsToClaim; bytes32 public constant ORIGINATOR_ROLE = keccak256('ORIGINATOR_ROLE'); bytes32 public constant AUDITOR_ROLE = keccak256('AUDITOR_ROLE'); uint256 public DEFAULT_DATE; mapping(bytes32 => uint256) public proposerBalances; event StateChange(uint256 state); event Staked(address indexed from, address indexed onBehalfOf, uint256 amount); event Redeem(address indexed from, address indexed to, uint256 amount); event Withdraw(address indexed proposer, uint256 amount); event RewardsAccrued(address user, uint256 amount); event RewardsClaimed(address indexed from, address indexed to, uint256 amount); event StartRewardsProjectFunded(uint128 previousEmissionPerSecond, uint128 extraEmissionsPerSecond, address lendingContractAddress); event EndRewardsProjectFunded(uint128 restoredEmissionsPerSecond, uint128 extraEmissionsPerSecond, address lendingContractAddress); modifier onlyGovernance() { require(hasRole(GOVERNANCE_ROLE, msg.sender), 'ONLY_GOVERNANCE'); _; } modifier onlyEmissionManager() { require(hasRole(EMISSION_MANAGER_ROLE, msg.sender), 'ONLY_EMISSION_MANAGER'); _; } modifier onlyOnStakingState() { require(state == OriginatorStakingState.STAKING, 'ONLY_ON_STAKING_STATE'); _; } modifier notZeroAmount(uint256 _amount) { require(_amount > 0, 'INVALID_ZERO_AMOUNT'); _; } function initialize( string memory _name, string memory _symbol, IERC20Upgradeable _lockedToken, IReserve _rewardsVault, address _emissionManager, uint128 _distributionDuration ) public initializer { __BaseTokenUpgradeable_init( msg.sender, 0, _name, _symbol, _name ); __StakingRewards_init(_emissionManager, _distributionDuration); STAKED_TOKEN = _lockedToken; REWARDS_VAULT = _rewardsVault; _changeState(OriginatorStakingState.UNINITIALIZED); } /** * @notice Function to set up proposers (originator and auditor) * in proposal period. * @param _auditor address * @param _originator address * @param _auditorPercentage uint256 (value * 100 e.g. 20% == 2000) * @param _originatorPercentage uint256 (value * 100 e.g. 20% == 2000) * @param _stakingGoal uint256 wei amount in Ethix * @param _defaultDelay uint256 seconds */ function setUpTerms( address _auditor, address _originator, address _governance, uint256 _auditorPercentage, uint256 _originatorPercentage, uint256 _stakingGoal, uint256 _defaultDelay ) external override notZeroAmount(_stakingGoal) onlyEmissionManager { require(_auditor != _originator, 'PROPOSERS_CANNOT_BE_THE_SAME'); require(_auditorPercentage != 0 && _originatorPercentage != 0, 'INVALID_PERCENTAGE_ZERO'); require(state == OriginatorStakingState.UNINITIALIZED, 'ONLY_ON_UNINITILIZED_STATE'); _setupRole(AUDITOR_ROLE, _auditor); _setupRole(ORIGINATOR_ROLE, _originator); _setupRole(GOVERNANCE_ROLE, _governance); _depositProposer(_auditor, _auditorPercentage, _stakingGoal); _depositProposer(_originator, _originatorPercentage, _stakingGoal); stakingGoal = _stakingGoal; DEFAULT_DATE = _defaultDelay.add(DISTRIBUTION_END); _changeState(OriginatorStakingState.STAKING); } /** * @notice Function to renew terms in STAKING_END or DEFAULT period. * @param _newAuditorPercentage uint256 (value * 100 e.g. 20% == 2000) * @param _newOriginatorPercentage uint256 (value * 100 e.g. 20% == 2000) * @param _newStakingGoal uint256 wei amount in Ethix * @param _newDistributionDuration uint128 seconds (e.g. 365 days == 31536000) * @param _newDefaultDelay uint256 seconds (e.g 90 days == 7776000) */ function renewTerms( uint256 _newAuditorPercentage, uint256 _newOriginatorPercentage, uint256 _newStakingGoal, uint128 _newDistributionDuration, uint256 _newDefaultDelay) external override notZeroAmount(_newStakingGoal) onlyGovernance { require(state == OriginatorStakingState.STAKING_END || state == OriginatorStakingState.DEFAULT, 'INVALID_STATE'); DISTRIBUTION_END = block.timestamp.add(_newDistributionDuration); _depositProposer(getRoleMember(AUDITOR_ROLE, 0), _newAuditorPercentage, _newStakingGoal); _depositProposer(getRoleMember(ORIGINATOR_ROLE, 0), _newOriginatorPercentage, _newStakingGoal); stakingGoal = _newStakingGoal; DEFAULT_DATE = _newDefaultDelay.add(DISTRIBUTION_END); _changeState(OriginatorStakingState.STAKING); } /** * @notice Function to stake tokens * @param _onBehalfOf Address to stake to * @param _amount Amount to stake **/ function stake(address _onBehalfOf, uint256 _amount) external override notZeroAmount(_amount) onlyOnStakingState { require(!hasReachedGoal(), 'GOAL_HAS_REACHED'); if (STAKED_TOKEN.balanceOf(address(this)).add(_amount) > stakingGoal) { _amount = stakingGoal.sub(STAKED_TOKEN.balanceOf(address(this))); } uint256 balanceOfUser = balanceOf(_onBehalfOf); uint256 accruedRewards = _updateUserAssetInternal(_onBehalfOf, address(this), balanceOfUser, totalSupply()); if (accruedRewards != 0) { emit RewardsAccrued(_onBehalfOf, accruedRewards); stakerRewardsToClaim[_onBehalfOf] = stakerRewardsToClaim[_onBehalfOf].add(accruedRewards); } _mint(_onBehalfOf, _amount); IERC20Upgradeable(STAKED_TOKEN).safeTransferFrom(msg.sender, address(this), _amount); emit Staked(msg.sender, _onBehalfOf, _amount); } /** * @dev Redeems staked tokens, and stop earning rewards * @param _to Address to redeem to * @param _amount Amount to redeem **/ function redeem(address _to, uint256 _amount) external override notZeroAmount(_amount) { require(_checkRedeemEligibilityState(), 'WRONG_STATE'); require(balanceOf(msg.sender) != 0, 'SENDER_BALANCE_ZERO'); uint256 balanceOfMessageSender = balanceOf(msg.sender); uint256 amountToRedeem = (_amount > balanceOfMessageSender) ? balanceOfMessageSender : _amount; _updateCurrentUnclaimedRewards(msg.sender, balanceOfMessageSender, true); _burn(msg.sender, amountToRedeem); IERC20Upgradeable(STAKED_TOKEN).safeTransfer(_to, amountToRedeem); emit Redeem(msg.sender, _to, amountToRedeem); } /** * @notice method to withdraw deposited amount. * @param _amount Amount to withdraw */ function withdrawProposerStake(uint256 _amount) external override { require(state == OriginatorStakingState.STAKING_END, 'ONLY_ON_STAKING_END_STATE'); bytes32 senderRole = 0x00; if (msg.sender == getRoleMember(ORIGINATOR_ROLE, 0)) { senderRole = ORIGINATOR_ROLE; } else if (msg.sender == getRoleMember(AUDITOR_ROLE, 0)) { senderRole = AUDITOR_ROLE; } else { revert('WITHDRAW_PERMISSION_DENIED'); } require(proposerBalances[senderRole] != 0, 'INVALID_ZERO_AMOUNT'); uint256 amountToWithdraw = (_amount > proposerBalances[senderRole]) ? proposerBalances[senderRole] : _amount; proposerBalances[senderRole] = proposerBalances[senderRole].sub(amountToWithdraw); IERC20Upgradeable(STAKED_TOKEN).safeTransfer(msg.sender, amountToWithdraw); emit Withdraw(msg.sender, amountToWithdraw); } /** * @dev Claims an `amount` from Rewards reserve to the address `to` * @param _to Address to stake for * @param _amount Amount to stake **/ function claimRewards(address payable _to, uint256 _amount) external override { uint256 newTotalRewards = _updateCurrentUnclaimedRewards(msg.sender, balanceOf(msg.sender), false); uint256 amountToClaim = (_amount == type(uint256).max) ? newTotalRewards : _amount; stakerRewardsToClaim[msg.sender] = newTotalRewards.sub(amountToClaim, 'INVALID_AMOUNT'); require(REWARDS_VAULT.transfer(_to, amountToClaim), 'ERROR_TRANSFER_FROM_VAULT'); emit RewardsClaimed(msg.sender, _to, amountToClaim); } /** * Function to add an extra emissions per second corresponding to staker rewards when a lending project by this originator * is funded. * @param _extraEmissionsPerSecond emissions per second to be added to current ones. * @param _lendingContractAddress lending contract address is relationated with this rewards */ function startProjectFundedRewards(uint128 _extraEmissionsPerSecond, address _lendingContractAddress) external override onlyOnStakingState { AssetData storage currentDistribution = assets[address(this)]; uint128 currentEmission = currentDistribution.emissionPerSecond; uint128 newEmissionsPerSecond = currentDistribution.emissionPerSecond.add(_extraEmissionsPerSecond); DistributionTypes.AssetConfigInput[] memory newAssetConfig = new DistributionTypes.AssetConfigInput[](1); newAssetConfig[0] = DistributionTypes.AssetConfigInput({ emissionPerSecond: newEmissionsPerSecond, totalStaked: totalSupply(), underlyingAsset: address(this) }); configureAssets(newAssetConfig); emit StartRewardsProjectFunded(currentEmission, _extraEmissionsPerSecond, _lendingContractAddress); } /** * Function to end extra emissions per second corresponding to staker rewards when a lending project by this originator * is funded. * @param _extraEmissionsPerSecond emissions per second to be added to current ones. * @param _lendingContractAddress lending contract address is relationated with this rewards. */ function endProjectFundedRewards(uint128 _extraEmissionsPerSecond, address _lendingContractAddress) external override onlyOnStakingState { AssetData storage currentDistribution = assets[address(this)]; uint128 currentEmission = currentDistribution.emissionPerSecond; uint128 newEmissionsPerSecond = currentDistribution.emissionPerSecond.sub(_extraEmissionsPerSecond); DistributionTypes.AssetConfigInput[] memory newAssetConfig = new DistributionTypes.AssetConfigInput[](1); newAssetConfig[0] = DistributionTypes.AssetConfigInput({ emissionPerSecond: newEmissionsPerSecond, totalStaked: totalSupply(), underlyingAsset: address(this) }); configureAssets(newAssetConfig); emit EndRewardsProjectFunded(currentEmission, _extraEmissionsPerSecond, _lendingContractAddress); } /** * @notice Amount to substract of the contract when state is default * @param _amount amount to substract * @param _role role to substract the amount (Originator, Auditor) */ function liquidateProposerStake(uint256 _amount, bytes32 _role) external override notZeroAmount(_amount) onlyGovernance { require(state == OriginatorStakingState.DEFAULT, 'ONLY_ON_DEFAULT'); require(_role == AUDITOR_ROLE || _role == ORIGINATOR_ROLE, 'INVALID_PROPOSER_ROLE'); proposerBalances[_role] = proposerBalances[_role].sub(_amount, 'INVALID_LIQUIDATE_AMOUNT'); IERC20Upgradeable(STAKED_TOKEN).safeTransfer(msg.sender, _amount); } /** * @notice Function to declare contract on staking end state * Only governance could change to this state **/ function declareStakingEnd() external override onlyGovernance onlyOnStakingState { _endDistributionIfNeeded(); _changeState(OriginatorStakingState.STAKING_END); } /** * @notice Function to declare as DEFAULT * @param _defaultedAmount uint256 **/ function declareDefault(uint256 _defaultedAmount) external override onlyGovernance onlyOnStakingState { require(block.timestamp >= DEFAULT_DATE, 'DEFAULT_DATE_NOT_REACHED'); defaultedAmount = _defaultedAmount; _endDistributionIfNeeded(); _changeState(OriginatorStakingState.DEFAULT); } /** * @dev Return the total rewards pending to claim by an staker * @param _staker The staker address * @return The rewards */ function getTotalRewardsBalance(address _staker) external override view returns (uint256) { DistributionTypes.UserStakeInput[] memory userStakeInputs = new DistributionTypes.UserStakeInput[](1); userStakeInputs[0] = DistributionTypes.UserStakeInput({ underlyingAsset: address(this), stakedByUser: balanceOf(_staker), totalStaked: totalSupply() }); return stakerRewardsToClaim[_staker].add(_getUnclaimedRewards(_staker, userStakeInputs)); } /** * @notice Check if fulfilled the objective (Only valid on STAKING state!!) */ function hasReachedGoal() public override notZeroAmount(stakingGoal) view returns (bool) { if (proposerBalances[ORIGINATOR_ROLE].add(proposerBalances[AUDITOR_ROLE]).add(totalSupply()) >= stakingGoal) { return true; } return false; } /** * @notice Function to transfer participation amount (originator or auditor) */ function _depositProposer(address _proposer, uint256 _percentage, uint256 _goalAmount) internal { uint256 percentageAmount = _calculatePercentage(_goalAmount, _percentage); uint256 depositAmount = 0; if (_proposer == getRoleMember(ORIGINATOR_ROLE, 0)) { depositAmount = _calculateDepositAmount(ORIGINATOR_ROLE, percentageAmount); proposerBalances[ORIGINATOR_ROLE] = proposerBalances[ORIGINATOR_ROLE].add(depositAmount); } else if (_proposer == getRoleMember(AUDITOR_ROLE, 0)) { depositAmount = _calculateDepositAmount(AUDITOR_ROLE, percentageAmount); proposerBalances[AUDITOR_ROLE] = proposerBalances[AUDITOR_ROLE].add(depositAmount); } IERC20Upgradeable(STAKED_TOKEN).safeTransferFrom(_proposer, address(this), depositAmount); } /** * @dev Internal ERC20 _transfer of the tokenized staked tokens * @param _from Address to transfer from * @param _to Address to transfer to * @param _amount Amount to transfer **/ function _transfer( address _from, address _to, uint256 _amount ) internal override { uint256 balanceOfFrom = balanceOf(_from); // Sender _updateCurrentUnclaimedRewards(_from, balanceOfFrom, true); // Recipient if (_from != _to) { uint256 balanceOfTo = balanceOf(_to); _updateCurrentUnclaimedRewards(_to, balanceOfTo, true); } super._transfer(_from, _to, _amount); } /** * @dev Check if the state of contract is suitable to redeem */ function _checkRedeemEligibilityState() internal view returns (bool) { if (state == OriginatorStakingState.STAKING_END) { return true; } else if (state == OriginatorStakingState.DEFAULT && defaultedAmount <= proposerBalances[ORIGINATOR_ROLE].add(proposerBalances[AUDITOR_ROLE])) { return true; } else { return false; } } /** * @dev Updates the user state related with his accrued rewards * @param _user Address of the user * @param _userBalance The current balance of the user * @param _updateStorage Boolean flag used to update or not the stakerRewardsToClaim of the user * @return The unclaimed rewards that were added to the total accrued **/ function _updateCurrentUnclaimedRewards( address _user, uint256 _userBalance, bool _updateStorage ) internal returns (uint256) { uint256 accruedRewards = _updateUserAssetInternal(_user, address(this), _userBalance, totalSupply()); uint256 unclaimedRewards = stakerRewardsToClaim[_user].add(accruedRewards); if (accruedRewards != 0) { if (_updateStorage) { stakerRewardsToClaim[_user] = unclaimedRewards; } emit RewardsAccrued(_user, accruedRewards); } return unclaimedRewards; } /** * @notice Function to calculate a percentage of an amount * @param _amount Amount to calculate the percentage of * @param _percentage Percentage to calculate of this amount * @return (amount) */ function _calculatePercentage(uint256 _amount, uint256 _percentage) internal pure returns (uint256) { return uint256(_amount.mul(_percentage).div(10000)); } /** * @notice Function to get the actual participation amount * of proposers according the amount that already exists in the contract * @param _role Auditor or originator role * @param _percentageAmount Percentage of staking goal amount * Note _percentageAmount SHOULD BE GREATER than the previously existing amount */ function _calculateDepositAmount(bytes32 _role, uint256 _percentageAmount) internal view returns (uint256){ return uint256(_percentageAmount.sub(proposerBalances[_role])); } /** * @notice Function to change contract state * @param _newState New contract state **/ function _changeState(OriginatorStakingState _newState) internal { state = _newState; emit StateChange(uint256(_newState)); } /** * @notice Function to change DISTRIBUTION_END if timestamp is less than the initial one **/ function _endDistributionIfNeeded() internal { if (block.timestamp <= DISTRIBUTION_END) { _changeDistributionEndDate(block.timestamp); } } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.5; pragma experimental ABIEncoderV2; import './lib/DistributionTypes.sol'; import './interfaces/IStakingRewards.sol'; import '@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol'; import '../../../utils/SafeMathUint128.sol'; import '@openzeppelin/contracts-upgradeable/proxy/Initializable.sol'; import '@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol'; /** * @title StakingRewards * @notice Accounting contract to manage multiple staking distributions * @author Aave / Ethichub **/ contract StakingRewards is Initializable, IStakingRewards, AccessControlUpgradeable { bytes32 public constant EMISSION_MANAGER_ROLE = keccak256('EMISSION_MANAGER'); using SafeMathUpgradeable for uint256; using SafeMathUint128 for uint128; struct AssetData { uint128 emissionPerSecond; uint128 lastUpdateTimestamp; uint256 index; mapping(address => uint256) users; } uint256 public DISTRIBUTION_END; uint8 constant public PRECISION = 18; mapping(address => AssetData) public assets; event AssetConfigUpdated(address indexed asset, uint256 emission); event AssetIndexUpdated(address indexed asset, uint256 index); event UserIndexUpdated(address indexed user, address indexed asset, uint256 index); event DistributionEndChanged(uint256 distributionEnd); function __StakingRewards_init(address emissionManager, uint256 distributionDuration) public initializer { __AccessControl_init_unchained(); DISTRIBUTION_END = block.timestamp.add(distributionDuration); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(EMISSION_MANAGER_ROLE, emissionManager); } /** * @dev Configures the distribution of rewards for a list of assets * @param assetsConfigInput The list of configurations to apply **/ function configureAssets(DistributionTypes.AssetConfigInput[] memory assetsConfigInput) public override { require(hasRole(EMISSION_MANAGER_ROLE, msg.sender), 'ONLY_EMISSION_MANAGER'); for (uint256 i = 0; i < assetsConfigInput.length; i++) { AssetData storage assetConfig = assets[assetsConfigInput[i].underlyingAsset]; _updateAssetStateInternal( assetsConfigInput[i].underlyingAsset, assetConfig, assetsConfigInput[i].totalStaked ); assetConfig.emissionPerSecond = assetsConfigInput[i].emissionPerSecond; emit AssetConfigUpdated( assetsConfigInput[i].underlyingAsset, assetsConfigInput[i].emissionPerSecond ); } } /** * @notice Change distribution end datetime * @param _distributionEndDate new distribution end datetime (UNIX Timestamp) */ function changeDistributionEndDate(uint256 _distributionEndDate) public override { require(hasRole(EMISSION_MANAGER_ROLE, msg.sender), 'ONLY_EMISSION_MANAGER'); return _changeDistributionEndDate(_distributionEndDate); } /** * @notice Change distribution end datetime internal function * @param _distributionEndDate new distribution end datetime (UNIX Timestamp) */ function _changeDistributionEndDate(uint256 _distributionEndDate) internal { DISTRIBUTION_END = _distributionEndDate; emit DistributionEndChanged(DISTRIBUTION_END); } /** * @dev Updates the state of one distribution, mainly rewards index and timestamp * @param underlyingAsset The address used as key in the distribution * @param assetConfig Storage pointer to the distribution's config * @param totalStaked Current total of staked assets for this distribution * @return The new distribution index **/ function _updateAssetStateInternal( address underlyingAsset, AssetData storage assetConfig, uint256 totalStaked ) internal returns (uint256) { uint256 oldIndex = assetConfig.index; uint128 lastUpdateTimestamp = assetConfig.lastUpdateTimestamp; if (block.timestamp == lastUpdateTimestamp) { return oldIndex; } uint256 newIndex = _getAssetIndex( oldIndex, assetConfig.emissionPerSecond, lastUpdateTimestamp, totalStaked ); if (newIndex != oldIndex) { assetConfig.index = newIndex; emit AssetIndexUpdated(underlyingAsset, newIndex); } assetConfig.lastUpdateTimestamp = uint128(block.timestamp); return newIndex; } /** * @dev Updates the state of an user in a distribution * @param user The user's address * @param asset The address of the reference asset of the distribution * @param stakedByUser Amount of tokens staked by the user in the distribution at the moment * @param totalStaked Total tokens staked in the distribution * @return The accrued rewards for the user until the moment **/ function _updateUserAssetInternal( address user, address asset, uint256 stakedByUser, uint256 totalStaked ) internal returns (uint256) { AssetData storage assetData = assets[asset]; uint256 userIndex = assetData.users[user]; uint256 accruedRewards = 0; uint256 newIndex = _updateAssetStateInternal(asset, assetData, totalStaked); if (userIndex != newIndex) { if (stakedByUser != 0) { accruedRewards = _getRewards(stakedByUser, newIndex, userIndex); } assetData.users[user] = newIndex; emit UserIndexUpdated(user, asset, newIndex); } return accruedRewards; } /** * @dev Used by "frontend" stake contracts to update the data of an user when claiming rewards from there * @param user The address of the user * @param stakes List of structs of the user data related with his stake * @return The accrued rewards for the user until the moment **/ function _claimRewards(address payable user, DistributionTypes.UserStakeInput[] memory stakes) internal returns (uint256) { uint256 accruedRewards = 0; for (uint256 i = 0; i < stakes.length; i++) { accruedRewards = accruedRewards.add( _updateUserAssetInternal( user, stakes[i].underlyingAsset, stakes[i].stakedByUser, stakes[i].totalStaked ) ); } return accruedRewards; } /** * @dev Return the accrued rewards for an user over a list of distribution * @param user The address of the user * @param stakes List of structs of the user data related with his stake * @return The accrued rewards for the user until the moment **/ function _getUnclaimedRewards(address user, DistributionTypes.UserStakeInput[] memory stakes) internal view returns (uint256) { uint256 accruedRewards = 0; for (uint256 i = 0; i < stakes.length; i++) { AssetData storage assetConfig = assets[stakes[i].underlyingAsset]; uint256 assetIndex = _getAssetIndex( assetConfig.index, assetConfig.emissionPerSecond, assetConfig.lastUpdateTimestamp, stakes[i].totalStaked ); accruedRewards = accruedRewards.add( _getRewards(stakes[i].stakedByUser, assetIndex, assetConfig.users[user]) ); } return accruedRewards; } /** * @dev Internal function for the calculation of user's rewards on a distribution * @param principalUserBalance Amount staked by the user on a distribution * @param reserveIndex Current index of the distribution * @param userIndex Index stored for the user, representation his staking moment * @return The rewards **/ function _getRewards( uint256 principalUserBalance, uint256 reserveIndex, uint256 userIndex ) internal view returns (uint256) { return principalUserBalance.mul(reserveIndex.sub(userIndex)).div(10**uint256(PRECISION)); } /** * @dev Calculates the next value of an specific distribution index, with validations * @param currentIndex Current index of the distribution * @param emissionPerSecond Representing the total rewards distributed per second per asset unit, on the distribution * @param lastUpdateTimestamp Last moment this distribution was updated * @param totalBalance of tokens considered for the distribution * @return The new index. **/ function _getAssetIndex( uint256 currentIndex, uint256 emissionPerSecond, uint128 lastUpdateTimestamp, uint256 totalBalance ) internal view returns (uint256) { if ( emissionPerSecond == 0 || totalBalance == 0 || lastUpdateTimestamp == block.timestamp || lastUpdateTimestamp >= DISTRIBUTION_END ) { return currentIndex; } uint256 currentTimestamp = block.timestamp > DISTRIBUTION_END ? DISTRIBUTION_END : block.timestamp; uint256 timeDelta = currentTimestamp.sub(lastUpdateTimestamp); return emissionPerSecond.mul(timeDelta).mul(10**uint256(PRECISION)).div(totalBalance).add( currentIndex ); } /** * @dev Returns the data of an user on a distribution * @param user Address of the user * @param asset The address of the reference asset of the distribution * @return The new index **/ function getUserAssetData(address user, address asset) public view returns (uint256) { return assets[asset].users[user]; } } // SPDX-License-Identifier: gpl-3.0 pragma solidity 0.7.5; import '../ERCs/ERC677/ERC677Upgradeable.sol'; import '../ERCs/ERC2612/ERC2612Upgradeable.sol'; import '@openzeppelin/contracts-upgradeable/proxy/Initializable.sol'; import 'hardhat/console.sol'; contract BaseTokenUpgradeable is Initializable, ERC677Upgradeable, ERC2612Upgradeable { function __BaseTokenUpgradeable_init( address _initialAccount, uint256 _initialBalance, string memory _name, string memory _symbol, string memory _EIP712Name ) public initializer { __ERC677_init(_initialAccount, _initialBalance, _name, _symbol); __ERC2612_init(_EIP712Name); } function permit( address _holder, address _spender, uint256 _nonce, uint256 _expiry, bool _allowed, uint8 _v, bytes32 _r, bytes32 _s ) public override { bytes32 digest = keccak256( abi.encodePacked( '\x19\x01', DOMAIN_SEPARATOR, keccak256( abi.encode(PERMIT_TYPEHASH, _holder, _spender, _nonce, _expiry, _allowed) ) ) ); require(_holder != address(0), 'Token: invalid-address-0'); require(_holder == ecrecover(digest, _v, _r, _s), 'Token: invalid-permit'); require(_expiry == 0 || block.timestamp <= _expiry, 'Token: permit-expired'); require(_nonce == nonces[_holder]++, 'Token: invalid-nonce'); uint256 _amount = _allowed ? 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff : 0; _approve(_holder, _spender, _amount); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.5; interface IOriginatorManager { function setUpTerms( address auditor, address originator, address governance, uint256 auditorPercentage, uint256 originatorPercentage, uint256 stakingGoal, uint256 defaultDelay ) external; function renewTerms( uint256 newAuditorPercentage, uint256 newOriginatorPercentage, uint256 newStakingGoal, uint128 newDistributionDuration, uint256 newDefaultDelay ) external; function declareDefault(uint256 defaultedAmount) external; function liquidateProposerStake(uint256 amount, bytes32 role) external; function declareStakingEnd() external; function hasReachedGoal() external view returns (bool); } interface IProjectFundedRewards { function startProjectFundedRewards(uint128 extraEmissionsPerSecond, address lendingContractAddress) external; function endProjectFundedRewards(uint128 extraEmissionsPerSecond, address lendingContractAddress) external; } interface IStaking { function stake(address to, uint256 amount) external; function redeem(address to, uint256 amount) external; function claimRewards(address payable to, uint256 amount) external; function withdrawProposerStake(uint256 amount) external; function getTotalRewardsBalance(address staker) external view returns (uint256); } // SPDX-License-Identifier: gpl-3.0 pragma solidity 0.7.5; interface IReserve { event Transfer(address indexed to, uint256 amount); event RescueFunds(address token, address indexed to, uint256 amount); function balance() external view returns (uint256); function transfer(address payable _to, uint256 _value) external returns (bool); function rescueFunds( address _tokenToRescue, address _to, uint256 _amount ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.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 SafeMathUint128 { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint128 a, uint128 b) internal pure returns (uint128) { uint128 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(uint128 a, uint128 b) internal pure returns (uint128) { 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(uint128 a, uint128 b, string memory errorMessage) internal pure returns (uint128) { require(b <= a, errorMessage); uint128 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(uint128 a, uint128 b) internal pure returns (uint128) { // 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; } uint128 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(uint128 a, uint128 b) internal pure returns (uint128) { 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(uint128 a, uint128 b, string memory errorMessage) internal pure returns (uint128) { require(b > 0, errorMessage); uint128 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(uint128 a, uint128 b) internal pure returns (uint128) { 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(uint128 a, uint128 b, string memory errorMessage) internal pure returns (uint128) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @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 <0.8.0; import "./IERC20Upgradeable.sol"; import "../../math/SafeMathUpgradeable.sol"; import "../../utils/AddressUpgradeable.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 SafeERC20Upgradeable { using SafeMathUpgradeable for uint256; using AddressUpgradeable for address; function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20Upgradeable 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(IERC20Upgradeable 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(IERC20Upgradeable 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(IERC20Upgradeable 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(IERC20Upgradeable 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.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 SafeMathUpgradeable { /** * @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; } } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; 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 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 !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.5; pragma experimental ABIEncoderV2; library DistributionTypes { struct AssetConfigInput { uint128 emissionPerSecond; uint256 totalStaked; address underlyingAsset; } struct UserStakeInput { address underlyingAsset; uint256 stakedByUser; uint256 totalStaked; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.5; pragma experimental ABIEncoderV2; import '../lib/DistributionTypes.sol'; interface IStakingRewards { function changeDistributionEndDate(uint256 date) external; function configureAssets(DistributionTypes.AssetConfigInput[] memory assetsConfigInput) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/EnumerableSetUpgradeable.sol"; import "../utils/AddressUpgradeable.sol"; import "../utils/ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * 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 AccessControlUpgradeable is Initializable, ContextUpgradeable { function __AccessControl_init() internal initializer { __Context_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; using AddressUpgradeable for address; struct RoleData { EnumerableSetUpgradeable.AddressSet 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 Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @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 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 { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _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 { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _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 { 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, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ 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 * ==== */ 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); } 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.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 EnumerableSetUpgradeable { // 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)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/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 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 ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } 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; } uint256[50] private __gap; } // SPDX-License-Identifier: gpl-3.0 pragma solidity 0.7.5; import './IERC677.sol'; import './IERC677Receiver.sol'; import '@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol'; import '@openzeppelin/contracts-upgradeable/proxy/Initializable.sol'; contract ERC677Upgradeable is Initializable, IERC677, ERC20Upgradeable { /** * @dev Sets the values for {_name} and {_symbol}, initializes {_decimals} with * a default value of 18. And mints {_initialBalance} to address {_initialAccount} * * All three of these values are immutable: they can only be set once during * construction. */ function __ERC677_init( address _initialAccount, uint256 _initialBalance, string memory _name, string memory _symbol ) internal initializer { __ERC20_init(_name, _symbol); if (_initialBalance != 0) { _mint(_initialAccount, _initialBalance); } } /** * @dev check if an address is a contract. * @param _addr The address to check. */ function isContract(address _addr) private view returns (bool hasCode) { uint256 length; assembly { length := extcodesize(_addr) } return length > 0; } /** * @dev transfer token to a contract address with additional data if the recipient is a contact. * @param _to The address to transfer to. * @param _value The amount to be transferred. * @param _data The extra data to be passed to the receiving contract. */ function transferAndCall( address _to, uint256 _value, bytes memory _data ) public virtual override returns (bool success) { require(super.transfer(_to, _value), 'ERC677Upgradeable: transfer failed'); if (isContract(_to)) { IERC677Receiver(_to).onTokenTransfer(msg.sender, _value, _data); } return true; } } // SPDX-License-Identifier: gpl-3.0 pragma solidity 0.7.5; import '@openzeppelin/contracts-upgradeable/proxy/Initializable.sol'; abstract contract ERC2612Upgradeable is Initializable { // --- EIP712 niceties --- bytes32 public DOMAIN_SEPARATOR; // bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address holder,address spender,uint256 nonce,uint256 expiry,bool allowed)"); bytes32 public PERMIT_TYPEHASH; string public version; mapping(address => uint256) public nonces; function __ERC2612_init(string memory _EIP712Name) internal initializer { version = '1'; DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256( 'EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)' ), keccak256(bytes(_EIP712Name)), keccak256(bytes(version)), getChainId(), address(this) ) ); PERMIT_TYPEHASH = 0xea2aa0a1be11a07ed86d755c93467f4f82362b452371d1ba94d1715123511acb; } function permit( address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s ) public virtual; function getChainId() public pure returns (uint256 chainId) { // solhint-disable-next-line no-inline-assembly assembly { chainId := chainid() } } } // SPDX-License-Identifier: MIT pragma solidity >= 0.4.22 <0.9.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // SPDX-License-Identifier: gpl-3.0 pragma solidity 0.7.5; interface IERC677 { function transferAndCall( address to, uint256 value, bytes memory data ) external returns (bool ok); event Transfer(address indexed from, address indexed to, uint256 value, bytes data); } // SPDX-License-Identifier: gpl-3.0 pragma solidity 0.7.5; interface IERC677Receiver { function onTokenTransfer( address from, uint256 amount, bytes calldata data ) external returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/ContextUpgradeable.sol"; import "./IERC20Upgradeable.sol"; import "../../math/SafeMathUpgradeable.sol"; import "../../proxy/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 ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable { using SafeMathUpgradeable for uint256; 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_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(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 virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual 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 view virtual returns (uint8) { return _decimals; } /** * @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); _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 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 virtual { _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 { } uint256[44] private __gap; }
Function to declare as DEFAULT _defaultedAmount uint256/
function declareDefault(uint256 _defaultedAmount) external override onlyGovernance onlyOnStakingState { require(block.timestamp >= DEFAULT_DATE, 'DEFAULT_DATE_NOT_REACHED'); defaultedAmount = _defaultedAmount; _endDistributionIfNeeded(); _changeState(OriginatorStakingState.DEFAULT); }
142,847
//Address: 0xd0df293593912a594b790137ff3b7a296ec33f42 //Contract name: MoyTokenOpenDistribution //Balance: 0 Ether //Verification Date: 12/30/2017 //Transacion Count: 2 // CODE STARTS HERE pragma solidity ^0.4.18; // **----------------------------------------------- // MoyToken Open Distribution Smart Contract. // 30,000,000 tokens available via unique Open Distribution. // POWTokens Contract @ POWToken.eth // Open Dsitribution Opens at the 1st Block of 2018. // All operations can be monitored at etherscan.io // ----------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/issues/20 // ------------------------------------------------- contract owned { address public owner; function owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { owner = newOwner; } } contract safeMath { function safeMul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; safeAssert(a == 0 || c / a == b); return c; } function safeDiv(uint256 a, uint256 b) internal pure returns (uint256) { safeAssert(b > 0); uint256 c = a / b; safeAssert(a == b * c + a % b); return c; } function safeSub(uint256 a, uint256 b) internal pure returns (uint256) { safeAssert(b <= a); return a - b; } function safeAdd(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; safeAssert(c>=a && c>=b); return c; } function safeAssert(bool assertion) internal pure { if (!assertion) revert(); } } contract StandardToken is owned, safeMath { 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 MoyTokenOpenDistribution is owned, safeMath { // owner/admin & token reward address public admin = owner; //admin address StandardToken public tokenContract; // address of MoibeTV MOY ERC20 Standard Token. // deployment variables for static supply sale uint256 public initialSupply; uint256 public tokensRemaining; // multi-sig addresses and price variable address public budgetWallet; // budgetMultiSig for PowerLineUp. uint256 public tokensPerEthPrice; // set initial value floating priceVar. // uint256 values for min,max,caps,tracking uint256 public amountRaised; uint256 public fundingCap; // loop control, startup and limiters string public CurrentStatus = ""; // current OpenDistribution status uint256 public fundingStartBlock; // OpenDistribution start block# uint256 public fundingEndBlock; // OpenDistribution end block# bool public isOpenDistributionClosed = false; // OpenDistribution completion boolean bool public areFundsReleasedToBudget= false; // boolean for MoibeTV to receive Eth or not, this allows MoibeTV to use Ether only if goal reached. bool public isOpenDistributionSetup = false; // boolean for OpenDistribution setup event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); event Buy(address indexed _sender, uint256 _eth, uint256 _MOY); mapping(address => uint256) balancesArray; mapping(address => uint256) fundValue; // default function, map admin function MoyOpenDistribution() public onlyOwner { admin = msg.sender; CurrentStatus = "Tokens Released, Open Distribution deployed to chain"; } // total number of tokens initially function initialMoySupply() public constant returns (uint256 tokenTotalSupply) { tokenTotalSupply = safeDiv(initialSupply,100); } // remaining number of tokens function remainingSupply() public constant returns (uint256 tokensLeft) { tokensLeft = tokensRemaining; } // setup the OpenDistribution parameters function setupOpenDistribution(uint256 _fundingStartBlock, uint256 _fundingEndBlock, address _tokenContract, address _budgetWallet) public onlyOwner returns (bytes32 response) { if ((msg.sender == admin) && (!(isOpenDistributionSetup)) && (!(budgetWallet > 0))){ // init addresses tokenContract = StandardToken(_tokenContract); //MoibeTV MOY tokens Smart Contract. budgetWallet = _budgetWallet; //Budget multisig. tokensPerEthPrice = 1000; //Regular Price 1 ETH = 1000 MOY. fundingCap = 3; // update values amountRaised = 0; initialSupply = 30000000; tokensRemaining = safeDiv(initialSupply,1); fundingStartBlock = _fundingStartBlock; fundingEndBlock = _fundingEndBlock; // configure OpenDistribution isOpenDistributionSetup = true; isOpenDistributionClosed = false; CurrentStatus = "OpenDistribution is setup"; //gas reduction experiment setPrice(); return "OpenDistribution is setup"; } else if (msg.sender != admin) { return "Not Authorized"; } else { return "Campaign cannot be changed."; } } function setPrice() public { //Verificar si es necesario que sea pública. //Funding Starts at the 1st Block of the Year. The very 1st block of the year is 4830771 UTC+14(Christmas Islands). //After that, all the CrowdSale is measured in UTC-11(Fiji), to give chance until the very last block of each day. if (block.number >= fundingStartBlock && block.number <= fundingStartBlock+11520) { // First Day 300% Bonus, 1 ETH = 3000 MOY. tokensPerEthPrice = 3000; } else if (block.number >= fundingStartBlock+11521 && block.number <= fundingStartBlock+46080) { // First Week 200% Bonus, 1 ETH = 2000 MOY. tokensPerEthPrice = 2000; //Regular Price for All Stages. } else if (block.number >= fundingStartBlock+46081 && block.number <= fundingStartBlock+86400) { // Second Week 150% Bonus, 1 ETH = 1500 MOY. tokensPerEthPrice = 2000; //Regular Price for All Stages. } else if (block.number >= fundingStartBlock+86401 && block.number <= fundingEndBlock) { // Regular Sale, final price for all users 1 ETH = 1000 MOY. tokensPerEthPrice = 1000; //Regular Price for All Stages. } } // default payable function when sending ether to this contract function () public payable { require(msg.data.length == 0); BuyMOYTokens(); } function BuyMOYTokens() public payable { // 0. conditions (length, OpenDistribution setup, zero check, exceed funding contrib check, contract valid check, within funding block range check, balance overflow check etc.) require(!(msg.value == 0) && (isOpenDistributionSetup) && (block.number >= fundingStartBlock) && (block.number <= fundingEndBlock) && (tokensRemaining > 0)); // 1. vars uint256 rewardTransferAmount = 0; // 2. effects setPrice(); amountRaised = safeAdd(amountRaised,msg.value); rewardTransferAmount = safeDiv(safeMul(msg.value,tokensPerEthPrice),1); // 3. interaction tokensRemaining = safeSub(tokensRemaining, safeDiv(rewardTransferAmount,1)); // will cause throw if attempt to purchase over the token limit in one tx or at all once limit reached. tokenContract.transfer(msg.sender, rewardTransferAmount); // 4. events fundValue[msg.sender] = safeAdd(fundValue[msg.sender], msg.value); Transfer(this, msg.sender, msg.value); Buy(msg.sender, msg.value, rewardTransferAmount); } function budgetMultiSigWithdraw(uint256 _amount) public onlyOwner { require(areFundsReleasedToBudget && (amountRaised >= fundingCap)); budgetWallet.transfer(_amount); } function checkGoalReached() public onlyOwner returns (bytes32 response) { // return OpenDistribution status to owner for each result case, update public constant. // update state & status variables require (isOpenDistributionSetup); if ((amountRaised < fundingCap) && (block.number <= fundingEndBlock && block.number >= fundingStartBlock)) { // OpenDistribution in progress waiting for hardcap. areFundsReleasedToBudget = false; isOpenDistributionClosed = false; CurrentStatus = "OpenDistribution in progress, waiting to reach goal."; return "OpenDistribution in progress."; } else if ((amountRaised < fundingCap) && (block.number < fundingStartBlock)) { // OpenDistribution has not started. areFundsReleasedToBudget = false; isOpenDistributionClosed = false; CurrentStatus = "OpenDistribution is setup"; return "OpenDistribution is setup"; } else if ((amountRaised < fundingCap) && (block.number > fundingEndBlock)) { // OpenDistribution ended, total not achieved. areFundsReleasedToBudget = false; isOpenDistributionClosed = true; CurrentStatus = "OpenDistribution is Over."; return "OpenDistribution is Over"; } else if ((amountRaised >= fundingCap) && (tokensRemaining == 0)) { // Distribution ended, all tokens gone. areFundsReleasedToBudget = true; isOpenDistributionClosed = true; CurrentStatus = "Successful OpenDistribution."; return "Successful OpenDistribution."; } else if ((amountRaised >= fundingCap) && (block.number > fundingEndBlock) && (tokensRemaining > 0)) { // OpenDistribution ended. areFundsReleasedToBudget = true; isOpenDistributionClosed = true; CurrentStatus = "Successful OpenDistribution."; return "Successful OpenDistribution"; } else if ((amountRaised >= fundingCap) && (tokensRemaining > 0) && (block.number <= fundingEndBlock)) { // OpenDistribution in progress, objetive achieved! areFundsReleasedToBudget = true; isOpenDistributionClosed = false; CurrentStatus = "OpenDistribution in Progress, Goal Achieved."; return "Goal Achieved."; } setPrice(); } }
0. conditions (length, OpenDistribution setup, zero check, exceed funding contrib check, contract valid check, within funding block range check, balance overflow check etc.) 1. vars 2. effects 3. interaction 4. events
function BuyMOYTokens() public payable { require(!(msg.value == 0) && (isOpenDistributionSetup) && (block.number >= fundingStartBlock) && (block.number <= fundingEndBlock) && (tokensRemaining > 0)); uint256 rewardTransferAmount = 0; setPrice(); amountRaised = safeAdd(amountRaised,msg.value); rewardTransferAmount = safeDiv(safeMul(msg.value,tokensPerEthPrice),1); tokenContract.transfer(msg.sender, rewardTransferAmount); fundValue[msg.sender] = safeAdd(fundValue[msg.sender], msg.value); Transfer(this, msg.sender, msg.value); Buy(msg.sender, msg.value, rewardTransferAmount); }
12,886,841
//Address: 0x20f7a3ddf244dc9299975b4da1c39f8d5d75f05a //Contract name: SapienToken //Balance: 0 Ether //Verification Date: 4/3/2018 //Transacion Count: 4104 // CODE STARTS HERE pragma solidity ^0.4.18; // File: contracts/zeppelin-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 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; } } // File: contracts/zeppelin-solidity/contracts/ownership/Claimable.sol /** * @title Claimable * @dev Extension for the Ownable contract, where the ownership needs to be claimed. * This allows the new owner to accept the transfer. */ contract Claimable is Ownable { address public pendingOwner; /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == pendingOwner); _; } /** * @dev Allows the current owner to set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { pendingOwner = newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() onlyPendingOwner public { OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } } // File: contracts/OwnClaimRenounceable.sol /** * @title `owner` can renounce its role and leave the contract unowned. * @dev There can not be a new `owner`. * @dev No `onlyOwner` functions can ever be called again. */ contract OwnClaimRenounceable is Claimable { function renounceOwnershipForever(uint8 _confirm) public onlyOwner { require(_confirm == 73); // Owner knows what he's doing owner = address(0); pendingOwner = address(0); } } // File: contracts/TokenController.sol /** The interface for a token contract to notify a controller of every transfers. */ contract TokenController { bytes4 public constant INTERFACE = bytes4(keccak256("TokenController")); function allowTransfer(address _sender, address _from, address _to, uint256 _value, bytes _purpose) public returns (bool); } // Basic examples contract YesController is TokenController { function allowTransfer(address /* _sender */, address /* _from */, address /* _to */, uint256 /* _value */, bytes /* _purpose */) public returns (bool) { return true; // allow all transfers } } contract NoController is TokenController { function allowTransfer(address /* _sender */, address /* _from */, address /* _to */, uint256 /* _value */, bytes /* _purpose */) public returns (bool) { return false; // veto all transfers } } // File: contracts/zeppelin-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) { 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/zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev 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: contracts/zeppelin-solidity/contracts/token/ERC20/BasicToken.sol /** * @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]); // 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 view returns (uint256 balance) { return balances[_owner]; } } // File: contracts/zeppelin-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: contracts/zeppelin-solidity/contracts/token/ERC20/StandardToken.sol /** * @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)) 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 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, uint _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, uint _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/SapienCoin.sol /** * @title Has a `controller`. * @dev The `controller` must be a contract implementing TokenController. * @dev The `controller` can track or veto the tokens transfers. * @dev The `controller` can assign its role to another address. * @dev The `owner` have all the powers of the `controller`. */ contract Controlled is OwnClaimRenounceable { bytes4 public constant TOKEN_CONTROLLER_INTERFACE = bytes4(keccak256("TokenController")); TokenController public controller; function Controlled() public {} /// @notice The address of the controller is the only address that can call /// a function with this modifier modifier onlyControllerOrOwner { require((msg.sender == address(controller)) || (msg.sender == owner)); _; } /// @notice Changes the controller of the contract /// @param _newController The new controller of the contract function changeController(TokenController _newController) public onlyControllerOrOwner { if(address(_newController) != address(0)) { // Check type to prevent mistakes require(_newController.INTERFACE() == TOKEN_CONTROLLER_INTERFACE); } controller = _newController; } } contract ControlledToken is StandardToken, Controlled { modifier controllerCallback(address _from, address _to, uint256 _value, bytes _purpose) { // If a controller is present, ask it about the transfer. if(address(controller) != address(0)) { bool _allow = controller.allowTransfer(msg.sender, _from, _to, _value, _purpose); if(!_allow) { return; // Do not transfer } } _; // Proceed with the transfer } /** @dev ERC20 transfer with controller callback */ function transfer(address _to, uint256 _value) public controllerCallback(msg.sender, _to, _value, hex"") returns (bool) { return super.transfer(_to, _value); } /** @dev ERC20 transferFrom with controller callback */ function transferFrom(address _from, address _to, uint256 _value) public controllerCallback(_from, _to, _value, hex"") returns (bool) { return super.transferFrom(_from, _to, _value); } /** * @dev Transfer tokens to a specified address, including a purpose. * @param _to The address to transfer to. * @param _value The amount to be transferred. * @param _purpose Arbitrary data attached to the transaction. */ function transferWithPurpose(address _to, uint256 _value, bytes _purpose) public controllerCallback(msg.sender, _to, _value, _purpose) returns (bool) { return super.transfer(_to, _value); } } contract BatchToken is ControlledToken { /** * @dev Transfer to many addresses in a single transaction. * @dev Call transfer(to, amount) with the arguments taken from two arrays. * @dev If one transfer is invalid, everything is aborted. * @dev The `_expectZero` option is intended for the initial batch minting. * It allows operations to be retried and prevents double-minting due to the * asynchronous and uncertain nature of blockchain transactions. * It should be avoided after trading has started. * @param _toArray Addresses that will receive tokens. * @param _amountArray Amounts of tokens to transfer, in the same order as `_toArray`. * @param _expectZero If false, transfer the tokens immediately. * If true, expect the current balance of `_to` to be zero before * the transfer. If not zero, skip this transfer but continue. */ function transferBatchIdempotent(address[] _toArray, uint256[] _amountArray, bool _expectZero) // Anyone can call if they have the balance public { // Check that the arrays are the same size uint256 _count = _toArray.length; require(_amountArray.length == _count); for (uint256 i = 0; i < _count; i++) { address _to = _toArray[i]; // Either regular transfer, or check that BasicToken.balances is zero. if(!_expectZero || (balanceOf(_to) == 0)) { transfer(_to, _amountArray[i]); } } } } /** * @title The Sapien Token. */ contract SapienToken is BatchToken { string public constant name = "Sapien Network"; string public constant symbol = "SPN"; uint256 public constant decimals = 6; string public constant website = "https://sapien.network"; /** * @dev The maximum supply that can be minted, in microSPN. * 500M with 6 decimals. */ uint256 public constant MAX_SUPPLY_USPN = 500 * 1000 * 1000 * (10**decimals); function SapienToken() public { // All initial tokens to owner balances[msg.sender] = MAX_SUPPLY_USPN; totalSupply_ = MAX_SUPPLY_USPN; } }
The maximum supply that can be minted, in microSPN. 500M with 6 decimals./ All initial tokens to owner
function SapienToken() public { balances[msg.sender] = MAX_SUPPLY_USPN; totalSupply_ = MAX_SUPPLY_USPN; }
13,030,219
//"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/utils/Address.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; contract LiquidityMining is Ownable { using SafeERC20 for IERC20; uint256 constant DECIMALS = 18; uint256 constant UNITS = 10**DECIMALS; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. uint256 rewardDebtAtBlock; // the last block user stake } // Info of each pool. struct PoolInfo { IERC20 token; // Address of LP token contract. uint256 tokenPerBlock; // tokens to distribute per block. There are aprox. 6500 blocks per day. 6500 * 1825 (5 years) = 11862500 total blocks. 600000000 token to be distributed in 11862500 = 50,579557428872497 token per block. uint256 lastRewardBlock; // Last block number that token distribution occurs. uint256 acctokenPerShare; // Accumulated tokens per share, times 1e18 (UNITS). uint256 waitForWithdraw; // Spent tokens until now, even if they are not withdrawn. } IERC20 public tokenToken; address public tokenLiquidityMiningWallet; // The block number when token mining starts. uint256 public START_BLOCK; // Info of each pool. PoolInfo[] public poolInfo; // tokenToPoolId mapping(address => uint256) public tokenToPoolId; // Info of each user that stakes LP tokens. pid => user address => info mapping(uint256 => mapping(address => UserInfo)) public userInfo; event Deposit(address indexed user, uint256 indexed poolId, uint256 amount); event Withdraw( address indexed user, uint256 indexed poolId, uint256 amount ); event EmergencyWithdraw( address indexed user, uint256 indexed poolId, uint256 amount ); event SendTokenReward( address indexed user, uint256 indexed poolId, uint256 amount ); event TokenPerBlockSet(uint256 amount); constructor( address _tokenAddress, address _tokenLiquidityMiningWallet, uint256 _startBlock ) public { require(_tokenAddress != address(0), "Token address should not be 0"); require(_tokenLiquidityMiningWallet != address(0), "TokenLiquidityMiningWallet address should not be 0"); tokenToken = IERC20(_tokenAddress); tokenLiquidityMiningWallet = _tokenLiquidityMiningWallet; START_BLOCK = _startBlock; } /********************** PUBLIC ********************************/ // Add a new erc20 token to the pool. Can only be called by the owner. function add( uint256 _tokenPerBlock, IERC20 _token, bool _withUpdate ) external onlyOwner { require( tokenToPoolId[address(_token)] == 0, "Token is already in pool" ); if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > START_BLOCK ? block.number : START_BLOCK; tokenToPoolId[address(_token)] = poolInfo.length + 1; poolInfo.push( PoolInfo({ token: _token, tokenPerBlock: _tokenPerBlock, lastRewardBlock: lastRewardBlock, acctokenPerShare: 0, waitForWithdraw: 0 }) ); } // Update the given pool's token allocation point. Can only be called by the owner. function set( uint256 _poolId, uint256 _tokenPerBlock, bool _withUpdate ) external onlyOwner { if (_withUpdate) { massUpdatePools(); } poolInfo[_poolId].tokenPerBlock = _tokenPerBlock; emit TokenPerBlockSet(_tokenPerBlock); } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 poolId = 0; poolId < length; ++poolId) { updatePool(poolId); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _poolId) public { PoolInfo storage pool = poolInfo[_poolId]; // Return if it's too early (if START_BLOCK is in the future probably) if (block.number <= pool.lastRewardBlock) return; // Retrieve amount of tokens held in contract uint256 poolBalance = pool.token.balanceOf(address(this)); // If the contract holds no tokens at all, don't proceed. if (poolBalance == 0) { pool.lastRewardBlock = block.number; return; } // Calculate the amount of token to send to the contract to pay out for this pool uint256 rewards = getPoolReward( pool.lastRewardBlock, block.number, pool.tokenPerBlock, pool.waitForWithdraw ); pool.waitForWithdraw += rewards; // Update the accumulated tokenPerShare pool.acctokenPerShare = pool.acctokenPerShare + (rewards * UNITS/poolBalance); // Update the last block pool.lastRewardBlock = block.number; } // Get rewards for a specific amount of tokenPerBlocks function getPoolReward( uint256 _from, uint256 _to, uint256 _tokenPerBlock, uint256 _waitForWithdraw ) public view returns (uint256 rewards) { // Calculate number of blocks covered. uint256 blockCount = _to - _from; // Get the amount of token for this pool uint256 amount = blockCount*(_tokenPerBlock); // Retrieve allowance and balance uint256 allowedToken = tokenToken.allowance( tokenLiquidityMiningWallet, address(this) ); uint256 farmingBalance = tokenToken.balanceOf(tokenLiquidityMiningWallet); // If the actual balance is less than the allowance, use the balance. allowedToken = farmingBalance < allowedToken ? farmingBalance : allowedToken; //no more token to pay as reward if(allowedToken <= _waitForWithdraw){ return 0; } allowedToken = allowedToken - _waitForWithdraw; // If we reached the total amount allowed already, return the allowedToken if (allowedToken < amount) { rewards = allowedToken; } else { rewards = amount; } } function claimReward(uint256 _poolId) external { updatePool(_poolId); _harvest(_poolId); } // Deposit LP tokens to tokenStaking for token allocation. function deposit(uint256 _poolId, uint256 _amount) external { require(_amount > 0, "Amount cannot be 0"); PoolInfo storage pool = poolInfo[_poolId]; UserInfo storage user = userInfo[_poolId][msg.sender]; updatePool(_poolId); _harvest(_poolId); // This is the very first deposit if (user.amount == 0) { user.rewardDebtAtBlock = block.number; } user.amount = user.amount+(_amount); user.rewardDebt = user.amount*(pool.acctokenPerShare)/(UNITS); emit Deposit(msg.sender, _poolId, _amount); pool.token.safeTransferFrom( address(msg.sender), address(this), _amount ); } // Withdraw LP tokens from tokenStaking. function withdraw(uint256 _poolId, uint256 _amount) external { PoolInfo storage pool = poolInfo[_poolId]; UserInfo storage user = userInfo[_poolId][msg.sender]; require(_amount > 0, "Amount cannot be 0"); updatePool(_poolId); _harvest(_poolId); user.amount = user.amount-(_amount); user.rewardDebt = user.amount*(pool.acctokenPerShare)/(UNITS); emit Withdraw(msg.sender, _poolId, _amount); pool.token.safeTransfer(address(msg.sender), _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _poolId) external { PoolInfo storage pool = poolInfo[_poolId]; UserInfo storage user = userInfo[_poolId][msg.sender]; uint256 amountToSend = user.amount; user.amount = 0; user.rewardDebt = 0; user.rewardDebtAtBlock = 0; emit EmergencyWithdraw(msg.sender, _poolId, amountToSend); pool.token.safeTransfer(address(msg.sender), amountToSend); } /********************** EXTERNAL ********************************/ // Return the number of added pools function poolLength() external view returns (uint256) { return poolInfo.length; } // View function to see pending tokens on frontend. function pendingReward(uint256 _poolId, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_poolId]; UserInfo storage user = userInfo[_poolId][_user]; uint256 acctokenPerShare = pool.acctokenPerShare; uint256 poolBalance = pool.token.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && poolBalance > 0) { uint256 rewards = getPoolReward( pool.lastRewardBlock, block.number, pool.tokenPerBlock, pool.waitForWithdraw ); acctokenPerShare = acctokenPerShare+( rewards*(UNITS)/(poolBalance) ); } uint256 pending = user.amount*(acctokenPerShare)/(UNITS)-( user.rewardDebt ); return pending; } /********************** INTERNAL ********************************/ function _harvest(uint256 _poolId) internal { PoolInfo storage pool = poolInfo[_poolId]; UserInfo storage user = userInfo[_poolId][msg.sender]; if (user.amount == 0) return; uint256 pending = user.amount*(pool.acctokenPerShare)/(UNITS)-(user.rewardDebt); uint256 tokenAvailable = tokenToken.balanceOf(tokenLiquidityMiningWallet); if (pending > tokenAvailable) { pending = tokenAvailable; } if (pending > 0) { user.rewardDebtAtBlock = block.number; user.rewardDebt = user.amount*(pool.acctokenPerShare)/(UNITS); pool.waitForWithdraw -= pending; emit SendTokenReward(msg.sender, _poolId, pending); // Pay out the pending rewards tokenToken.safeTransferFrom( tokenLiquidityMiningWallet, msg.sender, pending ); return; } user.rewardDebt = user.amount*(pool.acctokenPerShare)/(UNITS); } function changeRewardsWallet(address _address) external onlyOwner { require(_address != address(0),"Address should not be 0"); tokenLiquidityMiningWallet = _address; } } // 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; 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' 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 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; 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); } } } } // 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; /** * @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; } }
Get rewards for a specific amount of tokenPerBlocks Calculate number of blocks covered. Get the amount of token for this pool Retrieve allowance and balance If the actual balance is less than the allowance, use the balance.no more token to pay as reward If we reached the total amount allowed already, return the allowedToken
function getPoolReward( uint256 _from, uint256 _to, uint256 _tokenPerBlock, uint256 _waitForWithdraw ) public view returns (uint256 rewards) { uint256 blockCount = _to - _from; uint256 amount = blockCount*(_tokenPerBlock); uint256 allowedToken = tokenToken.allowance( tokenLiquidityMiningWallet, address(this) ); uint256 farmingBalance = tokenToken.balanceOf(tokenLiquidityMiningWallet); allowedToken = farmingBalance < allowedToken ? farmingBalance : allowedToken; if(allowedToken <= _waitForWithdraw){ return 0; } allowedToken = allowedToken - _waitForWithdraw; if (allowedToken < amount) { rewards = allowedToken; rewards = amount; } }
13,489,945
//Twitter: https://twitter.com/web3_io //TG: https://t.me/web3eth pragma solidity 0.8.9; 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; } } interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure 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); 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; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } 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 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); } 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); } contract ERC20 is Context, IERC20, IERC20Metadata { using SafeMath for uint256; 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 default 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); _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: * * - `account` 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 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 {} } 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; } } 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 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; } } library SafeMathInt { int256 private constant MIN_INT256 = int256(1) << 255; int256 private constant MAX_INT256 = ~(int256(1) << 255); /** * @dev Multiplies two int256 variables and fails on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { int256 c = a * b; // Detect overflow when multiplying MIN_INT256 with -1 require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256)); require((b == 0) || (c / b == a)); return c; } /** * @dev Division of two int256 variables and fails on overflow. */ function div(int256 a, int256 b) internal pure returns (int256) { // Prevent overflow when dividing MIN_INT256 by -1 require(b != -1 || a != MIN_INT256); // Solidity already throws when dividing by 0. return a / b; } /** * @dev Subtracts two int256 variables and fails 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 int256 variables and fails 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 Converts to absolute value, and fails on overflow. */ function abs(int256 a) internal pure returns (int256) { require(a != MIN_INT256); return a < 0 ? -a : a; } function toUint256Safe(int256 a) internal pure returns (uint256) { require(a >= 0); return uint256(a); } } library SafeMathUint { function toInt256Safe(uint256 a) internal pure returns (int256) { int256 b = int256(a); require(b >= 0); return b; } } interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint 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 returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } contract Web3Official is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; address public constant deadAddress = address(0xdead); bool private swapping; address public marketingWallet; address public devWallet; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; uint256 public percentForLPBurn = 25; // 25 = .25% bool public lpBurnEnabled = false; uint256 public lpBurnFrequency = 3600 seconds; uint256 public lastLpBurnTime; uint256 public manualBurnFrequency = 30 minutes; uint256 public lastManualLpBurnTime; bool public limitsInEffect = true; bool public tradingActive = true; bool public swapEnabled = true; // Anti-bot and anti-whale mappings and variables mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch bool public transferDelayEnabled = true; uint256 public buyTotalFees; uint256 public buyMarketingFee; uint256 public buyLiquidityFee; uint256 public buyDevFee; uint256 public sellTotalFees; uint256 public sellMarketingFee; uint256 public sellLiquidityFee; uint256 public sellDevFee; uint256 public tokensForMarketing; uint256 public tokensForLiquidity; uint256 public tokensForDev; /******************/ // exlcude from fees and max transaction amount mapping (address => bool) private _isExcludedFromFees; mapping (address => bool) public _isExcludedMaxTransactionAmount; // store addresses that a automatic market maker pairs. Any transfer *to* these addresses // could be subject to a maximum transfer amount mapping (address => bool) public automatedMarketMakerPairs; event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress); event ExcludeFromFees(address indexed account, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event marketingWalletUpdated(address indexed newWallet, address indexed oldWallet); event devWalletUpdated(address indexed newWallet, address indexed oldWallet); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event AutoNukeLP(); event ManualNukeLP(); constructor() ERC20("Web3Official", "web3") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 2; uint256 _buyLiquidityFee = 3; uint256 _buyDevFee = 1; uint256 _sellMarketingFee = 2; uint256 _sellLiquidityFee = 4; uint256 _sellDevFee = 2; uint256 totalSupply = 1 * 1e12 * 1e18; maxTransactionAmount = totalSupply * 5 / 1000; // 0.5% maxTransactionAmountTxn maxWallet = totalSupply * 1 / 100; // 1% maxWallet swapTokensAtAmount = totalSupply * 5 / 1000; // 0.5% swap wallet buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; marketingWallet = address(owner()); // set as marketing wallet devWallet = address(owner()); // set as dev wallet // exclude from paying fees or having max transaction amount excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); /* _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again */ _mint(msg.sender, totalSupply); } receive() external payable { } // once enabled, can never be turned off function enableTrading() external onlyOwner { tradingActive = true; swapEnabled = true; lastLpBurnTime = block.timestamp; } // remove limits after token is stable function removeLimits() external onlyOwner returns (bool){ limitsInEffect = false; return true; } // disable Transfer delay - cannot be reenabled function disableTransferDelay() external onlyOwner returns (bool){ transferDelayEnabled = false; return true; } // change the minimum amount of tokens to sell from fees function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){ require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply."); require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply."); swapTokensAtAmount = newAmount; return true; } function updateMaxTxnAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 1 / 1000)/1e18, "Cannot set maxTransactionAmount lower than 0.1%"); maxTransactionAmount = newNum * (10**18); } function updateMaxWalletAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 5 / 1000)/1e18, "Cannot set maxWallet lower than 0.5%"); maxWallet = newNum * (10**18); } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } // only use to disable contract sales if absolutely necessary (emergency use only) function updateSwapEnabled(bool enabled) external onlyOwner(){ swapEnabled = enabled; } function updateBuyFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner { buyMarketingFee = _marketingFee; buyLiquidityFee = _liquidityFee; buyDevFee = _devFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; require(buyTotalFees <= 20, "Must keep fees at 20% or less"); } function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner { sellMarketingFee = _marketingFee; sellLiquidityFee = _liquidityFee; sellDevFee = _devFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; require(sellTotalFees <= 25, "Must keep fees at 25% or less"); } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } function updateMarketingWallet(address newMarketingWallet) external onlyOwner { emit marketingWalletUpdated(newMarketingWallet, marketingWallet); marketingWallet = newMarketingWallet; } function updateDevWallet(address newWallet) external onlyOwner { emit devWalletUpdated(newWallet, devWallet); devWallet = newWallet; } function isExcludedFromFees(address account) public view returns(bool) { return _isExcludedFromFees[account]; } event BoughtEarly(address indexed sniper); function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } // at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch. if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } //when buy if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } //when sell else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; // if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; // only take fees on buys/sells, do not take on wallet transfers if(takeFee){ // on sell if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } // on buy else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable deadAddress, block.timestamp ); } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if(contractBalance == 0 || totalTokensToSwap == 0) {return;} if(contractBalance > swapTokensAtAmount * 20){ contractBalance = swapTokensAtAmount * 20; } // Halve the amount of liquidity tokens uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2; uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; (success,) = address(devWallet).call{value: ethForDev}(""); if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } (success,) = address(marketingWallet).call{value: address(this).balance}(""); } function setAutoLPBurnSettings(uint256 _frequencyInSeconds, uint256 _percent, bool _Enabled) external onlyOwner { require(_frequencyInSeconds >= 600, "cannot set buyback more often than every 10 minutes"); require(_percent <= 1000 && _percent >= 0, "Must set auto LP burn percent between 0% and 10%"); lpBurnFrequency = _frequencyInSeconds; percentForLPBurn = _percent; lpBurnEnabled = _Enabled; } function autoBurnLiquidityPairTokens() internal returns (bool){ lastLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div(10000); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0){ super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit AutoNukeLP(); return true; } function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool){ require(block.timestamp > lastManualLpBurnTime + manualBurnFrequency , "Must wait for cooldown to finish"); require(percent <= 1000, "May not nuke more than 10% of tokens in LP"); lastManualLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0){ super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit ManualNukeLP(); return true; } }
get balance of liquidity pair calculate amount to burn pull tokens from pancakePair liquidity and move to dead address permanently
function autoBurnLiquidityPairTokens() internal returns (bool){ lastLpBurnTime = block.timestamp; uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div(10000); if (amountToBurn > 0){ super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } pair.sync(); emit AutoNukeLP(); return true; }
5,776,301
// File: contracts/interfaces/SIInterface.sol interface SIInterface { function setCircuitBreakWithOwner(bool emergency) external returns (bool); function setCircuitBreaker(bool emergency) external returns (bool); function updateRewardPerBlockLogic(uint256 _rewardPerBlock) external returns (bool); function updateRewardLane(address payable userAddr) external returns (bool); function getBetaRateBaseTotalAmount() external view returns (uint256); function getBetaRateBaseUserAmount(address payable userAddr) external view returns (uint256); function getMarketRewardInfo() external view returns (uint256, uint256, uint256); function getUserRewardInfo(address payable userAddr) external view returns (uint256, uint256, uint256); } // File: contracts/interfaces/marketHandlerDataStorageInterface.sol pragma solidity 0.6.12; interface marketHandlerDataStorageInterface { function setCircuitBreaker(bool _emergency) external returns (bool); function setNewCustomer(address payable userAddr) external returns (bool); function getUserAccessed(address payable userAddr) external view returns (bool); function setUserAccessed(address payable userAddr, bool _accessed) external returns (bool); function getReservedAddr() external view returns (address payable); function setReservedAddr(address payable reservedAddress) external returns (bool); function getReservedAmount() external view returns (int256); function addReservedAmount(uint256 amount) external returns (int256); function subReservedAmount(uint256 amount) external returns (int256); function updateSignedReservedAmount(int256 amount) external returns (int256); function setTokenHandler(address _marketHandlerAddr, address _interestModelAddr) external returns (bool); function setCoinHandler(address _marketHandlerAddr, address _interestModelAddr) external returns (bool); function getDepositTotalAmount() external view returns (uint256); function addDepositTotalAmount(uint256 amount) external returns (uint256); function subDepositTotalAmount(uint256 amount) external returns (uint256); function getBorrowTotalAmount() external view returns (uint256); function addBorrowTotalAmount(uint256 amount) external returns (uint256); function subBorrowTotalAmount(uint256 amount) external returns (uint256); function getUserIntraDepositAmount(address payable userAddr) external view returns (uint256); function addUserIntraDepositAmount(address payable userAddr, uint256 amount) external returns (uint256); function subUserIntraDepositAmount(address payable userAddr, uint256 amount) external returns (uint256); function getUserIntraBorrowAmount(address payable userAddr) external view returns (uint256); function addUserIntraBorrowAmount(address payable userAddr, uint256 amount) external returns (uint256); function subUserIntraBorrowAmount(address payable userAddr, uint256 amount) external returns (uint256); function addDepositAmount(address payable userAddr, uint256 amount) external returns (bool); function subDepositAmount(address payable userAddr, uint256 amount) external returns (bool); function addBorrowAmount(address payable userAddr, uint256 amount) external returns (bool); function subBorrowAmount(address payable userAddr, uint256 amount) external returns (bool); function getUserAmount(address payable userAddr) external view returns (uint256, uint256); function getHandlerAmount() external view returns (uint256, uint256); function getAmount(address payable userAddr) external view returns (uint256, uint256, uint256, uint256); function setAmount(address payable userAddr, uint256 depositTotalAmount, uint256 borrowTotalAmount, uint256 depositAmount, uint256 borrowAmount) external returns (uint256); function setBlocks(uint256 lastUpdatedBlock, uint256 inactiveActionDelta) external returns (bool); function getLastUpdatedBlock() external view returns (uint256); function setLastUpdatedBlock(uint256 _lastUpdatedBlock) external returns (bool); function getInactiveActionDelta() external view returns (uint256); function setInactiveActionDelta(uint256 inactiveActionDelta) external returns (bool); function syncActionEXR() external returns (bool); function getActionEXR() external view returns (uint256, uint256); function setActionEXR(uint256 actionDepositExRate, uint256 actionBorrowExRate) external returns (bool); function getGlobalDepositEXR() external view returns (uint256); function getGlobalBorrowEXR() external view returns (uint256); function setEXR(address payable userAddr, uint256 globalDepositEXR, uint256 globalBorrowEXR) external returns (bool); function getUserEXR(address payable userAddr) external view returns (uint256, uint256); function setUserEXR(address payable userAddr, uint256 depositEXR, uint256 borrowEXR) external returns (bool); function getGlobalEXR() external view returns (uint256, uint256); function getMarketHandlerAddr() external view returns (address); function setMarketHandlerAddr(address marketHandlerAddr) external returns (bool); function getInterestModelAddr() external view returns (address); function setInterestModelAddr(address interestModelAddr) external returns (bool); function getMinimumInterestRate() external view returns (uint256); function setMinimumInterestRate(uint256 _minimumInterestRate) external returns (bool); function getLiquiditySensitivity() external view returns (uint256); function setLiquiditySensitivity(uint256 _liquiditySensitivity) external returns (bool); function getLimit() external view returns (uint256, uint256); function getBorrowLimit() external view returns (uint256); function setBorrowLimit(uint256 _borrowLimit) external returns (bool); function getMarginCallLimit() external view returns (uint256); function setMarginCallLimit(uint256 _marginCallLimit) external returns (bool); function getLimitOfAction() external view returns (uint256); function setLimitOfAction(uint256 limitOfAction) external returns (bool); function getLiquidityLimit() external view returns (uint256); function setLiquidityLimit(uint256 liquidityLimit) external returns (bool); } // File: contracts/interfaces/marketManagerInterface.sol pragma solidity 0.6.12; interface marketManagerInterface { function setBreakerTable(address _target, bool _status) external returns (bool); function getCircuitBreaker() external view returns (bool); function setCircuitBreaker(bool _emergency) external returns (bool); function getTokenHandlerInfo(uint256 handlerID) external view returns (bool, address, string memory); function handlerRegister(uint256 handlerID, address tokenHandlerAddr) external returns (bool); function applyInterestHandlers(address payable userAddr, uint256 callerID, bool allFlag) external returns (uint256, uint256, uint256); function liquidationApplyInterestHandlers(address payable userAddr, uint256 callerID) external returns (uint256, uint256, uint256, uint256, uint256); function getTokenHandlerPrice(uint256 handlerID) external view returns (uint256); function getTokenHandlerBorrowLimit(uint256 handlerID) external view returns (uint256); function getTokenHandlerSupport(uint256 handlerID) external view returns (bool); function getTokenHandlersLength() external view returns (uint256); function setTokenHandlersLength(uint256 _tokenHandlerLength) external returns (bool); function getTokenHandlerID(uint256 index) external view returns (uint256); function getTokenHandlerMarginCallLimit(uint256 handlerID) external view returns (uint256); function getUserIntraHandlerAssetWithInterest(address payable userAddr, uint256 handlerID) external view returns (uint256, uint256); function getUserTotalIntraCreditAsset(address payable userAddr) external view returns (uint256, uint256); function getUserLimitIntraAsset(address payable userAddr) external view returns (uint256, uint256); function getUserCollateralizableAmount(address payable userAddr, uint256 handlerID) external view returns (uint256); function getUserExtraLiquidityAmount(address payable userAddr, uint256 handlerID) external view returns (uint256); function partialLiquidationUser(address payable delinquentBorrower, uint256 liquidateAmount, address payable liquidator, uint256 liquidateHandlerID, uint256 rewardHandlerID) external returns (uint256, uint256, uint256); function getMaxLiquidationReward(address payable delinquentBorrower, uint256 liquidateHandlerID, uint256 liquidateAmount, uint256 rewardHandlerID, uint256 rewardRatio) external view returns (uint256); function partialLiquidationUserReward(address payable delinquentBorrower, uint256 rewardAmount, address payable liquidator, uint256 handlerID) external returns (uint256); function setLiquidationManager(address liquidationManagerAddr) external returns (bool); function rewardClaimAll(address payable userAddr) external returns (bool); function updateRewardParams(address payable userAddr) external returns (bool); function interestUpdateReward() external returns (bool); function getGlobalRewardInfo() external view returns (uint256, uint256, uint256); function setOracleProxy(address oracleProxyAddr) external returns (bool); function rewardUpdateOfInAction(address payable userAddr, uint256 callerID) external returns (bool); function ownerRewardTransfer(uint256 _amount) external returns (bool); } // File: contracts/interfaces/interestModelInterface.sol pragma solidity 0.6.12; interface interestModelInterface { function getInterestAmount(address handlerDataStorageAddr, address payable userAddr, bool isView) external view returns (bool, uint256, uint256, bool, uint256, uint256); function viewInterestAmount(address handlerDataStorageAddr, address payable userAddr) external view returns (bool, uint256, uint256, bool, uint256, uint256); function getSIRandBIR(address handlerDataStorageAddr, uint256 depositTotalAmount, uint256 borrowTotalAmount) external view returns (uint256, uint256); } // File: contracts/interfaces/tokenInterface.sol pragma solidity 0.6.12; interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external ; function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external view returns (bool); function transferFrom(address from, address to, uint256 value) external ; } // File: contracts/interfaces/marketSIHandlerDataStorageInterface.sol pragma solidity 0.6.12; interface marketSIHandlerDataStorageInterface { function setCircuitBreaker(bool _emergency) external returns (bool); function updateRewardPerBlockStorage(uint256 _rewardPerBlock) external returns (bool); function getRewardInfo(address userAddr) external view returns (uint256, uint256, uint256, uint256, uint256, uint256); function getMarketRewardInfo() external view returns (uint256, uint256, uint256); function setMarketRewardInfo(uint256 _rewardLane, uint256 _rewardLaneUpdateAt, uint256 _rewardPerBlock) external returns (bool); function getUserRewardInfo(address userAddr) external view returns (uint256, uint256, uint256); function setUserRewardInfo(address userAddr, uint256 _rewardLane, uint256 _rewardLaneUpdateAt, uint256 _rewardAmount) external returns (bool); function getBetaRate() external view returns (uint256); function setBetaRate(uint256 _betaRate) external returns (bool); } // File: contracts/marketHandler/tokenSI.sol pragma solidity 0.6.12; /** * @title Bifi tokenSI Contract * @notice Service incentive logic * @author Bifi */ contract tokenSI is SIInterface { event CircuitBreaked(bool breaked, uint256 blockNumber, uint256 handlerID); address payable owner; uint256 handlerID; string tokenName; uint256 constant unifiedPoint = 10 ** 18; uint256 unifiedTokenDecimal; uint256 underlyingTokenDecimal; marketManagerInterface marketManager; interestModelInterface interestModelInstance; marketHandlerDataStorageInterface handlerDataStorage; marketSIHandlerDataStorageInterface SIHandlerDataStorage; IERC20 erc20Instance; struct MarketRewardInfo { uint256 rewardLane; uint256 rewardLaneUpdateAt; uint256 rewardPerBlock; } struct UserRewardInfo { uint256 rewardLane; uint256 rewardLaneUpdateAt; uint256 rewardAmount; } modifier onlyMarketManager { address msgSender = msg.sender; require((msgSender == address(marketManager)) || (msgSender == owner), "onlyMarketManager function"); _; } modifier onlyOwner { require(msg.sender == address(owner), "onlyOwner function"); _; } /** * @dev Transfer ownership * @param _owner the address of the new owner * @return true (TODO: validate results) */ function ownershipTransfer(address _owner) onlyOwner external returns (bool) { owner = address(uint160(_owner)); return true; } /** * @dev Set circuitBreak to freeze/unfreeze all handlers by owne * @param _emergency The status of the circuit breaker * @return true (TODO: validate results) */ function setCircuitBreakWithOwner(bool _emergency) onlyOwner external override returns (bool) { SIHandlerDataStorage.setCircuitBreaker(_emergency); emit CircuitBreaked(_emergency, block.number, handlerID); return true; } /** * @dev Set circuitBreak to freeze/unfreeze all handlers by marketManager * @param _emergency The status of the circuit breaker * @return true (TODO: validate results) */ function setCircuitBreaker(bool _emergency) onlyMarketManager external override returns (bool) { SIHandlerDataStorage.setCircuitBreaker(_emergency); emit CircuitBreaked(_emergency, block.number, handlerID); return true; } /** * @dev Update the amount of rewards per block * @param _rewardPerBlock The amount of the reward amount per block * @return true (TODO: validate results) */ function updateRewardPerBlockLogic(uint256 _rewardPerBlock) onlyMarketManager external override returns (bool) { return SIHandlerDataStorage.updateRewardPerBlockStorage(_rewardPerBlock); } /** * @dev Update the reward lane (the acculumated sum of the reward unit per block) of the market and user * @param userAddr The address of user * @return Whether or not this process has succeeded */ function updateRewardLane(address payable userAddr) external override returns (bool) { MarketRewardInfo memory market; UserRewardInfo memory user; marketSIHandlerDataStorageInterface _SIHandlerDataStorage = SIHandlerDataStorage; (market.rewardLane, market.rewardLaneUpdateAt, market.rewardPerBlock, user.rewardLane, user.rewardLaneUpdateAt, user.rewardAmount) = _SIHandlerDataStorage.getRewardInfo(userAddr); uint256 currentBlockNum = block.number; uint256 depositTotalAmount; uint256 borrowTotalAmount; uint256 depositUserAmount; uint256 borrowUserAmount; (depositTotalAmount, borrowTotalAmount, depositUserAmount, borrowUserAmount) = handlerDataStorage.getAmount(userAddr); /* Unless the reward lane of the market is updated at the current block */ if (market.rewardLaneUpdateAt < currentBlockNum) { uint256 _delta = sub(currentBlockNum, market.rewardLaneUpdateAt); uint256 betaRateBaseTotalAmount = _calcBetaBaseAmount(_SIHandlerDataStorage.getBetaRate(), depositTotalAmount, borrowTotalAmount); if (betaRateBaseTotalAmount != 0) { /* update the reward lane */ market.rewardLane = add(market.rewardLane, _calcRewardLaneDistance(_delta, market.rewardPerBlock, betaRateBaseTotalAmount)); } _SIHandlerDataStorage.setMarketRewardInfo(market.rewardLane, currentBlockNum, market.rewardPerBlock); } /* Unless the reward lane of the user is updated at the current block */ if (user.rewardLaneUpdateAt < currentBlockNum) { uint256 betaRateBaseUserAmount = _calcBetaBaseAmount(_SIHandlerDataStorage.getBetaRate(), depositUserAmount, borrowUserAmount); if (betaRateBaseUserAmount != 0) { user.rewardAmount = add(user.rewardAmount, unifiedMul(betaRateBaseUserAmount, sub(market.rewardLane, user.rewardLane))); } _SIHandlerDataStorage.setUserRewardInfo(userAddr, market.rewardLane, currentBlockNum, user.rewardAmount); return true; } return false; } /** * @dev Calculates the reward lane distance (for delta blocks) based on the given parameters. * @param _delta The blockNumber difference * @param _rewardPerBlock The amount of reward per block * @param _total The total amount of betaRate * @return The reward lane distance */ function _calcRewardLaneDistance(uint256 _delta, uint256 _rewardPerBlock, uint256 _total) internal pure returns (uint256) { return mul(_delta, unifiedDiv(_rewardPerBlock, _total)); } /** * @dev Get the total amount of betaRate * @return The total amount of betaRate */ function getBetaRateBaseTotalAmount() external view override returns (uint256) { return _getBetaRateBaseTotalAmount(); } /** * @dev Get the total amount of betaRate * @return The total amount of betaRate */ function _getBetaRateBaseTotalAmount() internal view returns (uint256) { uint256 depositTotalAmount; uint256 borrowTotalAmount; (depositTotalAmount, borrowTotalAmount) = handlerDataStorage.getHandlerAmount(); return _calcBetaBaseAmount(SIHandlerDataStorage.getBetaRate(), depositTotalAmount, borrowTotalAmount); } /** * @dev Calculate the rewards given to the user by using the beta score (external). * betaRateBaseAmount = (depositAmount * betaRate) + ((1 - betaRate) * borrowAmount) * @param userAddr The address of user * @return The beta score of the user */ function getBetaRateBaseUserAmount(address payable userAddr) external view override returns (uint256) { return _getBetaRateBaseUserAmount(userAddr); } /** * @dev Calculate the rewards given to the user by using the beta score (internal) * betaRateBaseAmount = (depositAmount * betaRate) + ((1 - betaRate) * borrowAmount) * @param userAddr The address of user * @return The beta score of the user */ function _getBetaRateBaseUserAmount(address payable userAddr) internal view returns (uint256) { uint256 depositUserAmount; uint256 borrowUserAmount; (depositUserAmount, borrowUserAmount) = handlerDataStorage.getUserAmount(userAddr); return _calcBetaBaseAmount(SIHandlerDataStorage.getBetaRate(), depositUserAmount, borrowUserAmount); } function _calcBetaBaseAmount(uint256 _beta, uint256 _depositAmount, uint256 _borrowAmount) internal pure returns (uint256) { return add(unifiedMul(_depositAmount, _beta), unifiedMul(_borrowAmount, sub(unifiedPoint, _beta))); } /** * @dev Claim rewards for the user (external) * @param userAddr The address of user * @return The amount of user reward */ function claimRewardAmountUser(address payable userAddr) onlyMarketManager external returns (uint256) { return _claimRewardAmountUser(userAddr); } /** * @dev Claim rewards for the user (internal) * @param userAddr The address of user * @return The amount of user reward */ function _claimRewardAmountUser(address payable userAddr) internal returns (uint256) { UserRewardInfo memory user; uint256 currentBlockNum = block.number; (user.rewardLane, user.rewardLaneUpdateAt, user.rewardAmount) = SIHandlerDataStorage.getUserRewardInfo(userAddr); /* reset the user reward */ SIHandlerDataStorage.setUserRewardInfo(userAddr, user.rewardLane, currentBlockNum, 0); return user.rewardAmount; } /** * @dev Get the reward parameters of the market * @return (rewardLane, rewardLaneUpdateAt, rewardPerBlock) */ function getMarketRewardInfo() external view override returns (uint256, uint256, uint256) { return SIHandlerDataStorage.getMarketRewardInfo(); } /** * @dev Get reward parameters for the user * @return (uint256,uint256,uint256) (rewardLane, rewardLaneUpdateAt, rewardAmount) */ function getUserRewardInfo(address payable userAddr) external view override returns (uint256, uint256, uint256) { return SIHandlerDataStorage.getUserRewardInfo(userAddr); } /** * @dev Get the rate of beta (beta-score) * @return The rate of beta (beta-score) */ function getBetaRate() external view returns (uint256) { return SIHandlerDataStorage.getBetaRate(); } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "add overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return _sub(a, b, "sub overflow"); } function mul(uint256 a, uint256 b) internal pure returns (uint256) { return _mul(a, b); } function div(uint256 a, uint256 b) internal pure returns (uint256) { return _div(a, b, "div by zero"); } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return _mod(a, b, "mod by zero"); } function _sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } function _mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require((c / a) == b, "mul overflow"); return c; } function _div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } function _mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } function unifiedDiv(uint256 a, uint256 b) internal pure returns (uint256) { return _div(_mul(a, unifiedPoint), b, "unified div by zero"); } function unifiedMul(uint256 a, uint256 b) internal pure returns (uint256) { return _div(_mul(a, b), unifiedPoint, "unified mul by zero"); } function signedAdd(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require(((b >= 0) && (c >= a)) || ((b < 0) && (c < a)), "SignedSafeMath: addition overflow"); return c; } function signedSub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require(((b >= 0) && (c <= a)) || ((b < 0) && (c > a)), "SignedSafeMath: subtraction overflow"); return c; } } // File: contracts/truffleKit/LinkSi.sol contract LinkSI is tokenSI { constructor() tokenSI() public {} }
Set circuitBreak to freeze/unfreeze all handlers by marketManager _emergency The status of the circuit breaker return true (TODO: validate results)/
function setCircuitBreaker(bool _emergency) onlyMarketManager external override returns (bool) { SIHandlerDataStorage.setCircuitBreaker(_emergency); emit CircuitBreaked(_emergency, block.number, handlerID); return true; }
5,937,291
./full_match/80001/0x3A907E57Dca4a585b5cFE13Cbb438De03231a814/sources/contracts/ClampGovernance.sol
queue the proposal in the timelock contract for community validators to check if proposal is valid queue function can be called by anyone
function queue(uint _proposalId) external { require(_proposalId == proposalCount, "CLAMP: INVALID PROPOSAL ID"); require(block.number >= proposals[_proposalId].endBlock, "CLAMP: VOTING NOT ENDED YET!"); ProposalState proposersLatestProposalState = state(_proposalId); require(proposersLatestProposalState == ProposalState.Succeeded, "CLAMP: PROPOSAL NOT SUCCEEDED"); Proposal memory proposalDetails = proposals[_proposalId]; uint eta = block.timestamp.add(timelockContract.delay()); timelockContract.queueTransaction(proposalDetails.targets, proposalDetails.signatures, proposalDetails.calldatas, eta); proposals[_proposalId].eta = eta; emit ProposalQueued(_proposalId, eta); }
9,491,925
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/drafts/IERC20Permit.sol"; import "../external/ERC721PresetMinterPauserAutoId.sol"; import "../interfaces/IERC20withDec.sol"; import "../interfaces/ISeniorPool.sol"; import "../protocol/core/GoldfinchConfig.sol"; import "../protocol/core/ConfigHelper.sol"; import "../protocol/core/BaseUpgradeablePausable.sol"; import "../library/StakingRewardsVesting.sol"; contract StakingRewards is ERC721PresetMinterPauserAutoIdUpgradeSafe, ReentrancyGuardUpgradeSafe { using SafeMath for uint256; using SafeERC20 for IERC20withDec; using ConfigHelper for GoldfinchConfig; using StakingRewardsVesting for StakingRewardsVesting.Rewards; enum LockupPeriod { SixMonths, TwelveMonths, TwentyFourMonths } struct StakedPosition { // @notice Staked amount denominated in `stakingToken().decimals()` uint256 amount; // @notice Struct describing rewards owed with vesting StakingRewardsVesting.Rewards rewards; // @notice Multiplier applied to staked amount when locking up position uint256 leverageMultiplier; // @notice Time in seconds after which position can be unstaked uint256 lockedUntil; } /* ========== EVENTS =================== */ event RewardsParametersUpdated( address indexed who, uint256 targetCapacity, uint256 minRate, uint256 maxRate, uint256 minRateAtPercent, uint256 maxRateAtPercent ); event TargetCapacityUpdated(address indexed who, uint256 targetCapacity); event VestingScheduleUpdated(address indexed who, uint256 vestingLength); event MinRateUpdated(address indexed who, uint256 minRate); event MaxRateUpdated(address indexed who, uint256 maxRate); event MinRateAtPercentUpdated(address indexed who, uint256 minRateAtPercent); event MaxRateAtPercentUpdated(address indexed who, uint256 maxRateAtPercent); event LeverageMultiplierUpdated(address indexed who, LockupPeriod lockupPeriod, uint256 leverageMultiplier); /* ========== STATE VARIABLES ========== */ uint256 private constant MULTIPLIER_DECIMALS = 1e18; bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE"); GoldfinchConfig public config; /// @notice The block timestamp when rewards were last checkpointed uint256 public lastUpdateTime; /// @notice Accumulated rewards per token at the last checkpoint uint256 public accumulatedRewardsPerToken; /// @notice Total rewards available for disbursement at the last checkpoint, denominated in `rewardsToken()` uint256 public rewardsAvailable; /// @notice StakedPosition tokenId => accumulatedRewardsPerToken at the position's last checkpoint mapping(uint256 => uint256) public positionToAccumulatedRewardsPerToken; /// @notice Desired supply of staked tokens. The reward rate adjusts in a range /// around this value to incentivize staking or unstaking to maintain it. uint256 public targetCapacity; /// @notice The minimum total disbursed rewards per second, denominated in `rewardsToken()` uint256 public minRate; /// @notice The maximum total disbursed rewards per second, denominated in `rewardsToken()` uint256 public maxRate; /// @notice The percent of `targetCapacity` at which the reward rate reaches `maxRate`. /// Represented with `MULTIPLIER_DECIMALS`. uint256 public maxRateAtPercent; /// @notice The percent of `targetCapacity` at which the reward rate reaches `minRate`. /// Represented with `MULTIPLIER_DECIMALS`. uint256 public minRateAtPercent; /// @notice The duration in seconds over which rewards vest uint256 public vestingLength; /// @dev Supply of staked tokens, excluding leverage due to lock-up boosting, denominated in /// `stakingToken().decimals()` uint256 public totalStakedSupply; /// @dev Supply of staked tokens, including leverage due to lock-up boosting, denominated in /// `stakingToken().decimals()` uint256 private totalLeveragedStakedSupply; /// @dev A mapping from lockup periods to leverage multipliers used to boost rewards. /// See `stakeWithLockup`. mapping(LockupPeriod => uint256) private leverageMultipliers; /// @dev NFT tokenId => staked position mapping(uint256 => StakedPosition) public positions; // solhint-disable-next-line func-name-mixedcase function __initialize__(address owner, GoldfinchConfig _config) external initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721_init_unchained("Goldfinch V2 LP Staking Tokens", "GFI-V2-LPS"); __ERC721Pausable_init_unchained(); __AccessControl_init_unchained(); __Pausable_init_unchained(); __ReentrancyGuard_init_unchained(); _setupRole(OWNER_ROLE, owner); _setupRole(PAUSER_ROLE, owner); _setRoleAdmin(PAUSER_ROLE, OWNER_ROLE); _setRoleAdmin(OWNER_ROLE, OWNER_ROLE); config = _config; vestingLength = 365 days; // Set defaults for leverage multipliers (no boosting) leverageMultipliers[LockupPeriod.SixMonths] = MULTIPLIER_DECIMALS; // 1x leverageMultipliers[LockupPeriod.TwelveMonths] = MULTIPLIER_DECIMALS; // 1x leverageMultipliers[LockupPeriod.TwentyFourMonths] = MULTIPLIER_DECIMALS; // 1x } /* ========== VIEWS ========== */ /// @notice Returns the staked balance of a given position token /// @param tokenId A staking position token ID /// @return Amount of staked tokens denominated in `stakingToken().decimals()` function stakedBalanceOf(uint256 tokenId) external view returns (uint256) { return positions[tokenId].amount; } /// @notice The address of the token being disbursed as rewards function rewardsToken() public view returns (IERC20withDec) { return config.getGFI(); } /// @notice The address of the token that can be staked function stakingToken() public view returns (IERC20withDec) { return config.getFidu(); } /// @notice The additional rewards earned per token, between the provided time and the last /// time rewards were checkpointed, given the prevailing `rewardRate()`. This amount is limited /// by the amount of rewards that are available for distribution; if there aren't enough /// rewards in the balance of this contract, then we shouldn't be giving them out. /// @return Amount of rewards denominated in `rewardsToken().decimals()`. function additionalRewardsPerTokenSinceLastUpdate(uint256 time) internal view returns (uint256) { require(time >= lastUpdateTime, "Invalid end time for range"); if (totalLeveragedStakedSupply == 0) { return 0; } uint256 rewardsSinceLastUpdate = Math.min(time.sub(lastUpdateTime).mul(rewardRate()), rewardsAvailable); uint256 additionalRewardsPerToken = rewardsSinceLastUpdate.mul(stakingTokenMantissa()).div( totalLeveragedStakedSupply ); // Prevent perverse, infinite-mint scenario where totalLeveragedStakedSupply is a fraction of a token. // Since it's used as the denominator, this could make additionalRewardPerToken larger than the total number // of tokens that should have been disbursed in the elapsed time. The attacker would need to find // a way to reduce totalLeveragedStakedSupply while maintaining a staked position of >= 1. // See: https://twitter.com/Mudit__Gupta/status/1409463917290557440 if (additionalRewardsPerToken > rewardsSinceLastUpdate) { return 0; } return additionalRewardsPerToken; } /// @notice Returns accumulated rewards per token up to the current block timestamp /// @return Amount of rewards denominated in `rewardsToken().decimals()` function rewardPerToken() public view returns (uint256) { uint256 additionalRewardsPerToken = additionalRewardsPerTokenSinceLastUpdate(block.timestamp); return accumulatedRewardsPerToken.add(additionalRewardsPerToken); } /// @notice Returns rewards earned by a given position token from its last checkpoint up to the /// current block timestamp. /// @param tokenId A staking position token ID /// @return Amount of rewards denominated in `rewardsToken().decimals()` function earnedSinceLastCheckpoint(uint256 tokenId) public view returns (uint256) { StakedPosition storage position = positions[tokenId]; uint256 leveredAmount = positionToLeveredAmount(position); return leveredAmount.mul(rewardPerToken().sub(positionToAccumulatedRewardsPerToken[tokenId])).div( stakingTokenMantissa() ); } /// @notice Returns the rewards claimable by a given position token at the most recent checkpoint, taking into /// account vesting schedule. /// @return rewards Amount of rewards denominated in `rewardsToken()` function claimableRewards(uint256 tokenId) public view returns (uint256 rewards) { return positions[tokenId].rewards.claimable(); } /// @notice Returns the rewards that will have vested for some position with the given params. /// @return rewards Amount of rewards denominated in `rewardsToken()` function totalVestedAt( uint256 start, uint256 end, uint256 time, uint256 grantedAmount ) external pure returns (uint256 rewards) { return StakingRewardsVesting.totalVestedAt(start, end, time, grantedAmount); } /// @notice Number of rewards, in `rewardsToken().decimals()`, to disburse each second function rewardRate() internal view returns (uint256) { // The reward rate can be thought of as a piece-wise function: // // let intervalStart = (maxRateAtPercent * targetCapacity), // intervalEnd = (minRateAtPercent * targetCapacity), // x = totalStakedSupply // in // if x < intervalStart // y = maxRate // if x > intervalEnd // y = minRate // else // y = maxRate - (maxRate - minRate) * (x - intervalStart) / (intervalEnd - intervalStart) // // See an example here: // solhint-disable-next-line max-line-length // https://www.wolframalpha.com/input/?i=Piecewise%5B%7B%7B1000%2C+x+%3C+50%7D%2C+%7B100%2C+x+%3E+300%7D%2C+%7B1000+-+%281000+-+100%29+*+%28x+-+50%29+%2F+%28300+-+50%29+%2C+50+%3C+x+%3C+300%7D%7D%5D // // In that example: // maxRateAtPercent = 0.5, minRateAtPercent = 3, targetCapacity = 100, maxRate = 1000, minRate = 100 uint256 intervalStart = targetCapacity.mul(maxRateAtPercent).div(MULTIPLIER_DECIMALS); uint256 intervalEnd = targetCapacity.mul(minRateAtPercent).div(MULTIPLIER_DECIMALS); uint256 x = totalStakedSupply; // Subsequent computation would overflow if (intervalEnd <= intervalStart) { return 0; } if (x < intervalStart) { return maxRate; } if (x > intervalEnd) { return minRate; } return maxRate.sub(maxRate.sub(minRate).mul(x.sub(intervalStart)).div(intervalEnd.sub(intervalStart))); } function positionToLeveredAmount(StakedPosition storage position) internal view returns (uint256) { return toLeveredAmount(position.amount, position.leverageMultiplier); } function toLeveredAmount(uint256 amount, uint256 leverageMultiplier) internal pure returns (uint256) { return amount.mul(leverageMultiplier).div(MULTIPLIER_DECIMALS); } function stakingTokenMantissa() internal view returns (uint256) { return uint256(10)**stakingToken().decimals(); } /// @notice The amount of rewards currently being earned per token per second. This amount takes into /// account how many rewards are actually available for disbursal -- unlike `rewardRate()` which does not. /// This function is intended for public consumption, to know the rate at which rewards are being /// earned, and not as an input to the mutative calculations in this contract. /// @return Amount of rewards denominated in `rewardsToken().decimals()`. function currentEarnRatePerToken() public view returns (uint256) { uint256 time = block.timestamp == lastUpdateTime ? block.timestamp + 1 : block.timestamp; uint256 elapsed = time.sub(lastUpdateTime); return additionalRewardsPerTokenSinceLastUpdate(time).div(elapsed); } /// @notice The amount of rewards currently being earned per second, for a given position. This function /// is intended for public consumption, to know the rate at which rewards are being earned /// for a given position, and not as an input to the mutative calculations in this contract. /// @return Amount of rewards denominated in `rewardsToken().decimals()`. function positionCurrentEarnRate(uint256 tokenId) external view returns (uint256) { StakedPosition storage position = positions[tokenId]; uint256 leveredAmount = positionToLeveredAmount(position); return currentEarnRatePerToken().mul(leveredAmount).div(stakingTokenMantissa()); } /* ========== MUTATIVE FUNCTIONS ========== */ /// @notice Stake `stakingToken()` to earn rewards. When you call this function, you'll receive an /// an NFT representing your staked position. You can present your NFT to `getReward` or `unstake` /// to claim rewards or unstake your tokens respectively. Rewards vest over a schedule. /// @dev This function checkpoints rewards. /// @param amount The amount of `stakingToken()` to stake function stake(uint256 amount) external nonReentrant whenNotPaused updateReward(0) { _stakeWithLockup(msg.sender, msg.sender, amount, 0, MULTIPLIER_DECIMALS); } /// @notice Stake `stakingToken()` and lock your position for a period of time to boost your rewards. /// When you call this function, you'll receive an an NFT representing your staked position. /// You can present your NFT to `getReward` or `unstake` to claim rewards or unstake your tokens /// respectively. Rewards vest over a schedule. /// /// A locked position's rewards are boosted using a multiplier on the staked balance. For example, /// if I lock 100 tokens for a 2x multiplier, my rewards will be calculated as if I staked 200 tokens. /// This mechanism is similar to curve.fi's CRV-boosting vote-locking. Locked positions cannot be /// unstaked until after the position's lockedUntil timestamp. /// @dev This function checkpoints rewards. /// @param amount The amount of `stakingToken()` to stake /// @param lockupPeriod The period over which to lock staked tokens function stakeWithLockup(uint256 amount, LockupPeriod lockupPeriod) external nonReentrant whenNotPaused updateReward(0) { uint256 lockDuration = lockupPeriodToDuration(lockupPeriod); uint256 leverageMultiplier = getLeverageMultiplier(lockupPeriod); uint256 lockedUntil = block.timestamp.add(lockDuration); _stakeWithLockup(msg.sender, msg.sender, amount, lockedUntil, leverageMultiplier); } /// @notice Deposit to SeniorPool and stake your shares in the same transaction. /// @param usdcAmount The amount of USDC to deposit into the senior pool. All shares from deposit /// will be staked. function depositAndStake(uint256 usdcAmount) public nonReentrant whenNotPaused updateReward(0) { uint256 fiduAmount = depositToSeniorPool(usdcAmount); uint256 lockedUntil = 0; uint256 tokenId = _stakeWithLockup(address(this), msg.sender, fiduAmount, lockedUntil, MULTIPLIER_DECIMALS); emit DepositedAndStaked(msg.sender, usdcAmount, tokenId, fiduAmount, lockedUntil, MULTIPLIER_DECIMALS); } function depositToSeniorPool(uint256 usdcAmount) internal returns (uint256 fiduAmount) { require(config.getGo().goSeniorPool(msg.sender), "This address has not been go-listed"); IERC20withDec usdc = config.getUSDC(); usdc.safeTransferFrom(msg.sender, address(this), usdcAmount); ISeniorPool seniorPool = config.getSeniorPool(); usdc.safeIncreaseAllowance(address(seniorPool), usdcAmount); return seniorPool.deposit(usdcAmount); } /// @notice Identical to `depositAndStake`, except it allows for a signature to be passed that permits /// this contract to move funds on behalf of the user. /// @param usdcAmount The amount of USDC to deposit /// @param v secp256k1 signature component /// @param r secp256k1 signature component /// @param s secp256k1 signature component function depositWithPermitAndStake( uint256 usdcAmount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public { IERC20Permit(config.usdcAddress()).permit(msg.sender, address(this), usdcAmount, deadline, v, r, s); depositAndStake(usdcAmount); } /// @notice Deposit to the `SeniorPool` and stake your shares with a lock-up in the same transaction. /// @param usdcAmount The amount of USDC to deposit into the senior pool. All shares from deposit /// will be staked. /// @param lockupPeriod The period over which to lock staked tokens function depositAndStakeWithLockup(uint256 usdcAmount, LockupPeriod lockupPeriod) public nonReentrant whenNotPaused updateReward(0) { uint256 fiduAmount = depositToSeniorPool(usdcAmount); uint256 lockDuration = lockupPeriodToDuration(lockupPeriod); uint256 leverageMultiplier = getLeverageMultiplier(lockupPeriod); uint256 lockedUntil = block.timestamp.add(lockDuration); uint256 tokenId = _stakeWithLockup(address(this), msg.sender, fiduAmount, lockedUntil, leverageMultiplier); emit DepositedAndStaked(msg.sender, usdcAmount, tokenId, fiduAmount, lockedUntil, leverageMultiplier); } function lockupPeriodToDuration(LockupPeriod lockupPeriod) internal pure returns (uint256 lockDuration) { if (lockupPeriod == LockupPeriod.SixMonths) { return 365 days / 2; } else if (lockupPeriod == LockupPeriod.TwelveMonths) { return 365 days; } else if (lockupPeriod == LockupPeriod.TwentyFourMonths) { return 365 days * 2; } else { revert("unsupported LockupPeriod"); } } /// @notice Get the leverage multiplier used to boost rewards for a given lockup period. /// See `stakeWithLockup`. The leverage multiplier is denominated in `MULTIPLIER_DECIMALS`. function getLeverageMultiplier(LockupPeriod lockupPeriod) public view returns (uint256) { uint256 leverageMultiplier = leverageMultipliers[lockupPeriod]; require(leverageMultiplier > 0, "unsupported LockupPeriod"); return leverageMultiplier; } /// @notice Identical to `depositAndStakeWithLockup`, except it allows for a signature to be passed that permits /// this contract to move funds on behalf of the user. /// @param usdcAmount The amount of USDC to deposit /// @param lockupPeriod The period over which to lock staked tokens /// @param v secp256k1 signature component /// @param r secp256k1 signature component /// @param s secp256k1 signature component function depositWithPermitAndStakeWithLockup( uint256 usdcAmount, LockupPeriod lockupPeriod, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public { IERC20Permit(config.usdcAddress()).permit(msg.sender, address(this), usdcAmount, deadline, v, r, s); depositAndStakeWithLockup(usdcAmount, lockupPeriod); } function _stakeWithLockup( address staker, address nftRecipient, uint256 amount, uint256 lockedUntil, uint256 leverageMultiplier ) internal returns (uint256 tokenId) { require(amount > 0, "Cannot stake 0"); _tokenIdTracker.increment(); tokenId = _tokenIdTracker.current(); // Ensure we snapshot accumulatedRewardsPerToken for tokenId after it is available // We do this before setting the position, because we don't want `earned` to (incorrectly) account for // position.amount yet. This is equivalent to using the updateReward(msg.sender) modifier in the original // synthetix contract, where the modifier is called before any staking balance for that address is recorded _updateReward(tokenId); positions[tokenId] = StakedPosition({ amount: amount, rewards: StakingRewardsVesting.Rewards({ totalUnvested: 0, totalVested: 0, totalPreviouslyVested: 0, totalClaimed: 0, startTime: block.timestamp, endTime: block.timestamp.add(vestingLength) }), leverageMultiplier: leverageMultiplier, lockedUntil: lockedUntil }); _mint(nftRecipient, tokenId); uint256 leveredAmount = positionToLeveredAmount(positions[tokenId]); totalLeveragedStakedSupply = totalLeveragedStakedSupply.add(leveredAmount); totalStakedSupply = totalStakedSupply.add(amount); // Staker is address(this) when using depositAndStake or other convenience functions if (staker != address(this)) { stakingToken().safeTransferFrom(staker, address(this), amount); } emit Staked(nftRecipient, tokenId, amount, lockedUntil, leverageMultiplier); return tokenId; } /// @notice Unstake an amount of `stakingToken()` associated with a given position and transfer to msg.sender. /// Unvested rewards will be forfeited, but remaining staked amount will continue to accrue rewards. /// Positions that are still locked cannot be unstaked until the position's lockedUntil time has passed. /// @dev This function checkpoints rewards /// @param tokenId A staking position token ID /// @param amount Amount of `stakingToken()` to be unstaked from the position function unstake(uint256 tokenId, uint256 amount) public nonReentrant whenNotPaused updateReward(tokenId) { _unstake(tokenId, amount); stakingToken().safeTransfer(msg.sender, amount); } function unstakeAndWithdraw(uint256 tokenId, uint256 usdcAmount) public nonReentrant whenNotPaused { (uint256 usdcReceivedAmount, uint256 fiduAmount) = _unstakeAndWithdraw(tokenId, usdcAmount); emit UnstakedAndWithdrew(msg.sender, usdcReceivedAmount, tokenId, fiduAmount); } function _unstakeAndWithdraw(uint256 tokenId, uint256 usdcAmount) internal updateReward(tokenId) returns (uint256 usdcAmountReceived, uint256 fiduUsed) { require(config.getGo().goSeniorPool(msg.sender), "This address has not been go-listed"); ISeniorPool seniorPool = config.getSeniorPool(); IFidu fidu = config.getFidu(); uint256 fiduBalanceBefore = fidu.balanceOf(address(this)); usdcAmountReceived = seniorPool.withdraw(usdcAmount); fiduUsed = fiduBalanceBefore.sub(fidu.balanceOf(address(this))); _unstake(tokenId, fiduUsed); config.getUSDC().safeTransfer(msg.sender, usdcAmountReceived); return (usdcAmountReceived, fiduUsed); } function unstakeAndWithdrawMultiple(uint256[] calldata tokenIds, uint256[] calldata usdcAmounts) public nonReentrant whenNotPaused { require(tokenIds.length == usdcAmounts.length, "tokenIds and usdcAmounts must be the same length"); uint256 usdcReceivedAmountTotal = 0; uint256[] memory fiduAmounts = new uint256[](usdcAmounts.length); for (uint256 i = 0; i < usdcAmounts.length; i++) { (uint256 usdcReceivedAmount, uint256 fiduAmount) = _unstakeAndWithdraw(tokenIds[i], usdcAmounts[i]); usdcReceivedAmountTotal = usdcReceivedAmountTotal.add(usdcReceivedAmount); fiduAmounts[i] = fiduAmount; } emit UnstakedAndWithdrewMultiple(msg.sender, usdcReceivedAmountTotal, tokenIds, fiduAmounts); } function unstakeAndWithdrawInFidu(uint256 tokenId, uint256 fiduAmount) public nonReentrant whenNotPaused { uint256 usdcReceivedAmount = _unstakeAndWithdrawInFidu(tokenId, fiduAmount); emit UnstakedAndWithdrew(msg.sender, usdcReceivedAmount, tokenId, fiduAmount); } function _unstakeAndWithdrawInFidu(uint256 tokenId, uint256 fiduAmount) internal updateReward(tokenId) returns (uint256 usdcReceivedAmount) { usdcReceivedAmount = config.getSeniorPool().withdrawInFidu(fiduAmount); _unstake(tokenId, fiduAmount); config.getUSDC().safeTransfer(msg.sender, usdcReceivedAmount); return usdcReceivedAmount; } function unstakeAndWithdrawMultipleInFidu(uint256[] calldata tokenIds, uint256[] calldata fiduAmounts) public nonReentrant whenNotPaused { require(tokenIds.length == fiduAmounts.length, "tokenIds and usdcAmounts must be the same length"); uint256 usdcReceivedAmountTotal = 0; for (uint256 i = 0; i < fiduAmounts.length; i++) { uint256 usdcReceivedAmount = _unstakeAndWithdrawInFidu(tokenIds[i], fiduAmounts[i]); usdcReceivedAmountTotal = usdcReceivedAmountTotal.add(usdcReceivedAmount); } emit UnstakedAndWithdrewMultiple(msg.sender, usdcReceivedAmountTotal, tokenIds, fiduAmounts); } function _unstake(uint256 tokenId, uint256 amount) internal { require(ownerOf(tokenId) == msg.sender, "access denied"); require(amount > 0, "Cannot unstake 0"); StakedPosition storage position = positions[tokenId]; uint256 prevAmount = position.amount; require(amount <= prevAmount, "cannot unstake more than staked balance"); require(block.timestamp >= position.lockedUntil, "staked funds are locked"); // By this point, leverageMultiplier should always be 1x due to the reset logic in updateReward. // But we subtract leveredAmount from totalLeveragedStakedSupply anyway, since that is technically correct. uint256 leveredAmount = toLeveredAmount(amount, position.leverageMultiplier); totalLeveragedStakedSupply = totalLeveragedStakedSupply.sub(leveredAmount); totalStakedSupply = totalStakedSupply.sub(amount); position.amount = prevAmount.sub(amount); // Slash unvested rewards uint256 slashingPercentage = amount.mul(StakingRewardsVesting.PERCENTAGE_DECIMALS).div(prevAmount); position.rewards.slash(slashingPercentage); emit Unstaked(msg.sender, tokenId, amount); } /// @notice "Kick" a user's reward multiplier. If they are past their lock-up period, their reward /// multipler will be reset to 1x. /// @dev This will also checkpoint their rewards up to the current time. // solhint-disable-next-line no-empty-blocks function kick(uint256 tokenId) public nonReentrant whenNotPaused updateReward(tokenId) {} /// @notice Claim rewards for a given staked position /// @param tokenId A staking position token ID function getReward(uint256 tokenId) public nonReentrant whenNotPaused updateReward(tokenId) { require(ownerOf(tokenId) == msg.sender, "access denied"); uint256 reward = claimableRewards(tokenId); if (reward > 0) { positions[tokenId].rewards.claim(reward); rewardsToken().safeTransfer(msg.sender, reward); emit RewardPaid(msg.sender, tokenId, reward); } } /// @notice Unstake the position's full amount and claim all rewards /// @param tokenId A staking position token ID function exit(uint256 tokenId) external { unstake(tokenId, positions[tokenId].amount); getReward(tokenId); } function exitAndWithdraw(uint256 tokenId) external { unstakeAndWithdrawInFidu(tokenId, positions[tokenId].amount); getReward(tokenId); } /* ========== RESTRICTED FUNCTIONS ========== */ /// @notice Transfer rewards from msg.sender, to be used for reward distribution function loadRewards(uint256 rewards) public onlyAdmin updateReward(0) { rewardsToken().safeTransferFrom(msg.sender, address(this), rewards); rewardsAvailable = rewardsAvailable.add(rewards); emit RewardAdded(rewards); } function setRewardsParameters( uint256 _targetCapacity, uint256 _minRate, uint256 _maxRate, uint256 _minRateAtPercent, uint256 _maxRateAtPercent ) public onlyAdmin updateReward(0) { require(_maxRate >= _minRate, "maxRate must be >= then minRate"); require(_maxRateAtPercent <= _minRateAtPercent, "maxRateAtPercent must be <= minRateAtPercent"); targetCapacity = _targetCapacity; minRate = _minRate; maxRate = _maxRate; minRateAtPercent = _minRateAtPercent; maxRateAtPercent = _maxRateAtPercent; emit RewardsParametersUpdated(msg.sender, targetCapacity, minRate, maxRate, minRateAtPercent, maxRateAtPercent); } function setLeverageMultiplier(LockupPeriod lockupPeriod, uint256 leverageMultiplier) public onlyAdmin updateReward(0) { leverageMultipliers[lockupPeriod] = leverageMultiplier; emit LeverageMultiplierUpdated(msg.sender, lockupPeriod, leverageMultiplier); } function setVestingSchedule(uint256 _vestingLength) public onlyAdmin updateReward(0) { vestingLength = _vestingLength; emit VestingScheduleUpdated(msg.sender, vestingLength); } function updateGoldfinchConfig() external onlyAdmin { config = GoldfinchConfig(config.configAddress()); emit GoldfinchConfigUpdated(_msgSender(), address(config)); } /* ========== MODIFIERS ========== */ modifier updateReward(uint256 tokenId) { _updateReward(tokenId); _; } function _updateReward(uint256 tokenId) internal { uint256 prevAccumulatedRewardsPerToken = accumulatedRewardsPerToken; accumulatedRewardsPerToken = rewardPerToken(); uint256 rewardsJustDistributed = totalLeveragedStakedSupply .mul(accumulatedRewardsPerToken.sub(prevAccumulatedRewardsPerToken)) .div(stakingTokenMantissa()); rewardsAvailable = rewardsAvailable.sub(rewardsJustDistributed); lastUpdateTime = block.timestamp; if (tokenId != 0) { uint256 additionalRewards = earnedSinceLastCheckpoint(tokenId); StakedPosition storage position = positions[tokenId]; StakingRewardsVesting.Rewards storage rewards = position.rewards; rewards.totalUnvested = rewards.totalUnvested.add(additionalRewards); rewards.checkpoint(); positionToAccumulatedRewardsPerToken[tokenId] = accumulatedRewardsPerToken; // If position is unlocked, reset its leverageMultiplier back to 1x uint256 lockedUntil = position.lockedUntil; uint256 leverageMultiplier = position.leverageMultiplier; uint256 amount = position.amount; if (lockedUntil > 0 && block.timestamp >= lockedUntil && leverageMultiplier > MULTIPLIER_DECIMALS) { uint256 prevLeveredAmount = toLeveredAmount(amount, leverageMultiplier); uint256 newLeveredAmount = toLeveredAmount(amount, MULTIPLIER_DECIMALS); position.leverageMultiplier = MULTIPLIER_DECIMALS; totalLeveragedStakedSupply = totalLeveragedStakedSupply.sub(prevLeveredAmount).add(newLeveredAmount); } } } function isAdmin() public view returns (bool) { return hasRole(OWNER_ROLE, _msgSender()); } modifier onlyAdmin() { require(isAdmin(), "Must have admin role to perform this action"); _; } /* ========== EVENTS ========== */ event RewardAdded(uint256 reward); event Staked(address indexed user, uint256 indexed tokenId, uint256 amount, uint256 lockedUntil, uint256 multiplier); event DepositedAndStaked( address indexed user, uint256 depositedAmount, uint256 indexed tokenId, uint256 amount, uint256 lockedUntil, uint256 multiplier ); event Unstaked(address indexed user, uint256 indexed tokenId, uint256 amount); event UnstakedAndWithdrew(address indexed user, uint256 usdcReceivedAmount, uint256 indexed tokenId, uint256 amount); event UnstakedAndWithdrewMultiple( address indexed user, uint256 usdcReceivedAmount, uint256[] tokenIds, uint256[] amounts ); event RewardPaid(address indexed user, uint256 indexed tokenId, uint256 reward); event GoldfinchConfigUpdated(address indexed who, address configAddress); }
Transfer rewards from msg.sender, to be used for reward distribution
function loadRewards(uint256 rewards) public onlyAdmin updateReward(0) { rewardsToken().safeTransferFrom(msg.sender, address(this), rewards); rewardsAvailable = rewardsAvailable.add(rewards); emit RewardAdded(rewards); }
1,799,979
pragma solidity ^0.6.0; import "../common/Initializable.sol"; // Ownable implements basic access control mechanism with a single account, // the owner, that has been granted an elevated access privilege to specific // functions of the inherited contract. contract Ownable is Initializable { // keep the owner address address private _owner; // OwnershipTransferred informs about ownership changes event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); // initialize sets the initial state of the contract // by assigning the first owner address function initialize(address sender) internal initializer { _owner = sender; emit OwnershipTransferred(address(0), _owner); } // owner exposes the current owner address function owner() public view returns (address) { return _owner; } // isOwner checks if the given address is the current owner function isOwner(address adr) public view returns (bool) { return adr == _owner; } // onlyOwner allows to wrap functions to check for elevated privileges // before they are executed. modifier onlyOwner() { // check for privileges require(isOwner(msg.sender), "Ownable: access restricted"); _; } // renounceOwnership drops the ownership leaving the contract without // an owner. Please note, this can not be restored and any functionality // originally accessible only to the owner will be inaccessible. function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } // transferOwnership transfers ownership of the contract from the current // owner to a newly specified address. The old owner looses access // to all the functions with controlled access. function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } // _transferOwnership implements the ownership transfer with all the necessary // checks so the transfer is safe and sane. function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: zero address not allowed"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; }
isOwner checks if the given address is the current owner
function isOwner(address adr) public view returns (bool) { return adr == _owner; }
2,562,200
pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; // SPDX-License-Identifier: MIT OR Apache-2.0 import "./ReentrancyGuard.sol"; import "./SafeMath.sol"; import "./SafeMathUInt128.sol"; import "./SafeCast.sol"; import "./Utils.sol"; import "./Storage.sol"; import "./Config.sol"; import "./Events.sol"; import "./Bytes.sol"; import "./Operations.sol"; import "./UpgradeableMaster.sol"; import "./RegenesisMultisig.sol"; import "./AdditionalZkSync.sol"; /// @title zkSync main contract /// @author Matter Labs contract ZkSync is UpgradeableMaster, Storage, Config, Events, ReentrancyGuard { using SafeMath for uint256; using SafeMathUInt128 for uint128; bytes32 private constant EMPTY_STRING_KECCAK = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; /// @notice Data needed to process onchain operation from block public data. /// @notice Onchain operations is operations that need some processing on L1: Deposits, Withdrawals, ChangePubKey. /// @param ethWitness Some external data that can be needed for operation processing /// @param publicDataOffset Byte offset in public data for onchain operation struct OnchainOperationData { bytes ethWitness; uint32 publicDataOffset; } /// @notice Data needed to commit new block struct CommitBlockInfo { bytes32 newStateHash; bytes publicData; uint256 timestamp; OnchainOperationData[] onchainOperations; uint32 blockNumber; uint32 feeAccount; } /// @notice Data needed to execute committed and verified block /// @param commitmentsInSlot verified commitments in one slot /// @param commitmentIdx index such that commitmentsInSlot[commitmentIdx] is current block commitment struct ExecuteBlockInfo { StoredBlockInfo storedBlock; bytes[] pendingOnchainOpsPubdata; } /// @notice Recursive proof input data (individual commitments are constructed onchain) struct ProofInput { uint256[] recursiveInput; uint256[] proof; uint256[] commitments; uint8[] vkIndexes; uint256[16] subproofsLimbs; } // Upgrade functional /// @notice Notice period before activation preparation status of upgrade mode function getNoticePeriod() external pure override returns (uint256) { return 0; } /// @notice Notification that upgrade notice period started /// @dev Can be external because Proxy contract intercepts illegal calls of this function function upgradeNoticePeriodStarted() external override { upgradeStartTimestamp = block.timestamp; } /// @notice Notification that upgrade preparation status is activated /// @dev Can be external because Proxy contract intercepts illegal calls of this function function upgradePreparationStarted() external override { upgradePreparationActive = true; upgradePreparationActivationTime = block.timestamp; require(block.timestamp >= upgradeStartTimestamp.add(approvedUpgradeNoticePeriod)); } /// @dev When upgrade is finished or canceled we must clean upgrade-related state. function clearUpgradeStatus() internal { upgradePreparationActive = false; upgradePreparationActivationTime = 0; approvedUpgradeNoticePeriod = UPGRADE_NOTICE_PERIOD; emit NoticePeriodChange(approvedUpgradeNoticePeriod); upgradeStartTimestamp = 0; for (uint256 i = 0; i < SECURITY_COUNCIL_MEMBERS_NUMBER; ++i) { securityCouncilApproves[i] = false; } numberOfApprovalsFromSecurityCouncil = 0; } /// @notice Notification that upgrade canceled /// @dev Can be external because Proxy contract intercepts illegal calls of this function function upgradeCanceled() external override { clearUpgradeStatus(); } /// @notice Notification that upgrade finishes /// @dev Can be external because Proxy contract intercepts illegal calls of this function function upgradeFinishes() external override { clearUpgradeStatus(); } /// @notice Checks that contract is ready for upgrade /// @return bool flag indicating that contract is ready for upgrade function isReadyForUpgrade() external view override returns (bool) { return !exodusMode; } /// @notice zkSync contract initialization. Can be external because Proxy contract intercepts illegal calls of this function. /// @param initializationParameters Encoded representation of initialization parameters: /// @dev _governanceAddress The address of Governance contract /// @dev _verifierAddress The address of Verifier contract /// @dev _genesisStateHash Genesis blocks (first block) state tree root hash function initialize(bytes calldata initializationParameters) external { initializeReentrancyGuard(); ( Governance _governanceAddress, Verifier _verifierAddress, AdditionalZkSync _additionalZkSync, bytes32 _genesisStateHash ) = abi.decode(initializationParameters, (Governance, Verifier, AdditionalZkSync, bytes32)); verifier = _verifierAddress; governance = _governanceAddress; additionalZkSync = _additionalZkSync; StoredBlockInfo memory storedBlockZero = StoredBlockInfo(0, 0, EMPTY_STRING_KECCAK, 0, _genesisStateHash, bytes32(0)); storedBlockHashes[0] = hashStoredBlockInfo(storedBlockZero); approvedUpgradeNoticePeriod = UPGRADE_NOTICE_PERIOD; emit NoticePeriodChange(approvedUpgradeNoticePeriod); } /// @notice zkSync contract upgrade. Can be external because Proxy contract intercepts illegal calls of this function. /// @param upgradeParameters Encoded representation of upgrade parameters // solhint-disable-next-line no-empty-blocks function upgrade(bytes calldata upgradeParameters) external nonReentrant {} function cutUpgradeNoticePeriod() external { /// All functions delegated to additional contract should NOT be nonReentrant delegateAdditional(); } /// @notice Sends tokens /// @dev NOTE: will revert if transfer call fails or rollup balance difference (before and after transfer) is bigger than _maxAmount /// @dev This function is used to allow tokens to spend zkSync contract balance up to amount that is requested /// @param _token Token address /// @param _to Address of recipient /// @param _amount Amount of tokens to transfer /// @param _maxAmount Maximum possible amount of tokens to transfer to this account function _transferERC20( IERC20 _token, address _to, uint128 _amount, uint128 _maxAmount ) external returns (uint128 withdrawnAmount) { require(msg.sender == address(this), "5"); // wtg10 - can be called only from this contract as one "external" call (to revert all this function state changes if it is needed) uint256 balanceBefore = _token.balanceOf(address(this)); require(Utils.sendERC20(_token, _to, _amount), "6"); // wtg11 - ERC20 transfer fails uint256 balanceAfter = _token.balanceOf(address(this)); uint256 balanceDiff = balanceBefore.sub(balanceAfter); require(balanceDiff <= _maxAmount, "7"); // wtg12 - rollup balance difference (before and after transfer) is bigger than _maxAmount return SafeCast.toUint128(balanceDiff); } /// @notice Accrues users balances from deposit priority requests in Exodus mode /// @dev WARNING: Only for Exodus mode /// @dev Canceling may take several separate transactions to be completed /// @param _n number of requests to process function cancelOutstandingDepositsForExodusMode(uint64 _n, bytes[] memory _depositsPubdata) external { /// All functions delegated to additional contract should NOT be nonReentrant delegateAdditional(); } /// @notice Deposit ETH to Layer 2 - transfer ether from user into contract, validate it, register deposit /// @param _zkSyncAddress The receiver Layer 2 address function depositETH(address _zkSyncAddress) external payable { require(_zkSyncAddress != SPECIAL_ACCOUNT_ADDRESS, "P"); requireActive(); registerDeposit(0, SafeCast.toUint128(msg.value), _zkSyncAddress); } /// @notice Deposit ERC20 token to Layer 2 - transfer ERC20 tokens from user into contract, validate it, register deposit /// @param _token Token address /// @param _amount Token amount /// @param _zkSyncAddress Receiver Layer 2 address function depositERC20( IERC20 _token, uint104 _amount, address _zkSyncAddress ) external nonReentrant { require(_zkSyncAddress != SPECIAL_ACCOUNT_ADDRESS, "P"); requireActive(); // Get token id by its address uint16 tokenId = governance.validateTokenAddress(address(_token)); require(!governance.pausedTokens(tokenId), "b"); // token deposits are paused uint256 balanceBefore = _token.balanceOf(address(this)); require(Utils.transferFromERC20(_token, msg.sender, address(this), SafeCast.toUint128(_amount)), "c"); // token transfer failed deposit uint256 balanceAfter = _token.balanceOf(address(this)); uint128 depositAmount = SafeCast.toUint128(balanceAfter.sub(balanceBefore)); require(depositAmount <= MAX_DEPOSIT_AMOUNT, "C"); registerDeposit(tokenId, depositAmount, _zkSyncAddress); } /// @notice Returns amount of tokens that can be withdrawn by `address` from zkSync contract /// @param _address Address of the tokens owner /// @param _token Address of token, zero address is used for ETH function getPendingBalance(address _address, address _token) public view returns (uint128) { uint16 tokenId = 0; if (_token != address(0)) { tokenId = governance.validateTokenAddress(_token); } return pendingBalances[packAddressAndTokenId(_address, tokenId)].balanceToWithdraw; } /// @notice Withdraws tokens from zkSync contract to the owner /// @param _owner Address of the tokens owner /// @param _token Address of tokens, zero address is used for ETH /// @param _amount Amount to withdraw to request. /// NOTE: We will call ERC20.transfer(.., _amount), but if according to internal logic of ERC20 token zkSync contract /// balance will be decreased by value more then _amount we will try to subtract this value from user pending balance function withdrawPendingBalance( address payable _owner, address _token, uint128 _amount ) external nonReentrant { if (_token == address(0)) { registerWithdrawal(0, _amount, _owner); (bool success, ) = _owner.call{value: _amount}(""); require(success, "d"); // ETH withdraw failed } else { uint16 tokenId = governance.validateTokenAddress(_token); bytes22 packedBalanceKey = packAddressAndTokenId(_owner, tokenId); uint128 balance = pendingBalances[packedBalanceKey].balanceToWithdraw; // We will allow withdrawals of `value` such that: // `value` <= user pending balance // `value` can be bigger then `_amount` requested if token takes fee from sender in addition to `_amount` requested uint128 withdrawnAmount = this._transferERC20(IERC20(_token), _owner, _amount, balance); registerWithdrawal(tokenId, withdrawnAmount, _owner); } } /// @notice Withdraws NFT from zkSync contract to the owner /// @param _tokenId Id of NFT token function withdrawPendingNFTBalance(uint32 _tokenId) external nonReentrant { Operations.WithdrawNFT memory op = pendingWithdrawnNFTs[_tokenId]; require(op.creatorAddress != address(0), "op"); // No NFT to withdraw NFTFactory _factory = governance.getNFTFactory(op.creatorAccountId, op.creatorAddress); _factory.mintNFTFromZkSync( op.creatorAddress, op.receiver, op.creatorAccountId, op.serialId, op.contentHash, op.tokenId ); // Save withdrawn nfts for future deposits withdrawnNFTs[op.tokenId] = address(_factory); emit WithdrawalNFT(op.tokenId); delete pendingWithdrawnNFTs[_tokenId]; } /// @notice Register full exit request - pack pubdata, add priority request /// @param _accountId Numerical id of the account /// @param _token Token address, 0 address for ether function requestFullExit(uint32 _accountId, address _token) public nonReentrant { requireActive(); require(_accountId <= MAX_ACCOUNT_ID, "e"); require(_accountId != SPECIAL_ACCOUNT_ID, "v"); // request full exit for nft storage account uint16 tokenId; if (_token == address(0)) { tokenId = 0; } else { tokenId = governance.validateTokenAddress(_token); } // Priority Queue request Operations.FullExit memory op = Operations.FullExit({ accountId: _accountId, owner: msg.sender, tokenId: tokenId, amount: 0, // unknown at this point nftCreatorAccountId: uint32(0), // unknown at this point nftCreatorAddress: address(0), // unknown at this point nftSerialId: uint32(0), // unknown at this point nftContentHash: bytes32(0) // unknown at this point }); bytes memory pubData = Operations.writeFullExitPubdataForPriorityQueue(op); addPriorityRequest(Operations.OpType.FullExit, pubData); // User must fill storage slot of balancesToWithdraw(msg.sender, tokenId) with nonzero value // In this case operator should just overwrite this slot during confirming withdrawal bytes22 packedBalanceKey = packAddressAndTokenId(msg.sender, tokenId); pendingBalances[packedBalanceKey].gasReserveValue = FILLED_GAS_RESERVE_VALUE; } /// @notice Register full exit nft request - pack pubdata, add priority request /// @param _accountId Numerical id of the account /// @param _tokenId NFT token id in zkSync network function requestFullExitNFT(uint32 _accountId, uint32 _tokenId) public nonReentrant { requireActive(); require(_accountId <= MAX_ACCOUNT_ID, "e"); require(_accountId != SPECIAL_ACCOUNT_ID, "v"); // request full exit nft for nft storage account require(MAX_FUNGIBLE_TOKEN_ID < _tokenId && _tokenId < SPECIAL_NFT_TOKEN_ID, "T"); // request full exit nft for invalid token id // Priority Queue request Operations.FullExit memory op = Operations.FullExit({ accountId: _accountId, owner: msg.sender, tokenId: _tokenId, amount: 0, // unknown at this point nftCreatorAccountId: uint32(0), // unknown at this point nftCreatorAddress: address(0), // unknown at this point nftSerialId: uint32(0), // unknown at this point nftContentHash: bytes32(0) // unknown at this point }); bytes memory pubData = Operations.writeFullExitPubdataForPriorityQueue(op); addPriorityRequest(Operations.OpType.FullExit, pubData); } /// @dev Process one block commit using previous block StoredBlockInfo, /// @dev returns new block StoredBlockInfo /// @dev NOTE: Does not change storage (except events, so we can't mark it view) function commitOneBlock(StoredBlockInfo memory _previousBlock, CommitBlockInfo memory _newBlock) internal view returns (StoredBlockInfo memory storedNewBlock) { require(_newBlock.blockNumber == _previousBlock.blockNumber + 1, "f"); // only commit next block // Check timestamp of the new block { require(_newBlock.timestamp >= _previousBlock.timestamp, "g"); // Block should be after previous block bool timestampNotTooSmall = block.timestamp.sub(COMMIT_TIMESTAMP_NOT_OLDER) <= _newBlock.timestamp; bool timestampNotTooBig = _newBlock.timestamp <= block.timestamp.add(COMMIT_TIMESTAMP_APPROXIMATION_DELTA); require(timestampNotTooSmall && timestampNotTooBig, "h"); // New block timestamp is not valid } // Check onchain operations (bytes32 pendingOnchainOpsHash, uint64 priorityReqCommitted, bytes memory onchainOpsOffsetCommitment) = collectOnchainOps(_newBlock); // Create block commitment for verification proof bytes32 commitment = createBlockCommitment(_previousBlock, _newBlock, onchainOpsOffsetCommitment); return StoredBlockInfo( _newBlock.blockNumber, priorityReqCommitted, pendingOnchainOpsHash, _newBlock.timestamp, _newBlock.newStateHash, commitment ); } /// @notice Commit block /// @notice 1. Checks onchain operations, timestamp. /// @notice 2. Store block commitments function commitBlocks(StoredBlockInfo memory _lastCommittedBlockData, CommitBlockInfo[] memory _newBlocksData) external nonReentrant { requireActive(); governance.requireActiveValidator(msg.sender); // Check that we commit blocks after last committed block require(storedBlockHashes[totalBlocksCommitted] == hashStoredBlockInfo(_lastCommittedBlockData), "i"); // incorrect previous block data for (uint32 i = 0; i < _newBlocksData.length; ++i) { _lastCommittedBlockData = commitOneBlock(_lastCommittedBlockData, _newBlocksData[i]); totalCommittedPriorityRequests += _lastCommittedBlockData.priorityOperations; storedBlockHashes[_lastCommittedBlockData.blockNumber] = hashStoredBlockInfo(_lastCommittedBlockData); emit BlockCommit(_lastCommittedBlockData.blockNumber); } totalBlocksCommitted += uint32(_newBlocksData.length); require(totalCommittedPriorityRequests <= totalOpenPriorityRequests, "j"); } /// @dev 1. Try to send token to _recipients /// @dev 2. On failure: Increment _recipients balance to withdraw. function withdrawOrStoreNFT(Operations.WithdrawNFT memory op) internal { NFTFactory _factory = governance.getNFTFactory(op.creatorAccountId, op.creatorAddress); try _factory.mintNFTFromZkSync{gas: WITHDRAWAL_NFT_GAS_LIMIT}( op.creatorAddress, op.receiver, op.creatorAccountId, op.serialId, op.contentHash, op.tokenId ) { // Save withdrawn nfts for future deposits withdrawnNFTs[op.tokenId] = address(_factory); emit WithdrawalNFT(op.tokenId); } catch { pendingWithdrawnNFTs[op.tokenId] = op; } } /// @dev 1. Try to send token to _recipients /// @dev 2. On failure: Increment _recipients balance to withdraw. function withdrawOrStore( uint16 _tokenId, address _recipient, uint128 _amount ) internal { bytes22 packedBalanceKey = packAddressAndTokenId(_recipient, _tokenId); bool sent = false; if (_tokenId == 0) { address payable toPayable = address(uint160(_recipient)); sent = sendETHNoRevert(toPayable, _amount); } else { address tokenAddr = governance.tokenAddresses(_tokenId); // We use `_transferERC20` here to check that `ERC20` token indeed transferred `_amount` // and fail if token subtracted from zkSync balance more then `_amount` that was requested. // This can happen if token subtracts fee from sender while transferring `_amount` that was requested to transfer. try this._transferERC20{gas: WITHDRAWAL_GAS_LIMIT}(IERC20(tokenAddr), _recipient, _amount, _amount) { sent = true; } catch { sent = false; } } if (sent) { emit Withdrawal(_tokenId, _amount); } else { increaseBalanceToWithdraw(packedBalanceKey, _amount); } } /// @dev Executes one block /// @dev 1. Processes all pending operations (Send Exits, Complete priority requests) /// @dev 2. Finalizes block on Ethereum /// @dev _executedBlockIdx is index in the array of the blocks that we want to execute together function executeOneBlock(ExecuteBlockInfo memory _blockExecuteData, uint32 _executedBlockIdx) internal { // Ensure block was committed require( hashStoredBlockInfo(_blockExecuteData.storedBlock) == storedBlockHashes[_blockExecuteData.storedBlock.blockNumber], "exe10" // executing block should be committed ); require(_blockExecuteData.storedBlock.blockNumber == totalBlocksExecuted + _executedBlockIdx + 1, "k"); // Execute blocks in order bytes32 pendingOnchainOpsHash = EMPTY_STRING_KECCAK; for (uint32 i = 0; i < _blockExecuteData.pendingOnchainOpsPubdata.length; ++i) { bytes memory pubData = _blockExecuteData.pendingOnchainOpsPubdata[i]; Operations.OpType opType = Operations.OpType(uint8(pubData[0])); if (opType == Operations.OpType.PartialExit) { Operations.PartialExit memory op = Operations.readPartialExitPubdata(pubData); // Circuit guarantees that partial exits are available only for fungible tokens require(op.tokenId <= MAX_FUNGIBLE_TOKEN_ID, "mf1"); withdrawOrStore(uint16(op.tokenId), op.owner, op.amount); } else if (opType == Operations.OpType.ForcedExit) { Operations.ForcedExit memory op = Operations.readForcedExitPubdata(pubData); // Circuit guarantees that forced exits are available only for fungible tokens require(op.tokenId <= MAX_FUNGIBLE_TOKEN_ID, "mf2"); withdrawOrStore(uint16(op.tokenId), op.target, op.amount); } else if (opType == Operations.OpType.FullExit) { Operations.FullExit memory op = Operations.readFullExitPubdata(pubData); if (op.tokenId <= MAX_FUNGIBLE_TOKEN_ID) { withdrawOrStore(uint16(op.tokenId), op.owner, op.amount); } else { if (op.amount == 1) { Operations.WithdrawNFT memory withdrawNftOp = Operations.WithdrawNFT( op.nftCreatorAccountId, op.nftCreatorAddress, op.nftSerialId, op.nftContentHash, op.owner, op.tokenId ); withdrawOrStoreNFT(withdrawNftOp); } } } else if (opType == Operations.OpType.WithdrawNFT) { Operations.WithdrawNFT memory op = Operations.readWithdrawNFTPubdata(pubData); withdrawOrStoreNFT(op); } else { revert("l"); // unsupported op in block execution } pendingOnchainOpsHash = Utils.concatHash(pendingOnchainOpsHash, pubData); } require(pendingOnchainOpsHash == _blockExecuteData.storedBlock.pendingOnchainOperationsHash, "m"); // incorrect onchain ops executed } /// @notice Execute blocks, completing priority operations and processing withdrawals. /// @notice 1. Processes all pending operations (Send Exits, Complete priority requests) /// @notice 2. Finalizes block on Ethereum function executeBlocks(ExecuteBlockInfo[] memory _blocksData) external nonReentrant { requireActive(); governance.requireActiveValidator(msg.sender); uint64 priorityRequestsExecuted = 0; uint32 nBlocks = uint32(_blocksData.length); for (uint32 i = 0; i < nBlocks; ++i) { executeOneBlock(_blocksData[i], i); priorityRequestsExecuted += _blocksData[i].storedBlock.priorityOperations; emit BlockVerification(_blocksData[i].storedBlock.blockNumber); } firstPriorityRequestId += priorityRequestsExecuted; totalCommittedPriorityRequests -= priorityRequestsExecuted; totalOpenPriorityRequests -= priorityRequestsExecuted; totalBlocksExecuted += nBlocks; require(totalBlocksExecuted <= totalBlocksProven, "n"); // Can't execute blocks more then committed and proven currently. } /// @notice Blocks commitment verification. /// @notice Only verifies block commitments without any other processing function proveBlocks(StoredBlockInfo[] memory _committedBlocks, ProofInput memory _proof) external nonReentrant { uint32 currentTotalBlocksProven = totalBlocksProven; for (uint256 i = 0; i < _committedBlocks.length; ++i) { require(hashStoredBlockInfo(_committedBlocks[i]) == storedBlockHashes[currentTotalBlocksProven + 1], "o1"); ++currentTotalBlocksProven; require(_proof.commitments[i] & INPUT_MASK == uint256(_committedBlocks[i].commitment) & INPUT_MASK, "o"); // incorrect block commitment in proof } bool success = verifier.verifyAggregatedBlockProof( _proof.recursiveInput, _proof.proof, _proof.vkIndexes, _proof.commitments, _proof.subproofsLimbs ); require(success, "p"); // Aggregated proof verification fail require(currentTotalBlocksProven <= totalBlocksCommitted, "q"); totalBlocksProven = currentTotalBlocksProven; } /// @notice Reverts unverified blocks function revertBlocks(StoredBlockInfo[] memory _blocksToRevert) external { /// All functions delegated to additional contract should NOT be nonReentrant delegateAdditional(); } /// @notice Checks if Exodus mode must be entered. If true - enters exodus mode and emits ExodusMode event. /// @dev Exodus mode must be entered in case of current ethereum block number is higher than the oldest /// @dev of existed priority requests expiration block number. /// @return bool flag that is true if the Exodus mode must be entered. function activateExodusMode() public returns (bool) { bool trigger = block.number >= priorityRequests[firstPriorityRequestId].expirationBlock && priorityRequests[firstPriorityRequestId].expirationBlock != 0; if (trigger) { if (!exodusMode) { exodusMode = true; emit ExodusMode(); } return true; } else { return false; } } /// @notice Withdraws token from ZkSync to root chain in case of exodus mode. User must provide proof that he owns funds /// @param _storedBlockInfo Last verified block /// @param _owner Owner of the account /// @param _accountId Id of the account in the tree /// @param _proof Proof /// @param _tokenId Verified token id /// @param _amount Amount for owner (must be total amount, not part of it) function performExodus( StoredBlockInfo memory _storedBlockInfo, address _owner, uint32 _accountId, uint32 _tokenId, uint128 _amount, uint32 _nftCreatorAccountId, address _nftCreatorAddress, uint32 _nftSerialId, bytes32 _nftContentHash, uint256[] memory _proof ) external { /// All functions delegated to additional should NOT be nonReentrant delegateAdditional(); } /// @notice Set data for changing pubkey hash using onchain authorization. /// Transaction author (msg.sender) should be L2 account address /// @notice New pubkey hash can be reset, to do that user should send two transactions: /// 1) First `setAuthPubkeyHash` transaction for already used `_nonce` will set timer. /// 2) After `AUTH_FACT_RESET_TIMELOCK` time is passed second `setAuthPubkeyHash` transaction will reset pubkey hash for `_nonce`. /// @param _pubkeyHash New pubkey hash /// @param _nonce Nonce of the change pubkey L2 transaction function setAuthPubkeyHash(bytes calldata _pubkeyHash, uint32 _nonce) external { /// All functions delegated to additional contract should NOT be nonReentrant delegateAdditional(); } /// @notice Register deposit request - pack pubdata, add priority request and emit OnchainDeposit event /// @param _tokenId Token by id /// @param _amount Token amount /// @param _owner Receiver function registerDeposit( uint16 _tokenId, uint128 _amount, address _owner ) internal { // Priority Queue request Operations.Deposit memory op = Operations.Deposit({ accountId: 0, // unknown at this point owner: _owner, tokenId: _tokenId, amount: _amount }); bytes memory pubData = Operations.writeDepositPubdataForPriorityQueue(op); addPriorityRequest(Operations.OpType.Deposit, pubData); emit Deposit(_tokenId, _amount); } /// @notice Register withdrawal - update user balance and emit OnchainWithdrawal event /// @param _token - token by id /// @param _amount - token amount /// @param _to - address to withdraw to function registerWithdrawal( uint16 _token, uint128 _amount, address payable _to ) internal { bytes22 packedBalanceKey = packAddressAndTokenId(_to, _token); uint128 balance = pendingBalances[packedBalanceKey].balanceToWithdraw; pendingBalances[packedBalanceKey].balanceToWithdraw = balance.sub(_amount); emit Withdrawal(_token, _amount); } /// @dev Gets operations packed in bytes array. Unpacks it and stores onchain operations. /// @dev Priority operations must be committed in the same order as they are in the priority queue. /// @dev NOTE: does not change storage! (only emits events) /// @dev processableOperationsHash - hash of the all operations that needs to be executed (Deposit, Exits, ChangPubKey) /// @dev priorityOperationsProcessed - number of priority operations processed in this block (Deposits, FullExits) /// @dev offsetsCommitment - array where 1 is stored in chunk where onchainOperation begins and other are 0 (used in commitments) function collectOnchainOps(CommitBlockInfo memory _newBlockData) internal view returns ( bytes32 processableOperationsHash, uint64 priorityOperationsProcessed, bytes memory offsetsCommitment ) { bytes memory pubData = _newBlockData.publicData; uint64 uncommittedPriorityRequestsOffset = firstPriorityRequestId + totalCommittedPriorityRequests; priorityOperationsProcessed = 0; processableOperationsHash = EMPTY_STRING_KECCAK; require(pubData.length % CHUNK_BYTES == 0, "A"); // pubdata length must be a multiple of CHUNK_BYTES offsetsCommitment = new bytes(pubData.length / CHUNK_BYTES); for (uint256 i = 0; i < _newBlockData.onchainOperations.length; ++i) { OnchainOperationData memory onchainOpData = _newBlockData.onchainOperations[i]; uint256 pubdataOffset = onchainOpData.publicDataOffset; require(pubdataOffset < pubData.length, "A1"); require(pubdataOffset % CHUNK_BYTES == 0, "B"); // offsets should be on chunks boundaries uint256 chunkId = pubdataOffset / CHUNK_BYTES; require(offsetsCommitment[chunkId] == 0x00, "C"); // offset commitment should be empty offsetsCommitment[chunkId] = bytes1(0x01); Operations.OpType opType = Operations.OpType(uint8(pubData[pubdataOffset])); if (opType == Operations.OpType.Deposit) { bytes memory opPubData = Bytes.slice(pubData, pubdataOffset, DEPOSIT_BYTES); Operations.Deposit memory depositData = Operations.readDepositPubdata(opPubData); checkPriorityOperation(depositData, uncommittedPriorityRequestsOffset + priorityOperationsProcessed); priorityOperationsProcessed++; } else if (opType == Operations.OpType.ChangePubKey) { bytes memory opPubData = Bytes.slice(pubData, pubdataOffset, CHANGE_PUBKEY_BYTES); Operations.ChangePubKey memory op = Operations.readChangePubKeyPubdata(opPubData); if (onchainOpData.ethWitness.length != 0) { bool valid = verifyChangePubkey(onchainOpData.ethWitness, op); require(valid, "D"); // failed to verify change pubkey hash signature } else { bool valid = authFacts[op.owner][op.nonce] == keccak256(abi.encodePacked(op.pubKeyHash)); require(valid, "E"); // new pub key hash is not authenticated properly } } else { bytes memory opPubData; if (opType == Operations.OpType.PartialExit) { opPubData = Bytes.slice(pubData, pubdataOffset, PARTIAL_EXIT_BYTES); } else if (opType == Operations.OpType.ForcedExit) { opPubData = Bytes.slice(pubData, pubdataOffset, FORCED_EXIT_BYTES); } else if (opType == Operations.OpType.WithdrawNFT) { opPubData = Bytes.slice(pubData, pubdataOffset, WITHDRAW_NFT_BYTES); } else if (opType == Operations.OpType.FullExit) { opPubData = Bytes.slice(pubData, pubdataOffset, FULL_EXIT_BYTES); Operations.FullExit memory fullExitData = Operations.readFullExitPubdata(opPubData); checkPriorityOperation( fullExitData, uncommittedPriorityRequestsOffset + priorityOperationsProcessed ); priorityOperationsProcessed++; } else { revert("F"); // unsupported op } processableOperationsHash = Utils.concatHash(processableOperationsHash, opPubData); } } } /// @notice Checks that change operation is correct function verifyChangePubkey(bytes memory _ethWitness, Operations.ChangePubKey memory _changePk) internal pure returns (bool) { Operations.ChangePubkeyType changePkType = Operations.ChangePubkeyType(uint8(_ethWitness[0])); if (changePkType == Operations.ChangePubkeyType.ECRECOVER) { return verifyChangePubkeyECRECOVER(_ethWitness, _changePk); } else if (changePkType == Operations.ChangePubkeyType.CREATE2) { return verifyChangePubkeyCREATE2(_ethWitness, _changePk); } else if (changePkType == Operations.ChangePubkeyType.OldECRECOVER) { return verifyChangePubkeyOldECRECOVER(_ethWitness, _changePk); } else { revert("G"); // Incorrect ChangePubKey type } } /// @notice Checks that signature is valid for pubkey change message /// @param _ethWitness Signature (65 bytes) + 32 bytes of the arbitrary signed data /// @param _changePk Parsed change pubkey operation function verifyChangePubkeyECRECOVER(bytes memory _ethWitness, Operations.ChangePubKey memory _changePk) internal pure returns (bool) { (, bytes memory signature) = Bytes.read(_ethWitness, 1, 65); // offset is 1 because we skip type of ChangePubkey // (, bytes32 additionalData) = Bytes.readBytes32(_ethWitness, offset); bytes32 messageHash = keccak256( abi.encodePacked( "\x19Ethereum Signed Message:\n60", _changePk.pubKeyHash, _changePk.nonce, _changePk.accountId, bytes32(0) ) ); address recoveredAddress = Utils.recoverAddressFromEthSignature(signature, messageHash); return recoveredAddress == _changePk.owner && recoveredAddress != address(0); } /// @notice Checks that signature is valid for pubkey change message, old version differs by form of the signed message. /// @param _ethWitness Signature (65 bytes) /// @param _changePk Parsed change pubkey operation function verifyChangePubkeyOldECRECOVER(bytes memory _ethWitness, Operations.ChangePubKey memory _changePk) internal pure returns (bool) { (, bytes memory signature) = Bytes.read(_ethWitness, 1, 65); // offset is 1 because we skip type of ChangePubkey bytes32 messageHash = keccak256( abi.encodePacked( "\x19Ethereum Signed Message:\n152", "Register zkSync pubkey:\n\n", Bytes.bytesToHexASCIIBytes(abi.encodePacked(_changePk.pubKeyHash)), "\n", "nonce: 0x", Bytes.bytesToHexASCIIBytes(Bytes.toBytesFromUInt32(_changePk.nonce)), "\n", "account id: 0x", Bytes.bytesToHexASCIIBytes(Bytes.toBytesFromUInt32(_changePk.accountId)), "\n\n", "Only sign this message for a trusted client!" ) ); address recoveredAddress = Utils.recoverAddressFromEthSignature(signature, messageHash); return recoveredAddress == _changePk.owner && recoveredAddress != address(0); } /// @notice Checks that signature is valid for pubkey change message /// @param _ethWitness Create2 deployer address, saltArg, codeHash /// @param _changePk Parsed change pubkey operation function verifyChangePubkeyCREATE2(bytes memory _ethWitness, Operations.ChangePubKey memory _changePk) internal pure returns (bool) { address creatorAddress; bytes32 saltArg; // salt arg is additional bytes that are encoded in the CREATE2 salt bytes32 codeHash; uint256 offset = 1; // offset is 1 because we skip type of ChangePubkey (offset, creatorAddress) = Bytes.readAddress(_ethWitness, offset); (offset, saltArg) = Bytes.readBytes32(_ethWitness, offset); (offset, codeHash) = Bytes.readBytes32(_ethWitness, offset); // salt from CREATE2 specification bytes32 salt = keccak256(abi.encodePacked(saltArg, _changePk.pubKeyHash)); // Address computation according to CREATE2 definition: https://eips.ethereum.org/EIPS/eip-1014 address recoveredAddress = address(uint160(uint256(keccak256(abi.encodePacked(bytes1(0xff), creatorAddress, salt, codeHash))))); // This type of change pubkey can be done only once return recoveredAddress == _changePk.owner && _changePk.nonce == 0; } /// @dev Creates block commitment from its data /// @dev _offsetCommitment - hash of the array where 1 is stored in chunk where onchainOperation begins and 0 for other chunks function createBlockCommitment( StoredBlockInfo memory _previousBlock, CommitBlockInfo memory _newBlockData, bytes memory _offsetCommitment ) internal view returns (bytes32 commitment) { bytes32 hash = sha256(abi.encodePacked(uint256(_newBlockData.blockNumber), uint256(_newBlockData.feeAccount))); hash = sha256(abi.encodePacked(hash, _previousBlock.stateHash)); hash = sha256(abi.encodePacked(hash, _newBlockData.newStateHash)); hash = sha256(abi.encodePacked(hash, uint256(_newBlockData.timestamp))); bytes memory pubdata = abi.encodePacked(_newBlockData.publicData, _offsetCommitment); /// The code below is equivalent to `commitment = sha256(abi.encodePacked(hash, _publicData))` /// We use inline assembly instead of this concise and readable code in order to avoid copying of `_publicData` (which saves ~90 gas per transfer operation). /// Specifically, we perform the following trick: /// First, replace the first 32 bytes of `_publicData` (where normally its length is stored) with the value of `hash`. /// Then, we call `sha256` precompile passing the `_publicData` pointer and the length of the concatenated byte buffer. /// Finally, we put the `_publicData.length` back to its original location (to the first word of `_publicData`). assembly { let hashResult := mload(0x40) let pubDataLen := mload(pubdata) mstore(pubdata, hash) // staticcall to the sha256 precompile at address 0x2 let success := staticcall(gas(), 0x2, pubdata, add(pubDataLen, 0x20), hashResult, 0x20) mstore(pubdata, pubDataLen) // Use "invalid" to make gas estimation work switch success case 0 { invalid() } commitment := mload(hashResult) } } /// @notice Checks that deposit is same as operation in priority queue /// @param _deposit Deposit data /// @param _priorityRequestId Operation's id in priority queue function checkPriorityOperation(Operations.Deposit memory _deposit, uint64 _priorityRequestId) internal view { Operations.OpType priorReqType = priorityRequests[_priorityRequestId].opType; require(priorReqType == Operations.OpType.Deposit, "H"); // incorrect priority op type bytes20 hashedPubdata = priorityRequests[_priorityRequestId].hashedPubData; require(Operations.checkDepositInPriorityQueue(_deposit, hashedPubdata), "I"); } /// @notice Checks that FullExit is same as operation in priority queue /// @param _fullExit FullExit data /// @param _priorityRequestId Operation's id in priority queue function checkPriorityOperation(Operations.FullExit memory _fullExit, uint64 _priorityRequestId) internal view { Operations.OpType priorReqType = priorityRequests[_priorityRequestId].opType; require(priorReqType == Operations.OpType.FullExit, "J"); // incorrect priority op type bytes20 hashedPubdata = priorityRequests[_priorityRequestId].hashedPubData; require(Operations.checkFullExitInPriorityQueue(_fullExit, hashedPubdata), "K"); } /// @notice Checks that current state not is exodus mode function requireActive() internal view { require(!exodusMode, "L"); // exodus mode activated } // Priority queue /// @notice Saves priority request in storage /// @dev Calculates expiration block for request, store this request and emit NewPriorityRequest event /// @param _opType Rollup operation type /// @param _pubData Operation pubdata function addPriorityRequest(Operations.OpType _opType, bytes memory _pubData) internal { // Expiration block is: current block number + priority expiration delta uint64 expirationBlock = uint64(block.number + PRIORITY_EXPIRATION); uint64 nextPriorityRequestId = firstPriorityRequestId + totalOpenPriorityRequests; bytes20 hashedPubData = Utils.hashBytesToBytes20(_pubData); priorityRequests[nextPriorityRequestId] = PriorityOperation({ hashedPubData: hashedPubData, expirationBlock: expirationBlock, opType: _opType }); emit NewPriorityRequest(msg.sender, nextPriorityRequestId, _opType, _pubData, uint256(expirationBlock)); totalOpenPriorityRequests++; } function increaseBalanceToWithdraw(bytes22 _packedBalanceKey, uint128 _amount) internal { uint128 balance = pendingBalances[_packedBalanceKey].balanceToWithdraw; pendingBalances[_packedBalanceKey] = PendingBalance(balance.add(_amount), FILLED_GAS_RESERVE_VALUE); } /// @notice Sends ETH /// @param _to Address of recipient /// @param _amount Amount of tokens to transfer /// @return bool flag indicating that transfer is successful function sendETHNoRevert(address payable _to, uint256 _amount) internal returns (bool) { (bool callSuccess, ) = _to.call{gas: WITHDRAWAL_GAS_LIMIT, value: _amount}(""); return callSuccess; } /// @notice Delegates the call to the additional part of the main contract. /// @notice Should be only use to delegate the external calls as it passes the calldata /// @notice All functions delegated to additional contract should NOT be nonReentrant function delegateAdditional() internal { AdditionalZkSync _target = additionalZkSync; assembly { // The pointer to the free memory slot let ptr := mload(0x40) // Copy function signature and arguments from calldata at zero position into memory at pointer position calldatacopy(ptr, 0x0, calldatasize()) // Delegatecall method of the implementation contract, returns 0 on error let result := delegatecall(gas(), _target, ptr, calldatasize(), 0x0, 0) // Get the size of the last return data let size := returndatasize() // Copy the size length of bytes from return data at zero position to pointer position returndatacopy(ptr, 0x0, size) // Depending on result value switch result case 0 { // End execution and revert state changes revert(ptr, size) } default { // Return data with length of size at pointers position return(ptr, size) } } } } pragma solidity ^0.7.0; // SPDX-License-Identifier: MIT OR Apache-2.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 { /// @dev Address of lock flag variable. /// @dev Flag is placed at random memory location to not interfere with Storage contract. uint256 private constant LOCK_FLAG_ADDRESS = 0x8e94fed44239eb2314ab7a406345e6c5a8f0ccedf3b600de3d004e672c33abf4; // keccak256("ReentrancyGuard") - 1; // https://github.com/OpenZeppelin/openzeppelin-contracts/blob/566a774222707e424896c0c390a84dc3c13bdcb2/contracts/security/ReentrancyGuard.sol // 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; function initializeReentrancyGuard() internal { uint256 lockSlotOldValue; // Storing an initial non-zero value makes deployment a bit more // expensive, but in exchange every call to nonReentrant // will be cheaper. assembly { lockSlotOldValue := sload(LOCK_FLAG_ADDRESS) sstore(LOCK_FLAG_ADDRESS, _NOT_ENTERED) } // Check that storage slot for reentrancy guard is empty to rule out possibility of slot conflict require(lockSlotOldValue == 0, "1B"); } /** * @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() { uint256 _status; assembly { _status := sload(LOCK_FLAG_ADDRESS) } // On the first call to nonReentrant, _notEntered will be true require(_status == _NOT_ENTERED); // Any calls to nonReentrant after this point will fail assembly { sstore(LOCK_FLAG_ADDRESS, _ENTERED) } _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) assembly { sstore(LOCK_FLAG_ADDRESS, _NOT_ENTERED) } } } pragma solidity ^0.7.0; // SPDX-License-Identifier: MIT OR Apache-2.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, "14"); 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, "v"); } /** * @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, "15"); 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, "x"); } /** * @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, "y"); } /** * @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; } } pragma solidity ^0.7.0; // SPDX-License-Identifier: MIT OR Apache-2.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 SafeMathUInt128 { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint128 a, uint128 b) internal pure returns (uint128) { uint128 c = a + b; require(c >= a, "12"); 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(uint128 a, uint128 b) internal pure returns (uint128) { return sub(a, b, "aa"); } /** * @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( uint128 a, uint128 b, string memory errorMessage ) internal pure returns (uint128) { require(b <= a, errorMessage); uint128 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(uint128 a, uint128 b) internal pure returns (uint128) { // 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; } uint128 c = a * b; require(c / a == b, "13"); 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(uint128 a, uint128 b) internal pure returns (uint128) { return div(a, b, "ac"); } /** * @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( uint128 a, uint128 b, string memory errorMessage ) internal pure returns (uint128) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint128 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(uint128 a, uint128 b) internal pure returns (uint128) { return mod(a, b, "ad"); } /** * @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( uint128 a, uint128 b, string memory errorMessage ) internal pure returns (uint128) { require(b != 0, errorMessage); return a % b; } } pragma solidity ^0.7.0; // SPDX-License-Identifier: MIT OR Apache-2.0 /** * @dev Wrappers over Solidity's uintXX casting operators with added overflow * checks. * * Downcasting from uint256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such 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. * * Can be combined with {SafeMath} to extend it to smaller types, by performing * all math on `uint256` and then downcasting. * * _Available since v2.5.0._ */ library SafeCast { /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "16"); return uint128(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "17"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "18"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "19"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "1a"); return uint8(value); } } pragma solidity ^0.7.0; // SPDX-License-Identifier: MIT OR Apache-2.0 import "./IERC20.sol"; import "./Bytes.sol"; library Utils { /// @notice Returns lesser of two values function minU32(uint32 a, uint32 b) internal pure returns (uint32) { return a < b ? a : b; } /// @notice Returns lesser of two values function minU64(uint64 a, uint64 b) internal pure returns (uint64) { return a < b ? a : b; } /// @notice Sends tokens /// @dev NOTE: this function handles tokens that have transfer function not strictly compatible with ERC20 standard /// @dev NOTE: call `transfer` to this token may return (bool) or nothing /// @param _token Token address /// @param _to Address of recipient /// @param _amount Amount of tokens to transfer /// @return bool flag indicating that transfer is successful function sendERC20( IERC20 _token, address _to, uint256 _amount ) internal returns (bool) { (bool callSuccess, bytes memory callReturnValueEncoded) = address(_token).call(abi.encodeWithSignature("transfer(address,uint256)", _to, _amount)); // `transfer` method may return (bool) or nothing. bool returnedSuccess = callReturnValueEncoded.length == 0 || abi.decode(callReturnValueEncoded, (bool)); return callSuccess && returnedSuccess; } /// @notice Transfers token from one address to another /// @dev NOTE: this function handles tokens that have transfer function not strictly compatible with ERC20 standard /// @dev NOTE: call `transferFrom` to this token may return (bool) or nothing /// @param _token Token address /// @param _from Address of sender /// @param _to Address of recipient /// @param _amount Amount of tokens to transfer /// @return bool flag indicating that transfer is successful function transferFromERC20( IERC20 _token, address _from, address _to, uint256 _amount ) internal returns (bool) { (bool callSuccess, bytes memory callReturnValueEncoded) = address(_token).call(abi.encodeWithSignature("transferFrom(address,address,uint256)", _from, _to, _amount)); // `transferFrom` method may return (bool) or nothing. bool returnedSuccess = callReturnValueEncoded.length == 0 || abi.decode(callReturnValueEncoded, (bool)); return callSuccess && returnedSuccess; } /// @notice Recovers signer's address from ethereum signature for given message /// @param _signature 65 bytes concatenated. R (32) + S (32) + V (1) /// @param _messageHash signed message hash. /// @return address of the signer function recoverAddressFromEthSignature(bytes memory _signature, bytes32 _messageHash) internal pure returns (address) { require(_signature.length == 65, "P"); // incorrect signature length bytes32 signR; bytes32 signS; uint8 signV; assembly { signR := mload(add(_signature, 32)) signS := mload(add(_signature, 64)) signV := byte(0, mload(add(_signature, 96))) } return ecrecover(_messageHash, signV, signR, signS); } /// @notice Returns new_hash = hash(old_hash + bytes) function concatHash(bytes32 _hash, bytes memory _bytes) internal pure returns (bytes32) { bytes32 result; assembly { let bytesLen := add(mload(_bytes), 32) mstore(_bytes, _hash) result := keccak256(_bytes, bytesLen) } return result; } function hashBytesToBytes20(bytes memory _bytes) internal pure returns (bytes20) { return bytes20(uint160(uint256(keccak256(_bytes)))); } } pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; // SPDX-License-Identifier: MIT OR Apache-2.0 // solhint-disable max-states-count import "./IERC20.sol"; import "./Governance.sol"; import "./Verifier.sol"; import "./Operations.sol"; import "./NFTFactory.sol"; import "./AdditionalZkSync.sol"; /// @title zkSync storage contract /// @author Matter Labs contract Storage { /// @dev Flag indicates that upgrade preparation status is active /// @dev Will store false in case of not active upgrade mode bool internal upgradePreparationActive; /// @dev Upgrade preparation activation timestamp (as seconds since unix epoch) /// @dev Will be equal to zero in case of not active upgrade mode uint256 internal upgradePreparationActivationTime; /// @dev Verifier contract. Used to verify block proof and exit proof Verifier internal verifier; /// @dev Governance contract. Contains the governor (the owner) of whole system, validators list, possible tokens list Governance internal governance; uint8 internal constant FILLED_GAS_RESERVE_VALUE = 0xff; // we use it to set gas revert value so slot will not be emptied with 0 balance struct PendingBalance { uint128 balanceToWithdraw; uint8 gasReserveValue; // gives user opportunity to fill storage slot with nonzero value } /// @dev Root-chain balances (per owner and token id, see packAddressAndTokenId) to withdraw mapping(bytes22 => PendingBalance) internal pendingBalances; // @dev Pending withdrawals are not used in this version struct PendingWithdrawalDEPRECATED { address to; uint16 tokenId; } mapping(uint32 => PendingWithdrawalDEPRECATED) internal pendingWithdrawalsDEPRECATED; uint32 internal firstPendingWithdrawalIndexDEPRECATED; uint32 internal numberOfPendingWithdrawalsDEPRECATED; /// @dev Total number of executed blocks i.e. blocks[totalBlocksExecuted] points at the latest executed block (block 0 is genesis) uint32 public totalBlocksExecuted; /// @notice Total number of committed blocks i.e. blocks[totalBlocksCommitted] points at the latest committed block uint32 public totalBlocksCommitted; /// @Old rollup block stored data - not used in current version /// @member validator Block producer /// @member committedAtBlock ETH block number at which this block was committed /// @member cumulativeOnchainOperations Total number of operations in this and all previous blocks /// @member priorityOperations Total number of priority operations for this block /// @member commitment Hash of the block circuit commitment /// @member stateRoot New tree root hash /// /// Consider memory alignment when changing field order: https://solidity.readthedocs.io/en/v0.4.21/miscellaneous.html struct BlockDEPRECATED { uint32 committedAtBlock; uint64 priorityOperations; uint32 chunks; bytes32 withdrawalsDataHash; // can be restricted to 16 bytes to reduce number of required storage slots bytes32 commitment; bytes32 stateRoot; } mapping(uint32 => BlockDEPRECATED) internal blocksDEPRECATED; /// @dev Flag indicates that a user has exited in the exodus mode certain token balance (per account id and tokenId) mapping(uint32 => mapping(uint32 => bool)) internal performedExodus; /// @dev Flag indicates that exodus (mass exit) mode is triggered /// @dev Once it was raised, it can not be cleared again, and all users must exit bool public exodusMode; /// @dev User authenticated fact hashes for some nonce. mapping(address => mapping(uint32 => bytes32)) public authFacts; /// @notice Old Priority Operation container /// @member opType Priority operation type /// @member pubData Priority operation public data /// @member expirationBlock Expiration block number (ETH block) for this request (must be satisfied before) struct PriorityOperationDEPRECATED { Operations.OpType opType; bytes pubData; uint256 expirationBlock; } /// @dev Priority Requests mapping (request id - operation) /// @dev Contains op type, pubdata and expiration block of unsatisfied requests. /// @dev Numbers are in order of requests receiving mapping(uint64 => PriorityOperationDEPRECATED) internal priorityRequestsDEPRECATED; /// @dev First open priority request id uint64 public firstPriorityRequestId; /// @dev Total number of requests uint64 public totalOpenPriorityRequests; /// @dev Total number of committed requests. /// @dev Used in checks: if the request matches the operation on Rollup contract and if provided number of requests is not too big uint64 internal totalCommittedPriorityRequests; /// @notice Packs address and token id into single word to use as a key in balances mapping function packAddressAndTokenId(address _address, uint16 _tokenId) internal pure returns (bytes22) { return bytes22((uint176(_address) | (uint176(_tokenId) << 160))); } /// @Rollup block stored data /// @member blockNumber Rollup block number /// @member priorityOperations Number of priority operations processed /// @member pendingOnchainOperationsHash Hash of all operations that must be processed after verify /// @member timestamp Rollup block timestamp, have the same format as Ethereum block constant /// @member stateHash Root hash of the rollup state /// @member commitment Verified input for the zkSync circuit struct StoredBlockInfo { uint32 blockNumber; uint64 priorityOperations; bytes32 pendingOnchainOperationsHash; uint256 timestamp; bytes32 stateHash; bytes32 commitment; } /// @notice Returns the keccak hash of the ABI-encoded StoredBlockInfo function hashStoredBlockInfo(StoredBlockInfo memory _storedBlockInfo) internal pure returns (bytes32) { return keccak256(abi.encode(_storedBlockInfo)); } /// @dev Stored hashed StoredBlockInfo for some block number mapping(uint32 => bytes32) public storedBlockHashes; /// @dev Total blocks proven. uint32 public totalBlocksProven; /// @notice Priority Operation container /// @member hashedPubData Hashed priority operation public data /// @member expirationBlock Expiration block number (ETH block) for this request (must be satisfied before) /// @member opType Priority operation type struct PriorityOperation { bytes20 hashedPubData; uint64 expirationBlock; Operations.OpType opType; } /// @dev Priority Requests mapping (request id - operation) /// @dev Contains op type, pubdata and expiration block of unsatisfied requests. /// @dev Numbers are in order of requests receiving mapping(uint64 => PriorityOperation) internal priorityRequests; /// @dev Timer for authFacts entry reset (address, nonce -> timer). /// @dev Used when user wants to reset `authFacts` for some nonce. mapping(address => mapping(uint32 => uint256)) internal authFactsResetTimer; mapping(uint32 => address) internal withdrawnNFTs; mapping(uint32 => Operations.WithdrawNFT) internal pendingWithdrawnNFTs; AdditionalZkSync internal additionalZkSync; /// @dev Upgrade notice period, possibly shorten by the security council uint256 internal approvedUpgradeNoticePeriod; /// @dev Upgrade start timestamp (as seconds since unix epoch) /// @dev Will be equal to zero in case of not active upgrade mode uint256 internal upgradeStartTimestamp; /// @dev Stores boolean flags which means the confirmations of the upgrade for each member of security council /// @dev Will store zeroes in case of not active upgrade mode mapping(uint256 => bool) internal securityCouncilApproves; uint256 internal numberOfApprovalsFromSecurityCouncil; } pragma solidity ^0.7.0; // SPDX-License-Identifier: MIT OR Apache-2.0 /// @title zkSync configuration constants /// @author Matter Labs contract Config { /// @dev ERC20 tokens and ETH withdrawals gas limit, used only for complete withdrawals uint256 internal constant WITHDRAWAL_GAS_LIMIT = 100000; /// @dev NFT withdrawals gas limit, used only for complete withdrawals uint256 internal constant WITHDRAWAL_NFT_GAS_LIMIT = 300000; /// @dev Bytes in one chunk uint8 internal constant CHUNK_BYTES = 10; /// @dev zkSync address length uint8 internal constant ADDRESS_BYTES = 20; uint8 internal constant PUBKEY_HASH_BYTES = 20; /// @dev Public key bytes length uint8 internal constant PUBKEY_BYTES = 32; /// @dev Ethereum signature r/s bytes length uint8 internal constant ETH_SIGN_RS_BYTES = 32; /// @dev Success flag bytes length uint8 internal constant SUCCESS_FLAG_BYTES = 1; /// @dev Max amount of tokens registered in the network (excluding ETH, which is hardcoded as tokenId = 0) uint16 internal constant MAX_AMOUNT_OF_REGISTERED_TOKENS = 1023; /// @dev Max account id that could be registered in the network uint32 internal constant MAX_ACCOUNT_ID = 16777215; /// @dev Expected average period of block creation uint256 internal constant BLOCK_PERIOD = 15 seconds; /// @dev ETH blocks verification expectation /// @dev Blocks can be reverted if they are not verified for at least EXPECT_VERIFICATION_IN. /// @dev If set to 0 validator can revert blocks at any time. uint256 internal constant EXPECT_VERIFICATION_IN = 0 hours / BLOCK_PERIOD; uint256 internal constant NOOP_BYTES = 1 * CHUNK_BYTES; uint256 internal constant DEPOSIT_BYTES = 6 * CHUNK_BYTES; uint256 internal constant MINT_NFT_BYTES = 5 * CHUNK_BYTES; uint256 internal constant TRANSFER_TO_NEW_BYTES = 6 * CHUNK_BYTES; uint256 internal constant PARTIAL_EXIT_BYTES = 6 * CHUNK_BYTES; uint256 internal constant TRANSFER_BYTES = 2 * CHUNK_BYTES; uint256 internal constant FORCED_EXIT_BYTES = 6 * CHUNK_BYTES; uint256 internal constant WITHDRAW_NFT_BYTES = 10 * CHUNK_BYTES; /// @dev Full exit operation length uint256 internal constant FULL_EXIT_BYTES = 11 * CHUNK_BYTES; /// @dev ChangePubKey operation length uint256 internal constant CHANGE_PUBKEY_BYTES = 6 * CHUNK_BYTES; /// @dev Expiration delta for priority request to be satisfied (in seconds) /// @dev NOTE: Priority expiration should be > (EXPECT_VERIFICATION_IN * BLOCK_PERIOD) /// @dev otherwise incorrect block with priority op could not be reverted. uint256 internal constant PRIORITY_EXPIRATION_PERIOD = 3 days; /// @dev Expiration delta for priority request to be satisfied (in ETH blocks) uint256 internal constant PRIORITY_EXPIRATION = PRIORITY_EXPIRATION_PERIOD/BLOCK_PERIOD; /// @dev Maximum number of priority request to clear during verifying the block /// @dev Cause deleting storage slots cost 5k gas per each slot it's unprofitable to clear too many slots /// @dev Value based on the assumption of ~750k gas cost of verifying and 5 used storage slots per PriorityOperation structure uint64 internal constant MAX_PRIORITY_REQUESTS_TO_DELETE_IN_VERIFY = 6; /// @dev Reserved time for users to send full exit priority operation in case of an upgrade (in seconds) uint256 internal constant MASS_FULL_EXIT_PERIOD = 9 days; /// @dev Reserved time for users to withdraw funds from full exit priority operation in case of an upgrade (in seconds) uint256 internal constant TIME_TO_WITHDRAW_FUNDS_FROM_FULL_EXIT = 2 days; /// @dev Notice period before activation preparation status of upgrade mode (in seconds) /// @dev NOTE: we must reserve for users enough time to send full exit operation, wait maximum time for processing this operation and withdraw funds from it. uint256 internal constant UPGRADE_NOTICE_PERIOD = MASS_FULL_EXIT_PERIOD+PRIORITY_EXPIRATION_PERIOD+TIME_TO_WITHDRAW_FUNDS_FROM_FULL_EXIT; /// @dev Timestamp - seconds since unix epoch uint256 internal constant COMMIT_TIMESTAMP_NOT_OLDER = 24 hours; /// @dev Maximum available error between real commit block timestamp and analog used in the verifier (in seconds) /// @dev Must be used cause miner's `block.timestamp` value can differ on some small value (as we know - 15 seconds) uint256 internal constant COMMIT_TIMESTAMP_APPROXIMATION_DELTA = 15 minutes; /// @dev Bit mask to apply for verifier public input before verifying. uint256 internal constant INPUT_MASK = 14474011154664524427946373126085988481658748083205070504932198000989141204991; /// @dev Auth fact reset timelock. uint256 internal constant AUTH_FACT_RESET_TIMELOCK = 1 days; /// @dev Max deposit of ERC20 token that is possible to deposit uint128 internal constant MAX_DEPOSIT_AMOUNT = 20282409603651670423947251286015; uint32 internal constant SPECIAL_ACCOUNT_ID = 16777215; address internal constant SPECIAL_ACCOUNT_ADDRESS = address(0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF); uint32 internal constant SPECIAL_NFT_TOKEN_ID = 2147483646; uint32 internal constant MAX_FUNGIBLE_TOKEN_ID = 65535; uint256 internal constant SECURITY_COUNCIL_MEMBERS_NUMBER = 15; } pragma solidity ^0.7.0; // SPDX-License-Identifier: MIT OR Apache-2.0 import "./Upgradeable.sol"; import "./Operations.sol"; /// @title zkSync events /// @author Matter Labs interface Events { /// @notice Event emitted when a block is committed event BlockCommit(uint32 indexed blockNumber); /// @notice Event emitted when a block is verified event BlockVerification(uint32 indexed blockNumber); /// @notice Event emitted when user funds are withdrawn from the zkSync contract event Withdrawal(uint16 indexed tokenId, uint128 amount); /// @notice Event emitted when user NFT is withdrawn from the zkSync contract event WithdrawalNFT(uint32 indexed tokenId); /// @notice Event emitted when user funds are deposited to the zkSync contract event Deposit(uint16 indexed tokenId, uint128 amount); /// @notice Event emitted when user sends a authentication fact (e.g. pub-key hash) event FactAuth(address indexed sender, uint32 nonce, bytes fact); /// @notice Event emitted when blocks are reverted event BlocksRevert(uint32 totalBlocksVerified, uint32 totalBlocksCommitted); /// @notice Exodus mode entered event event ExodusMode(); /// @notice New priority request event. Emitted when a request is placed into mapping event NewPriorityRequest( address sender, uint64 serialId, Operations.OpType opType, bytes pubData, uint256 expirationBlock ); /// @notice Deposit committed event. event DepositCommit( uint32 indexed zkSyncBlockId, uint32 indexed accountId, address owner, uint16 indexed tokenId, uint128 amount ); /// @notice Full exit committed event. event FullExitCommit( uint32 indexed zkSyncBlockId, uint32 indexed accountId, address owner, uint16 indexed tokenId, uint128 amount ); /// @notice Notice period changed event NoticePeriodChange(uint256 newNoticePeriod); } /// @title Upgrade events /// @author Matter Labs interface UpgradeEvents { /// @notice Event emitted when new upgradeable contract is added to upgrade gatekeeper's list of managed contracts event NewUpgradable(uint256 indexed versionId, address indexed upgradeable); /// @notice Upgrade mode enter event event NoticePeriodStart( uint256 indexed versionId, address[] newTargets, uint256 noticePeriod // notice period (in seconds) ); /// @notice Upgrade mode cancel event event UpgradeCancel(uint256 indexed versionId); /// @notice Upgrade mode preparation status event event PreparationStart(uint256 indexed versionId); /// @notice Upgrade mode complete event event UpgradeComplete(uint256 indexed versionId, address[] newTargets); } pragma solidity ^0.7.0; // SPDX-License-Identifier: MIT OR Apache-2.0 // Functions named bytesToX, except bytesToBytes20, where X is some type of size N < 32 (size of one word) // implements the following algorithm: // f(bytes memory input, uint offset) -> X out // where byte representation of out is N bytes from input at the given offset // 1) We compute memory location of the word W such that last N bytes of W is input[offset..offset+N] // W_address = input + 32 (skip stored length of bytes) + offset - (32 - N) == input + offset + N // 2) We load W from memory into out, last N bytes of W are placed into out library Bytes { function toBytesFromUInt16(uint16 self) internal pure returns (bytes memory _bts) { return toBytesFromUIntTruncated(uint256(self), 2); } function toBytesFromUInt24(uint24 self) internal pure returns (bytes memory _bts) { return toBytesFromUIntTruncated(uint256(self), 3); } function toBytesFromUInt32(uint32 self) internal pure returns (bytes memory _bts) { return toBytesFromUIntTruncated(uint256(self), 4); } function toBytesFromUInt128(uint128 self) internal pure returns (bytes memory _bts) { return toBytesFromUIntTruncated(uint256(self), 16); } // Copies 'len' lower bytes from 'self' into a new 'bytes memory'. // Returns the newly created 'bytes memory'. The returned bytes will be of length 'len'. function toBytesFromUIntTruncated(uint256 self, uint8 byteLength) private pure returns (bytes memory bts) { require(byteLength <= 32, "Q"); bts = new bytes(byteLength); // Even though the bytes will allocate a full word, we don't want // any potential garbage bytes in there. uint256 data = self << ((32 - byteLength) * 8); assembly { mstore( add(bts, 32), // BYTES_HEADER_SIZE data ) } } // Copies 'self' into a new 'bytes memory'. // Returns the newly created 'bytes memory'. The returned bytes will be of length '20'. function toBytesFromAddress(address self) internal pure returns (bytes memory bts) { bts = toBytesFromUIntTruncated(uint256(self), 20); } // See comment at the top of this file for explanation of how this function works. // NOTE: theoretically possible overflow of (_start + 20) function bytesToAddress(bytes memory self, uint256 _start) internal pure returns (address addr) { uint256 offset = _start + 20; require(self.length >= offset, "R"); assembly { addr := mload(add(self, offset)) } } // Reasoning about why this function works is similar to that of other similar functions, except NOTE below. // NOTE: that bytes1..32 is stored in the beginning of the word unlike other primitive types // NOTE: theoretically possible overflow of (_start + 20) function bytesToBytes20(bytes memory self, uint256 _start) internal pure returns (bytes20 r) { require(self.length >= (_start + 20), "S"); assembly { r := mload(add(add(self, 0x20), _start)) } } // See comment at the top of this file for explanation of how this function works. // NOTE: theoretically possible overflow of (_start + 0x2) function bytesToUInt16(bytes memory _bytes, uint256 _start) internal pure returns (uint16 r) { uint256 offset = _start + 0x2; require(_bytes.length >= offset, "T"); assembly { r := mload(add(_bytes, offset)) } } // See comment at the top of this file for explanation of how this function works. // NOTE: theoretically possible overflow of (_start + 0x3) function bytesToUInt24(bytes memory _bytes, uint256 _start) internal pure returns (uint24 r) { uint256 offset = _start + 0x3; require(_bytes.length >= offset, "U"); assembly { r := mload(add(_bytes, offset)) } } // NOTE: theoretically possible overflow of (_start + 0x4) function bytesToUInt32(bytes memory _bytes, uint256 _start) internal pure returns (uint32 r) { uint256 offset = _start + 0x4; require(_bytes.length >= offset, "V"); assembly { r := mload(add(_bytes, offset)) } } // NOTE: theoretically possible overflow of (_start + 0x10) function bytesToUInt128(bytes memory _bytes, uint256 _start) internal pure returns (uint128 r) { uint256 offset = _start + 0x10; require(_bytes.length >= offset, "W"); assembly { r := mload(add(_bytes, offset)) } } // See comment at the top of this file for explanation of how this function works. // NOTE: theoretically possible overflow of (_start + 0x14) function bytesToUInt160(bytes memory _bytes, uint256 _start) internal pure returns (uint160 r) { uint256 offset = _start + 0x14; require(_bytes.length >= offset, "X"); assembly { r := mload(add(_bytes, offset)) } } // NOTE: theoretically possible overflow of (_start + 0x20) function bytesToBytes32(bytes memory _bytes, uint256 _start) internal pure returns (bytes32 r) { uint256 offset = _start + 0x20; require(_bytes.length >= offset, "Y"); assembly { r := mload(add(_bytes, offset)) } } // Original source code: https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol#L228 // Get slice from bytes arrays // Returns the newly created 'bytes memory' // NOTE: theoretically possible overflow of (_start + _length) function slice( bytes memory _bytes, uint256 _start, uint256 _length ) internal pure returns (bytes memory) { require(_bytes.length >= (_start + _length), "Z"); // bytes length is less then start byte + length bytes bytes memory tempBytes = new bytes(_length); if (_length != 0) { assembly { let slice_curr := add(tempBytes, 0x20) let slice_end := add(slice_curr, _length) for { let array_current := add(_bytes, add(_start, 0x20)) } lt(slice_curr, slice_end) { slice_curr := add(slice_curr, 0x20) array_current := add(array_current, 0x20) } { mstore(slice_curr, mload(array_current)) } } } return tempBytes; } /// Reads byte stream /// @return newOffset - offset + amount of bytes read /// @return data - actually read data // NOTE: theoretically possible overflow of (_offset + _length) function read( bytes memory _data, uint256 _offset, uint256 _length ) internal pure returns (uint256 newOffset, bytes memory data) { data = slice(_data, _offset, _length); newOffset = _offset + _length; } // NOTE: theoretically possible overflow of (_offset + 1) function readBool(bytes memory _data, uint256 _offset) internal pure returns (uint256 newOffset, bool r) { newOffset = _offset + 1; r = uint8(_data[_offset]) != 0; } // NOTE: theoretically possible overflow of (_offset + 1) function readUint8(bytes memory _data, uint256 _offset) internal pure returns (uint256 newOffset, uint8 r) { newOffset = _offset + 1; r = uint8(_data[_offset]); } // NOTE: theoretically possible overflow of (_offset + 2) function readUInt16(bytes memory _data, uint256 _offset) internal pure returns (uint256 newOffset, uint16 r) { newOffset = _offset + 2; r = bytesToUInt16(_data, _offset); } // NOTE: theoretically possible overflow of (_offset + 3) function readUInt24(bytes memory _data, uint256 _offset) internal pure returns (uint256 newOffset, uint24 r) { newOffset = _offset + 3; r = bytesToUInt24(_data, _offset); } // NOTE: theoretically possible overflow of (_offset + 4) function readUInt32(bytes memory _data, uint256 _offset) internal pure returns (uint256 newOffset, uint32 r) { newOffset = _offset + 4; r = bytesToUInt32(_data, _offset); } // NOTE: theoretically possible overflow of (_offset + 16) function readUInt128(bytes memory _data, uint256 _offset) internal pure returns (uint256 newOffset, uint128 r) { newOffset = _offset + 16; r = bytesToUInt128(_data, _offset); } // NOTE: theoretically possible overflow of (_offset + 20) function readUInt160(bytes memory _data, uint256 _offset) internal pure returns (uint256 newOffset, uint160 r) { newOffset = _offset + 20; r = bytesToUInt160(_data, _offset); } // NOTE: theoretically possible overflow of (_offset + 20) function readAddress(bytes memory _data, uint256 _offset) internal pure returns (uint256 newOffset, address r) { newOffset = _offset + 20; r = bytesToAddress(_data, _offset); } // NOTE: theoretically possible overflow of (_offset + 20) function readBytes20(bytes memory _data, uint256 _offset) internal pure returns (uint256 newOffset, bytes20 r) { newOffset = _offset + 20; r = bytesToBytes20(_data, _offset); } // NOTE: theoretically possible overflow of (_offset + 32) function readBytes32(bytes memory _data, uint256 _offset) internal pure returns (uint256 newOffset, bytes32 r) { newOffset = _offset + 32; r = bytesToBytes32(_data, _offset); } /// Trim bytes into single word function trim(bytes memory _data, uint256 _newLength) internal pure returns (uint256 r) { require(_newLength <= 0x20, "10"); // new_length is longer than word require(_data.length >= _newLength, "11"); // data is to short uint256 a; assembly { a := mload(add(_data, 0x20)) // load bytes into uint256 } return a >> ((0x20 - _newLength) * 8); } // Helper function for hex conversion. function halfByteToHex(bytes1 _byte) internal pure returns (bytes1 _hexByte) { require(uint8(_byte) < 0x10, "hbh11"); // half byte's value is out of 0..15 range. // "FEDCBA9876543210" ASCII-encoded, shifted and automatically truncated. return bytes1(uint8(0x66656463626139383736353433323130 >> (uint8(_byte) * 8))); } // Convert bytes to ASCII hex representation function bytesToHexASCIIBytes(bytes memory _input) internal pure returns (bytes memory _output) { bytes memory outStringBytes = new bytes(_input.length * 2); // code in `assembly` construction is equivalent of the next code: // for (uint i = 0; i < _input.length; ++i) { // outStringBytes[i*2] = halfByteToHex(_input[i] >> 4); // outStringBytes[i*2+1] = halfByteToHex(_input[i] & 0x0f); // } assembly { let input_curr := add(_input, 0x20) let input_end := add(input_curr, mload(_input)) for { let out_curr := add(outStringBytes, 0x20) } lt(input_curr, input_end) { input_curr := add(input_curr, 0x01) out_curr := add(out_curr, 0x02) } { let curr_input_byte := shr(0xf8, mload(input_curr)) // here outStringByte from each half of input byte calculates by the next: // // "FEDCBA9876543210" ASCII-encoded, shifted and automatically truncated. // outStringByte = byte (uint8 (0x66656463626139383736353433323130 >> (uint8 (_byteHalf) * 8))) mstore( out_curr, shl(0xf8, shr(mul(shr(0x04, curr_input_byte), 0x08), 0x66656463626139383736353433323130)) ) mstore( add(out_curr, 0x01), shl(0xf8, shr(mul(and(0x0f, curr_input_byte), 0x08), 0x66656463626139383736353433323130)) ) } } return outStringBytes; } } pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; // SPDX-License-Identifier: MIT OR Apache-2.0 import "./Bytes.sol"; import "./Utils.sol"; /// @title zkSync operations tools library Operations { // Circuit ops and their pubdata (chunks * bytes) /// @notice zkSync circuit operation type enum OpType { Noop, Deposit, TransferToNew, PartialExit, _CloseAccount, // used for correct op id offset Transfer, FullExit, ChangePubKey, ForcedExit, MintNFT, WithdrawNFT, Swap } // Byte lengths uint8 internal constant OP_TYPE_BYTES = 1; uint8 internal constant TOKEN_BYTES = 4; uint8 internal constant PUBKEY_BYTES = 32; uint8 internal constant NONCE_BYTES = 4; uint8 internal constant PUBKEY_HASH_BYTES = 20; uint8 internal constant ADDRESS_BYTES = 20; uint8 internal constant CONTENT_HASH_BYTES = 32; /// @dev Packed fee bytes lengths uint8 internal constant FEE_BYTES = 2; /// @dev zkSync account id bytes lengths uint8 internal constant ACCOUNT_ID_BYTES = 4; /// @dev zkSync nft serial id bytes lengths uint8 internal constant NFT_SERIAL_ID_BYTES = 4; uint8 internal constant AMOUNT_BYTES = 16; /// @dev Signature (for example full exit signature) bytes length uint8 internal constant SIGNATURE_BYTES = 64; // Deposit pubdata struct Deposit { // uint8 opType uint32 accountId; uint32 tokenId; uint128 amount; address owner; } uint256 internal constant PACKED_DEPOSIT_PUBDATA_BYTES = OP_TYPE_BYTES + ACCOUNT_ID_BYTES + TOKEN_BYTES + AMOUNT_BYTES + ADDRESS_BYTES; /// Deserialize deposit pubdata function readDepositPubdata(bytes memory _data) internal pure returns (Deposit memory parsed) { // NOTE: there is no check that variable sizes are same as constants (i.e. TOKEN_BYTES), fix if possible. uint256 offset = OP_TYPE_BYTES; (offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId (offset, parsed.tokenId) = Bytes.readUInt32(_data, offset); // tokenId (offset, parsed.amount) = Bytes.readUInt128(_data, offset); // amount (offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner require(offset == PACKED_DEPOSIT_PUBDATA_BYTES, "N"); // reading invalid deposit pubdata size } /// Serialize deposit pubdata function writeDepositPubdataForPriorityQueue(Deposit memory op) internal pure returns (bytes memory buf) { buf = abi.encodePacked( uint8(OpType.Deposit), bytes4(0), // accountId (ignored) (update when ACCOUNT_ID_BYTES is changed) op.tokenId, // tokenId op.amount, // amount op.owner // owner ); } /// @notice Write deposit pubdata for priority queue check. function checkDepositInPriorityQueue(Deposit memory op, bytes20 hashedPubdata) internal pure returns (bool) { return Utils.hashBytesToBytes20(writeDepositPubdataForPriorityQueue(op)) == hashedPubdata; } // FullExit pubdata struct FullExit { // uint8 opType uint32 accountId; address owner; uint32 tokenId; uint128 amount; uint32 nftCreatorAccountId; address nftCreatorAddress; uint32 nftSerialId; bytes32 nftContentHash; } uint256 public constant PACKED_FULL_EXIT_PUBDATA_BYTES = OP_TYPE_BYTES + ACCOUNT_ID_BYTES + ADDRESS_BYTES + TOKEN_BYTES + AMOUNT_BYTES + ACCOUNT_ID_BYTES + ADDRESS_BYTES + NFT_SERIAL_ID_BYTES + CONTENT_HASH_BYTES; function readFullExitPubdata(bytes memory _data) internal pure returns (FullExit memory parsed) { // NOTE: there is no check that variable sizes are same as constants (i.e. TOKEN_BYTES), fix if possible. uint256 offset = OP_TYPE_BYTES; (offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId (offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner (offset, parsed.tokenId) = Bytes.readUInt32(_data, offset); // tokenId (offset, parsed.amount) = Bytes.readUInt128(_data, offset); // amount (offset, parsed.nftCreatorAccountId) = Bytes.readUInt32(_data, offset); // nftCreatorAccountId (offset, parsed.nftCreatorAddress) = Bytes.readAddress(_data, offset); // nftCreatorAddress (offset, parsed.nftSerialId) = Bytes.readUInt32(_data, offset); // nftSerialId (offset, parsed.nftContentHash) = Bytes.readBytes32(_data, offset); // nftContentHash require(offset == PACKED_FULL_EXIT_PUBDATA_BYTES, "O"); // reading invalid full exit pubdata size } function writeFullExitPubdataForPriorityQueue(FullExit memory op) internal pure returns (bytes memory buf) { buf = abi.encodePacked( uint8(OpType.FullExit), op.accountId, // accountId op.owner, // owner op.tokenId, // tokenId uint128(0), // amount -- ignored uint32(0), // nftCreatorAccountId -- ignored address(0), // nftCreatorAddress -- ignored uint32(0), // nftSerialId -- ignored bytes32(0) // nftContentHash -- ignored ); } function checkFullExitInPriorityQueue(FullExit memory op, bytes20 hashedPubdata) internal pure returns (bool) { return Utils.hashBytesToBytes20(writeFullExitPubdataForPriorityQueue(op)) == hashedPubdata; } // PartialExit pubdata struct PartialExit { //uint8 opType; -- present in pubdata, ignored at serialization //uint32 accountId; -- present in pubdata, ignored at serialization uint32 tokenId; uint128 amount; //uint16 fee; -- present in pubdata, ignored at serialization address owner; } function readPartialExitPubdata(bytes memory _data) internal pure returns (PartialExit memory parsed) { // NOTE: there is no check that variable sizes are same as constants (i.e. TOKEN_BYTES), fix if possible. uint256 offset = OP_TYPE_BYTES + ACCOUNT_ID_BYTES; // opType + accountId (ignored) (offset, parsed.tokenId) = Bytes.readUInt32(_data, offset); // tokenId (offset, parsed.amount) = Bytes.readUInt128(_data, offset); // amount offset += FEE_BYTES; // fee (ignored) (offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner } // ForcedExit pubdata struct ForcedExit { //uint8 opType; -- present in pubdata, ignored at serialization //uint32 initiatorAccountId; -- present in pubdata, ignored at serialization //uint32 targetAccountId; -- present in pubdata, ignored at serialization uint32 tokenId; uint128 amount; //uint16 fee; -- present in pubdata, ignored at serialization address target; } function readForcedExitPubdata(bytes memory _data) internal pure returns (ForcedExit memory parsed) { // NOTE: there is no check that variable sizes are same as constants (i.e. TOKEN_BYTES), fix if possible. uint256 offset = OP_TYPE_BYTES + ACCOUNT_ID_BYTES * 2; // opType + initiatorAccountId + targetAccountId (ignored) (offset, parsed.tokenId) = Bytes.readUInt32(_data, offset); // tokenId (offset, parsed.amount) = Bytes.readUInt128(_data, offset); // amount offset += FEE_BYTES; // fee (ignored) (offset, parsed.target) = Bytes.readAddress(_data, offset); // target } // ChangePubKey enum ChangePubkeyType {ECRECOVER, CREATE2, OldECRECOVER} struct ChangePubKey { // uint8 opType; -- present in pubdata, ignored at serialization uint32 accountId; bytes20 pubKeyHash; address owner; uint32 nonce; //uint32 tokenId; -- present in pubdata, ignored at serialization //uint16 fee; -- present in pubdata, ignored at serialization } function readChangePubKeyPubdata(bytes memory _data) internal pure returns (ChangePubKey memory parsed) { uint256 offset = OP_TYPE_BYTES; (offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId (offset, parsed.pubKeyHash) = Bytes.readBytes20(_data, offset); // pubKeyHash (offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner (offset, parsed.nonce) = Bytes.readUInt32(_data, offset); // nonce } struct WithdrawNFT { //uint8 opType; -- present in pubdata, ignored at serialization //uint32 accountId; -- present in pubdata, ignored at serialization uint32 creatorAccountId; address creatorAddress; uint32 serialId; bytes32 contentHash; address receiver; uint32 tokenId; //uint32 feeTokenId; //uint16 fee; -- present in pubdata, ignored at serialization } function readWithdrawNFTPubdata(bytes memory _data) internal pure returns (WithdrawNFT memory parsed) { uint256 offset = OP_TYPE_BYTES + ACCOUNT_ID_BYTES; // opType + accountId (ignored) (offset, parsed.creatorAccountId) = Bytes.readUInt32(_data, offset); (offset, parsed.creatorAddress) = Bytes.readAddress(_data, offset); (offset, parsed.serialId) = Bytes.readUInt32(_data, offset); (offset, parsed.contentHash) = Bytes.readBytes32(_data, offset); (offset, parsed.receiver) = Bytes.readAddress(_data, offset); (offset, parsed.tokenId) = Bytes.readUInt32(_data, offset); } } pragma solidity ^0.7.0; // SPDX-License-Identifier: MIT OR Apache-2.0 /// @title Interface of the upgradeable master contract (defines notice period duration and allows finish upgrade during preparation of it) /// @author Matter Labs interface UpgradeableMaster { /// @notice Notice period before activation preparation status of upgrade mode function getNoticePeriod() external returns (uint256); /// @notice Notifies contract that notice period started function upgradeNoticePeriodStarted() external; /// @notice Notifies contract that upgrade preparation status is activated function upgradePreparationStarted() external; /// @notice Notifies contract that upgrade canceled function upgradeCanceled() external; /// @notice Notifies contract that upgrade finishes function upgradeFinishes() external; /// @notice Checks that contract is ready for upgrade /// @return bool flag indicating that contract is ready for upgrade function isReadyForUpgrade() external returns (bool); } pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; // SPDX-License-Identifier: MIT OR Apache-2.0 import "./Ownable.sol"; import "./Config.sol"; /// @title Regenesis Multisig contract /// @author Matter Labs contract RegenesisMultisig is Ownable, Config { event CandidateAccepted(bytes32 oldRootHash, bytes32 newRootHash); event CandidateApproval(uint256 currentApproval); bytes32 public oldRootHash; bytes32 public newRootHash; bytes32 public candidateOldRootHash; bytes32 public candidateNewRootHash; /// @dev Stores boolean flags which means the confirmations of the upgrade for each member of security council mapping(uint256 => bool) internal securityCouncilApproves; uint256 internal numberOfApprovalsFromSecurityCouncil; uint256 securityCouncilThreshold; constructor(uint256 threshold) Ownable(msg.sender) { securityCouncilThreshold = threshold; } function submitHash(bytes32 _oldRootHash, bytes32 _newRootHash) external { // Only zkSync team can submit the hashes require(msg.sender == getMaster(), "1"); candidateOldRootHash = _oldRootHash; candidateNewRootHash = _newRootHash; oldRootHash = bytes32(0); newRootHash = bytes32(0); for (uint256 i = 0; i < SECURITY_COUNCIL_MEMBERS_NUMBER; ++i) { securityCouncilApproves[i] = false; } numberOfApprovalsFromSecurityCouncil = 0; } function approveHash(bytes32 _oldRootHash, bytes32 _newRootHash) external { require(_oldRootHash == candidateOldRootHash, "2"); require(_newRootHash == candidateNewRootHash, "3"); address payable[SECURITY_COUNCIL_MEMBERS_NUMBER] memory SECURITY_COUNCIL_MEMBERS = [0xa2602ea835E03fb39CeD30B43d6b6EAf6aDe1769,0x9D5d6D4BaCCEDf6ECE1883456AA785dc996df607,0x002A5dc50bbB8d5808e418Aeeb9F060a2Ca17346,0x71E805aB236c945165b9Cd0bf95B9f2F0A0488c3,0x76C6cE74EAb57254E785d1DcC3f812D274bCcB11,0xFBfF3FF69D65A9103Bf4fdBf988f5271D12B3190,0xAfC2F2D803479A2AF3A72022D54cc0901a0ec0d6,0x4d1E3089042Ab3A93E03CA88B566b99Bd22438C6,0x19eD6cc20D44e5cF4Bb4894F50162F72402d8567,0x39415255619783A2E71fcF7d8f708A951d92e1b6,0x399a6a13D298CF3F41a562966C1a450136Ea52C2,0xee8AE1F1B4B1E1956C8Bda27eeBCE54Cf0bb5eaB,0xe7CCD4F3feA7df88Cf9B59B30f738ec1E049231f,0xA093284c707e207C36E3FEf9e0B6325fd9d0e33B,0x225d3822De44E58eE935440E0c0B829C4232086e]; for (uint256 id = 0; id < SECURITY_COUNCIL_MEMBERS_NUMBER; ++id) { if (SECURITY_COUNCIL_MEMBERS[id] == msg.sender) { require(securityCouncilApproves[id] == false); securityCouncilApproves[id] = true; numberOfApprovalsFromSecurityCouncil++; emit CandidateApproval(numberOfApprovalsFromSecurityCouncil); // It is ok to check for strict equality since the numberOfApprovalsFromSecurityCouncil // is increased by one at a time. It is better to do so not to emit the // CandidateAccepted event more than once if (numberOfApprovalsFromSecurityCouncil == securityCouncilThreshold) { oldRootHash = candidateOldRootHash; newRootHash = candidateNewRootHash; emit CandidateAccepted(oldRootHash, newRootHash); } } } } } pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; // SPDX-License-Identifier: MIT OR Apache-2.0 import "./ReentrancyGuard.sol"; import "./SafeMath.sol"; import "./SafeMathUInt128.sol"; import "./SafeCast.sol"; import "./Utils.sol"; import "./Storage.sol"; import "./Config.sol"; import "./Events.sol"; import "./Bytes.sol"; import "./Operations.sol"; import "./UpgradeableMaster.sol"; /// @title zkSync additional main contract /// @author Matter Labs contract AdditionalZkSync is Storage, Config, Events, ReentrancyGuard { using SafeMath for uint256; using SafeMathUInt128 for uint128; function increaseBalanceToWithdraw(bytes22 _packedBalanceKey, uint128 _amount) internal { uint128 balance = pendingBalances[_packedBalanceKey].balanceToWithdraw; pendingBalances[_packedBalanceKey] = PendingBalance(balance.add(_amount), FILLED_GAS_RESERVE_VALUE); } /// @notice Withdraws token from ZkSync to root chain in case of exodus mode. User must provide proof that he owns funds /// @param _storedBlockInfo Last verified block /// @param _owner Owner of the account /// @param _accountId Id of the account in the tree /// @param _proof Proof /// @param _tokenId Verified token id /// @param _amount Amount for owner (must be total amount, not part of it) function performExodus( StoredBlockInfo memory _storedBlockInfo, address _owner, uint32 _accountId, uint32 _tokenId, uint128 _amount, uint32 _nftCreatorAccountId, address _nftCreatorAddress, uint32 _nftSerialId, bytes32 _nftContentHash, uint256[] memory _proof ) external { require(_accountId <= MAX_ACCOUNT_ID, "e"); require(_accountId != SPECIAL_ACCOUNT_ID, "v"); require(_tokenId < SPECIAL_NFT_TOKEN_ID, "T"); require(exodusMode, "s"); // must be in exodus mode require(!performedExodus[_accountId][_tokenId], "t"); // already exited require(storedBlockHashes[totalBlocksExecuted] == hashStoredBlockInfo(_storedBlockInfo), "u"); // incorrect stored block info bool proofCorrect = verifier.verifyExitProof( _storedBlockInfo.stateHash, _accountId, _owner, _tokenId, _amount, _nftCreatorAccountId, _nftCreatorAddress, _nftSerialId, _nftContentHash, _proof ); require(proofCorrect, "x"); if (_tokenId <= MAX_FUNGIBLE_TOKEN_ID) { bytes22 packedBalanceKey = packAddressAndTokenId(_owner, uint16(_tokenId)); increaseBalanceToWithdraw(packedBalanceKey, _amount); } else { require(_amount != 0, "Z"); // Unsupported nft amount Operations.WithdrawNFT memory withdrawNftOp = Operations.WithdrawNFT( _nftCreatorAccountId, _nftCreatorAddress, _nftSerialId, _nftContentHash, _owner, _tokenId ); pendingWithdrawnNFTs[_tokenId] = withdrawNftOp; } performedExodus[_accountId][_tokenId] = true; } function cancelOutstandingDepositsForExodusMode(uint64 _n, bytes[] memory _depositsPubdata) external { require(exodusMode, "8"); // exodus mode not active uint64 toProcess = Utils.minU64(totalOpenPriorityRequests, _n); require(toProcess > 0, "9"); // no deposits to process uint64 currentDepositIdx = 0; for (uint64 id = firstPriorityRequestId; id < firstPriorityRequestId + toProcess; id++) { if (priorityRequests[id].opType == Operations.OpType.Deposit) { bytes memory depositPubdata = _depositsPubdata[currentDepositIdx]; require(Utils.hashBytesToBytes20(depositPubdata) == priorityRequests[id].hashedPubData, "a"); ++currentDepositIdx; Operations.Deposit memory op = Operations.readDepositPubdata(depositPubdata); bytes22 packedBalanceKey = packAddressAndTokenId(op.owner, uint16(op.tokenId)); pendingBalances[packedBalanceKey].balanceToWithdraw += op.amount; } delete priorityRequests[id]; } firstPriorityRequestId += toProcess; totalOpenPriorityRequests -= toProcess; } uint256 internal constant SECURITY_COUNCIL_2_WEEKS_THRESHOLD = 8; uint256 internal constant SECURITY_COUNCIL_1_WEEK_THRESHOLD = 10; uint256 internal constant SECURITY_COUNCIL_3_DAYS_THRESHOLD = 12; function cutUpgradeNoticePeriod() external { address payable[SECURITY_COUNCIL_MEMBERS_NUMBER] memory SECURITY_COUNCIL_MEMBERS = [0xa2602ea835E03fb39CeD30B43d6b6EAf6aDe1769,0x9D5d6D4BaCCEDf6ECE1883456AA785dc996df607,0x002A5dc50bbB8d5808e418Aeeb9F060a2Ca17346,0x71E805aB236c945165b9Cd0bf95B9f2F0A0488c3,0x76C6cE74EAb57254E785d1DcC3f812D274bCcB11,0xFBfF3FF69D65A9103Bf4fdBf988f5271D12B3190,0xAfC2F2D803479A2AF3A72022D54cc0901a0ec0d6,0x4d1E3089042Ab3A93E03CA88B566b99Bd22438C6,0x19eD6cc20D44e5cF4Bb4894F50162F72402d8567,0x39415255619783A2E71fcF7d8f708A951d92e1b6,0x399a6a13D298CF3F41a562966C1a450136Ea52C2,0xee8AE1F1B4B1E1956C8Bda27eeBCE54Cf0bb5eaB,0xe7CCD4F3feA7df88Cf9B59B30f738ec1E049231f,0xA093284c707e207C36E3FEf9e0B6325fd9d0e33B,0x225d3822De44E58eE935440E0c0B829C4232086e]; for (uint256 id = 0; id < SECURITY_COUNCIL_MEMBERS_NUMBER; ++id) { if (SECURITY_COUNCIL_MEMBERS[id] == msg.sender) { require(upgradeStartTimestamp != 0); require(securityCouncilApproves[id] == false); securityCouncilApproves[id] = true; numberOfApprovalsFromSecurityCouncil++; if (numberOfApprovalsFromSecurityCouncil == SECURITY_COUNCIL_2_WEEKS_THRESHOLD) { if (approvedUpgradeNoticePeriod > 2 weeks) { approvedUpgradeNoticePeriod = 2 weeks; emit NoticePeriodChange(approvedUpgradeNoticePeriod); } } else if (numberOfApprovalsFromSecurityCouncil == SECURITY_COUNCIL_1_WEEK_THRESHOLD) { if (approvedUpgradeNoticePeriod > 1 weeks) { approvedUpgradeNoticePeriod = 1 weeks; emit NoticePeriodChange(approvedUpgradeNoticePeriod); } } else if (numberOfApprovalsFromSecurityCouncil == SECURITY_COUNCIL_3_DAYS_THRESHOLD) { if (approvedUpgradeNoticePeriod > 3 days) { approvedUpgradeNoticePeriod = 3 days; emit NoticePeriodChange(approvedUpgradeNoticePeriod); } } break; } } } /// @notice Set data for changing pubkey hash using onchain authorization. /// Transaction author (msg.sender) should be L2 account address /// @notice New pubkey hash can be reset, to do that user should send two transactions: /// 1) First `setAuthPubkeyHash` transaction for already used `_nonce` will set timer. /// 2) After `AUTH_FACT_RESET_TIMELOCK` time is passed second `setAuthPubkeyHash` transaction will reset pubkey hash for `_nonce`. /// @param _pubkeyHash New pubkey hash /// @param _nonce Nonce of the change pubkey L2 transaction function setAuthPubkeyHash(bytes calldata _pubkeyHash, uint32 _nonce) external { require(_pubkeyHash.length == PUBKEY_HASH_BYTES, "y"); // PubKeyHash should be 20 bytes. if (authFacts[msg.sender][_nonce] == bytes32(0)) { authFacts[msg.sender][_nonce] = keccak256(_pubkeyHash); } else { uint256 currentResetTimer = authFactsResetTimer[msg.sender][_nonce]; if (currentResetTimer == 0) { authFactsResetTimer[msg.sender][_nonce] = block.timestamp; } else { require(block.timestamp.sub(currentResetTimer) >= AUTH_FACT_RESET_TIMELOCK, "z"); authFactsResetTimer[msg.sender][_nonce] = 0; authFacts[msg.sender][_nonce] = keccak256(_pubkeyHash); } } } /// @notice Reverts unverified blocks function revertBlocks(StoredBlockInfo[] memory _blocksToRevert) external { governance.requireActiveValidator(msg.sender); uint32 blocksCommitted = totalBlocksCommitted; uint32 blocksToRevert = Utils.minU32(uint32(_blocksToRevert.length), blocksCommitted - totalBlocksExecuted); uint64 revertedPriorityRequests = 0; for (uint32 i = 0; i < blocksToRevert; ++i) { StoredBlockInfo memory storedBlockInfo = _blocksToRevert[i]; require(storedBlockHashes[blocksCommitted] == hashStoredBlockInfo(storedBlockInfo), "r"); // incorrect stored block info delete storedBlockHashes[blocksCommitted]; --blocksCommitted; revertedPriorityRequests += storedBlockInfo.priorityOperations; } totalBlocksCommitted = blocksCommitted; totalCommittedPriorityRequests -= revertedPriorityRequests; if (totalBlocksCommitted < totalBlocksProven) { totalBlocksProven = totalBlocksCommitted; } emit BlocksRevert(totalBlocksExecuted, blocksCommitted); } } pragma solidity ^0.7.0; // SPDX-License-Identifier: UNLICENSED /** * @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); } pragma solidity ^0.7.0; // SPDX-License-Identifier: MIT OR Apache-2.0 import "./Config.sol"; import "./Utils.sol"; import "./NFTFactory.sol"; import "./TokenGovernance.sol"; /// @title Governance Contract /// @author Matter Labs contract Governance is Config { /// @notice Token added to Franklin net event NewToken(address indexed token, uint16 indexed tokenId); /// @notice Default nft factory has set event SetDefaultNFTFactory(address indexed factory); /// @notice NFT factory registered new creator account event NFTFactoryRegisteredCreator( uint32 indexed creatorAccountId, address indexed creatorAddress, address factoryAddress ); /// @notice Governor changed event NewGovernor(address newGovernor); /// @notice Token Governance changed event NewTokenGovernance(TokenGovernance newTokenGovernance); /// @notice Validator's status changed event ValidatorStatusUpdate(address indexed validatorAddress, bool isActive); event TokenPausedUpdate(address indexed token, bool paused); /// @notice Address which will exercise governance over the network i.e. add tokens, change validator set, conduct upgrades address public networkGovernor; /// @notice Total number of ERC20 tokens registered in the network (excluding ETH, which is hardcoded as tokenId = 0) uint16 public totalTokens; /// @notice List of registered tokens by tokenId mapping(uint16 => address) public tokenAddresses; /// @notice List of registered tokens by address mapping(address => uint16) public tokenIds; /// @notice List of permitted validators mapping(address => bool) public validators; /// @notice Paused tokens list, deposits are impossible to create for paused tokens mapping(uint16 => bool) public pausedTokens; /// @notice Address that is authorized to add tokens to the Governance. TokenGovernance public tokenGovernance; /// @notice NFT Creator address to factory address mapping mapping(uint32 => mapping(address => NFTFactory)) public nftFactories; /// @notice Address which will be used if NFT token has no factories NFTFactory public defaultFactory; /// @notice Governance contract initialization. Can be external because Proxy contract intercepts illegal calls of this function. /// @param initializationParameters Encoded representation of initialization parameters: /// _networkGovernor The address of network governor function initialize(bytes calldata initializationParameters) external { address _networkGovernor = abi.decode(initializationParameters, (address)); networkGovernor = _networkGovernor; } /// @notice Governance contract upgrade. Can be external because Proxy contract intercepts illegal calls of this function. /// @param upgradeParameters Encoded representation of upgrade parameters // solhint-disable-next-line no-empty-blocks function upgrade(bytes calldata upgradeParameters) external {} /// @notice Change current governor /// @param _newGovernor Address of the new governor function changeGovernor(address _newGovernor) external { requireGovernor(msg.sender); if (networkGovernor != _newGovernor) { networkGovernor = _newGovernor; emit NewGovernor(_newGovernor); } } /// @notice Change current token governance /// @param _newTokenGovernance Address of the new token governor function changeTokenGovernance(TokenGovernance _newTokenGovernance) external { requireGovernor(msg.sender); if (tokenGovernance != _newTokenGovernance) { tokenGovernance = _newTokenGovernance; emit NewTokenGovernance(_newTokenGovernance); } } /// @notice Add token to the list of networks tokens /// @param _token Token address function addToken(address _token) external { require(msg.sender == address(tokenGovernance), "1E"); require(tokenIds[_token] == 0, "1e"); // token exists require(totalTokens < MAX_AMOUNT_OF_REGISTERED_TOKENS, "1f"); // no free identifiers for tokens totalTokens++; uint16 newTokenId = totalTokens; // it is not `totalTokens - 1` because tokenId = 0 is reserved for eth tokenAddresses[newTokenId] = _token; tokenIds[_token] = newTokenId; emit NewToken(_token, newTokenId); } /// @notice Pause token deposits for the given token /// @param _tokenAddr Token address /// @param _tokenPaused Token paused status function setTokenPaused(address _tokenAddr, bool _tokenPaused) external { requireGovernor(msg.sender); uint16 tokenId = this.validateTokenAddress(_tokenAddr); if (pausedTokens[tokenId] != _tokenPaused) { pausedTokens[tokenId] = _tokenPaused; emit TokenPausedUpdate(_tokenAddr, _tokenPaused); } } /// @notice Change validator status (active or not active) /// @param _validator Validator address /// @param _active Active flag function setValidator(address _validator, bool _active) external { requireGovernor(msg.sender); if (validators[_validator] != _active) { validators[_validator] = _active; emit ValidatorStatusUpdate(_validator, _active); } } /// @notice Check if specified address is is governor /// @param _address Address to check function requireGovernor(address _address) public view { require(_address == networkGovernor, "1g"); // only by governor } /// @notice Checks if validator is active /// @param _address Validator address function requireActiveValidator(address _address) external view { require(validators[_address], "1h"); // validator is not active } /// @notice Validate token id (must be less than or equal to total tokens amount) /// @param _tokenId Token id /// @return bool flag that indicates if token id is less than or equal to total tokens amount function isValidTokenId(uint16 _tokenId) external view returns (bool) { return _tokenId <= totalTokens; } /// @notice Validate token address /// @param _tokenAddr Token address /// @return tokens id function validateTokenAddress(address _tokenAddr) external view returns (uint16) { uint16 tokenId = tokenIds[_tokenAddr]; require(tokenId != 0, "1i"); // 0 is not a valid token return tokenId; } function packRegisterNFTFactoryMsg( uint32 _creatorAccountId, address _creatorAddress, address _factoryAddress ) internal pure returns (bytes memory) { return abi.encodePacked( "\x19Ethereum Signed Message:\n141", "\nCreator's account ID in zkSync: ", Bytes.bytesToHexASCIIBytes(abi.encodePacked((_creatorAccountId))), "\nCreator: ", Bytes.bytesToHexASCIIBytes(abi.encodePacked((_creatorAddress))), "\nFactory: ", Bytes.bytesToHexASCIIBytes(abi.encodePacked((_factoryAddress))) ); } /// @notice Register creator corresponding to the factory /// @param _creatorAccountId Creator's zkSync account ID /// @param _creatorAddress NFT creator address /// @param _signature Creator's signature function registerNFTFactoryCreator( uint32 _creatorAccountId, address _creatorAddress, bytes memory _signature ) external { require(address(nftFactories[_creatorAccountId][_creatorAddress]) == address(0), "Q"); bytes32 messageHash = keccak256(packRegisterNFTFactoryMsg(_creatorAccountId, _creatorAddress, msg.sender)); address recoveredAddress = Utils.recoverAddressFromEthSignature(_signature, messageHash); require(recoveredAddress == _creatorAddress && recoveredAddress != address(0), "ws"); nftFactories[_creatorAccountId][_creatorAddress] = NFTFactory(msg.sender); emit NFTFactoryRegisteredCreator(_creatorAccountId, _creatorAddress, msg.sender); } //@notice Set default factory for our contract. This factory will be used to mint an NFT token that has no factory //@param _factory Address of NFT factory function setDefaultNFTFactory(address _factory) external { requireGovernor(msg.sender); require(address(_factory) != address(0), "mb1"); // Factory should be non zero require(address(defaultFactory) == address(0), "mb2"); // NFTFactory is already set defaultFactory = NFTFactory(_factory); emit SetDefaultNFTFactory(_factory); } function getNFTFactory(uint32 _creatorAccountId, address _creatorAddress) external view returns (NFTFactory) { NFTFactory _factory = nftFactories[_creatorAccountId][_creatorAddress]; if (address(_factory) == address(0)) { require(address(defaultFactory) != address(0), "fs"); // NFTFactory does not set return defaultFactory; } else { return _factory; } } } pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; // SPDX-License-Identifier: MIT OR Apache-2.0 import "./KeysWithPlonkVerifier.sol"; import "./Config.sol"; // Hardcoded constants to avoid accessing store contract Verifier is KeysWithPlonkVerifier, KeysWithPlonkVerifierOld, Config { // solhint-disable-next-line no-empty-blocks function initialize(bytes calldata) external {} /// @notice Verifier contract upgrade. Can be external because Proxy contract intercepts illegal calls of this function. /// @param upgradeParameters Encoded representation of upgrade parameters // solhint-disable-next-line no-empty-blocks function upgrade(bytes calldata upgradeParameters) external {} function verifyAggregatedBlockProof( uint256[] memory _recursiveInput, uint256[] memory _proof, uint8[] memory _vkIndexes, uint256[] memory _individualVksInputs, uint256[16] memory _subproofsLimbs ) external view returns (bool) { for (uint256 i = 0; i < _individualVksInputs.length; ++i) { uint256 commitment = _individualVksInputs[i]; _individualVksInputs[i] = commitment & INPUT_MASK; } VerificationKey memory vk = getVkAggregated(uint32(_vkIndexes.length)); return verify_serialized_proof_with_recursion( _recursiveInput, _proof, VK_TREE_ROOT, VK_MAX_INDEX, _vkIndexes, _individualVksInputs, _subproofsLimbs, vk ); } function verifyExitProof( bytes32 _rootHash, uint32 _accountId, address _owner, uint32 _tokenId, uint128 _amount, uint32 _nftCreatorAccountId, address _nftCreatorAddress, uint32 _nftSerialId, bytes32 _nftContentHash, uint256[] calldata _proof ) external view returns (bool) { bytes32 commitment = sha256( abi.encodePacked( _rootHash, _accountId, _owner, _tokenId, _amount, _nftCreatorAccountId, _nftCreatorAddress, _nftSerialId, _nftContentHash ) ); uint256[] memory inputs = new uint256[](1); inputs[0] = uint256(commitment) & INPUT_MASK; ProofOld memory proof = deserialize_proof_old(inputs, _proof); VerificationKeyOld memory vk = getVkExit(); require(vk.num_inputs == inputs.length, "n1"); return verify_old(proof, vk); } } pragma solidity ^0.7.0; // SPDX-License-Identifier: UNLICENSED interface NFTFactory { function mintNFTFromZkSync( address creator, address recipient, uint32 creatorAccountId, uint32 serialId, bytes32 contentHash, // Even though the token id can fit into the uint32, we still use // the uint256 to preserve consistency with the ERC721 parent contract uint256 tokenId ) external; event MintNFTFromZkSync( address indexed creator, address indexed recipient, uint32 creatorAccountId, uint32 serialId, bytes32 contentHash, uint256 tokenId ); } pragma solidity ^0.7.0; // SPDX-License-Identifier: MIT OR Apache-2.0 import "./Governance.sol"; import "./IERC20.sol"; import "./Utils.sol"; /// @title Token Governance Contract /// @author Matter Labs /// @notice Contract is used to allow anyone to add new ERC20 tokens to zkSync given sufficient payment contract TokenGovernance { /// @notice Token lister added or removed (see `tokenLister`) event TokenListerUpdate(address indexed tokenLister, bool isActive); /// @notice Listing fee token set event ListingFeeTokenUpdate(IERC20 indexed newListingFeeToken); /// @notice Listing fee set event ListingFeeUpdate(uint256 newListingFee); /// @notice Maximum number of listed tokens updated event ListingCapUpdate(uint16 newListingCap); /// @notice The treasury (the account which will receive the fee) was updated event TreasuryUpdate(address newTreasury); /// @notice zkSync governance contract Governance public governance; /// @notice Token used to collect listing fee for addition of new token to zkSync network IERC20 public listingFeeToken; /// @notice Token listing fee uint256 public listingFee; /// @notice Max number of tokens that can be listed using this contract uint16 public listingCap; /// @notice Addresses that can list tokens without fee mapping(address => bool) public tokenLister; /// @notice Address that collects listing payments address public treasury; constructor( Governance _governance, IERC20 _listingFeeToken, uint256 _listingFee, uint16 _listingCap, address _treasury ) { governance = _governance; listingFeeToken = _listingFeeToken; listingFee = _listingFee; listingCap = _listingCap; treasury = _treasury; address governor = governance.networkGovernor(); // We add zkSync governor as a first token lister. tokenLister[governor] = true; emit TokenListerUpdate(governor, true); } /// @notice Adds new ERC20 token to zkSync network. /// @notice If caller is not present in the `tokenLister` map payment of `listingFee` in `listingFeeToken` should be made. /// @notice NOTE: before calling this function make sure to approve `listingFeeToken` transfer for this contract. function addToken(address _token) external { require(governance.totalTokens() < listingCap, "can't add more tokens"); // Impossible to add more tokens using this contract if (!tokenLister[msg.sender]) { // Collect fees bool feeTransferOk = Utils.transferFromERC20(listingFeeToken, msg.sender, treasury, listingFee); require(feeTransferOk, "fee transfer failed"); // Failed to receive payment for token addition. } governance.addToken(_token); } /// Governance functions (this contract is governed by zkSync governor) /// @notice Set new listing token and fee /// @notice Can be called only by zkSync governor function setListingFeeToken(IERC20 _newListingFeeToken, uint256 _newListingFee) external { governance.requireGovernor(msg.sender); listingFeeToken = _newListingFeeToken; listingFee = _newListingFee; emit ListingFeeTokenUpdate(_newListingFeeToken); } /// @notice Set new listing fee /// @notice Can be called only by zkSync governor function setListingFee(uint256 _newListingFee) external { governance.requireGovernor(msg.sender); listingFee = _newListingFee; emit ListingFeeUpdate(_newListingFee); } /// @notice Enable or disable token lister. If enabled new tokens can be added by that address without payment /// @notice Can be called only by zkSync governor function setLister(address _listerAddress, bool _active) external { governance.requireGovernor(msg.sender); if (tokenLister[_listerAddress] != _active) { tokenLister[_listerAddress] = _active; emit TokenListerUpdate(_listerAddress, _active); } } /// @notice Change maximum amount of tokens that can be listed using this method /// @notice Can be called only by zkSync governor function setListingCap(uint16 _newListingCap) external { governance.requireGovernor(msg.sender); listingCap = _newListingCap; emit ListingCapUpdate(_newListingCap); } /// @notice Change address that collects payments for listing tokens. /// @notice Can be called only by zkSync governor function setTreasury(address _newTreasury) external { governance.requireGovernor(msg.sender); treasury = _newTreasury; emit TreasuryUpdate(_newTreasury); } } pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; // SPDX-License-Identifier: MIT OR Apache-2.0 import "./PlonkCore.sol"; // Hardcoded constants to avoid accessing store contract KeysWithPlonkVerifier is VerifierWithDeserialize { uint256 constant VK_TREE_ROOT = 0x12d3ca8e7e185734779f3969f1d0a9dbb357a737ed605c37c7157c341012e6d9; uint8 constant VK_MAX_INDEX = 3; function getVkAggregated(uint32 _proofs) internal pure returns (VerificationKey memory vk) { if (_proofs == uint32(1)) { return getVkAggregated1(); } else if (_proofs == uint32(4)) { return getVkAggregated4(); } else if (_proofs == uint32(8)) { return getVkAggregated8(); } } function getVkAggregated1() internal pure returns(VerificationKey memory vk) { vk.domain_size = 4194304; vk.num_inputs = 1; vk.omega = PairingsBn254.new_fr(0x18c95f1ae6514e11a1b30fd7923947c5ffcec5347f16e91b4dd654168326bede); vk.gate_setup_commitments[0] = PairingsBn254.new_g1( 0x19fbd6706b4cbde524865701eae0ae6a270608a09c3afdab7760b685c1c6c41b, 0x25082a191f0690c175cc9af1106c6c323b5b5de4e24dc23be1e965e1851bca48 ); vk.gate_setup_commitments[1] = PairingsBn254.new_g1( 0x16c02d9ca95023d1812a58d16407d1ea065073f02c916290e39242303a8a1d8e, 0x230338b422ce8533e27cd50086c28cb160cf05a7ae34ecd5899dbdf449dc7ce0 ); vk.gate_setup_commitments[2] = PairingsBn254.new_g1( 0x1db0d133243750e1ea692050bbf6068a49dc9f6bae1f11960b6ce9e10adae0f5, 0x12a453ed0121ae05de60848b4374d54ae4b7127cb307372e14e8daf5097c5123 ); vk.gate_setup_commitments[3] = PairingsBn254.new_g1( 0x1062ed5e86781fd34f78938e5950c2481a79f132085d2bc7566351ddff9fa3b7, 0x2fd7aac30f645293cc99883ab57d8c99a518d5b4ab40913808045e8653497346 ); vk.gate_setup_commitments[4] = PairingsBn254.new_g1( 0x062755048bb95739f845e8659795813127283bf799443d62fea600ae23e7f263, 0x2af86098beaa241281c78a454c5d1aa6e9eedc818c96cd1e6518e1ac2d26aa39 ); vk.gate_setup_commitments[5] = PairingsBn254.new_g1( 0x0994e25148bbd25be655034f81062d1ebf0a1c2b41e0971434beab1ae8101474, 0x27cc8cfb1fafd13068aeee0e08a272577d89f8aa0fb8507aabbc62f37587b98f ); vk.gate_setup_commitments[6] = PairingsBn254.new_g1( 0x044edf69ce10cfb6206795f92c3be2b0d26ab9afd3977b789840ee58c7dbe927, 0x2a8aa20c106f8dc7e849bc9698064dcfa9ed0a4050d794a1db0f13b0ee3def37 ); vk.gate_selector_commitments[0] = PairingsBn254.new_g1( 0x136967f1a2696db05583a58dbf8971c5d9d1dc5f5c97e88f3b4822aa52fefa1c, 0x127b41299ea5c840c3b12dbe7b172380f432b7b63ce3b004750d6abb9e7b3b7a ); vk.gate_selector_commitments[1] = PairingsBn254.new_g1( 0x02fd5638bf3cc2901395ad1124b951e474271770a337147a2167e9797ab9d951, 0x0fcb2e56b077c8461c36911c9252008286d782e96030769bf279024fc81d412a ); vk.copy_permutation_commitments[0] = PairingsBn254.new_g1( 0x1865c60ecad86f81c6c952445707203c9c7fdace3740232ceb704aefd5bd45b3, 0x2f35e29b39ec8bb054e2cff33c0299dd13f8c78ea24a07622128a7444aba3f26 ); vk.copy_permutation_commitments[1] = PairingsBn254.new_g1( 0x2a86ec9c6c1f903650b5abbf0337be556b03f79aecc4d917e90c7db94518dde6, 0x15b1b6be641336eebd58e7991be2991debbbd780e70c32b49225aa98d10b7016 ); vk.copy_permutation_commitments[2] = PairingsBn254.new_g1( 0x213e42fcec5297b8e01a602684fcd412208d15bdac6b6331a8819d478ba46899, 0x03223485f4e808a3b2496ae1a3c0dfbcbf4391cffc57ee01e8fca114636ead18 ); vk.copy_permutation_commitments[3] = PairingsBn254.new_g1( 0x2e9b02f8cf605ad1a36e99e990a07d435de06716448ad53053c7a7a5341f71e1, 0x2d6fdf0bc8bd89112387b1894d6f24b45dcb122c09c84344b6fc77a619dd1d59 ); vk.copy_permutation_non_residues[0] = PairingsBn254.new_fr( 0x0000000000000000000000000000000000000000000000000000000000000005 ); vk.copy_permutation_non_residues[1] = PairingsBn254.new_fr( 0x0000000000000000000000000000000000000000000000000000000000000007 ); vk.copy_permutation_non_residues[2] = PairingsBn254.new_fr( 0x000000000000000000000000000000000000000000000000000000000000000a ); vk.g2_x = PairingsBn254.new_g2( [0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1, 0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0], [0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4, 0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55] ); } function getVkAggregated4() internal pure returns(VerificationKey memory vk) { vk.domain_size = 8388608; vk.num_inputs = 1; vk.omega = PairingsBn254.new_fr(0x1283ba6f4b7b1a76ba2008fe823128bea4adb9269cbfd7c41c223be65bc60863); vk.gate_setup_commitments[0] = PairingsBn254.new_g1( 0x2988e24b15bce9a1e3a4d1d9a8f7c7a65db6c29fd4c6f4afe1a3fbd954d4b4b6, 0x0bdb6e5ba27a22e03270c7c71399b866b28d7cec504d30e665d67be58e306e12 ); vk.gate_setup_commitments[1] = PairingsBn254.new_g1( 0x20f3d30d3a91a7419d658f8c035e42a811c9f75eac2617e65729033286d36089, 0x07ac91e8194eb78a9db537e9459dd6ca26bef8770dde54ac3dd396450b1d4cfe ); vk.gate_setup_commitments[2] = PairingsBn254.new_g1( 0x0311872bab6df6e9095a9afe40b12e2ed58f00cc88835442e6b4cf73fb3e147d, 0x2cdfc5b5e73737809b54644b2f96494f8fcc1dd0fb440f64f44930b432c4542d ); vk.gate_setup_commitments[3] = PairingsBn254.new_g1( 0x28fd545b1e960d2eff3142271affa4096ef724212031fdabe22dd4738f36472b, 0x2c743150ee9894ff3965d8f1129399a3b89a1a9289d4cfa904b0a648d3a8a9fa ); vk.gate_setup_commitments[4] = PairingsBn254.new_g1( 0x2c283ce950eee1173b78657e57c80658a8398e7970a9a45b20cd39aff16ad61a, 0x081c003cbd09f7c3e0d723d6ebbaf432421c188d5759f5ee8ff1ee1dc357d4a8 ); vk.gate_setup_commitments[5] = PairingsBn254.new_g1( 0x2eb50a2dd293a71a0c038e958c5237bd7f50b2f0c9ee6385895a553de1517d43, 0x15fdc2b5b28fc351f987b98aa6caec7552cefbafa14e6651061eec4f41993b65 ); vk.gate_setup_commitments[6] = PairingsBn254.new_g1( 0x17a9403e5c846c1ca5e767c89250113aa156fdb1f026aa0b4db59c09d06816ec, 0x2512241972ca3ee4839ac72a4cab39ddb413a7553556abd7909284b34ee73f6b ); vk.gate_selector_commitments[0] = PairingsBn254.new_g1( 0x09edd69c8baa7928b16615e993e3032bc8cbf9f42bfa3cf28caba1078d371edb, 0x12e5c39148af860a87b14ae938f33eafa91deeb548cda4cc23ed9ba3e6e496b8 ); vk.gate_selector_commitments[1] = PairingsBn254.new_g1( 0x0e25c0027706ca3fd3daae849f7c50ec88d4d030da02452001dec7b554cc71b4, 0x2421da0ca385ff7ba9e5ae68890655669248c8c8187e67d12b2a7ae97e2cff8b ); vk.copy_permutation_commitments[0] = PairingsBn254.new_g1( 0x151536359fe184567bce57379833f6fae485e5cc9bc27423d83d281aaf2701df, 0x116beb145bc27faae5a8ae30c28040d3baafb3ea47360e528227b94adb9e4f26 ); vk.copy_permutation_commitments[1] = PairingsBn254.new_g1( 0x23ee338093db23364a6e44acfb60d810a4c4bd6565b185374f7840152d3ae82c, 0x0f6714f3ee113b9dfb6b653f04bf497602588b16b96ac682d9a5dd880a0aa601 ); vk.copy_permutation_commitments[2] = PairingsBn254.new_g1( 0x05860b0ea3c6f22150812aee304bf35e1a95cfa569a8da52b42dba44a122378a, 0x19e5a9f3097289272e65e842968752c5355d1cdb2d3d737050e4dfe32ebe1e41 ); vk.copy_permutation_commitments[3] = PairingsBn254.new_g1( 0x3046881fcbe369ac6f99fea8b9505de85ded3de3bc445060be4bc6ef651fa352, 0x06fe14c1dd6c2f2b48aebeb6fd525573d276b2e148ad25e75c57a58588f755ec ); vk.copy_permutation_non_residues[0] = PairingsBn254.new_fr( 0x0000000000000000000000000000000000000000000000000000000000000005 ); vk.copy_permutation_non_residues[1] = PairingsBn254.new_fr( 0x0000000000000000000000000000000000000000000000000000000000000007 ); vk.copy_permutation_non_residues[2] = PairingsBn254.new_fr( 0x000000000000000000000000000000000000000000000000000000000000000a ); vk.g2_x = PairingsBn254.new_g2( [0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1, 0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0], [0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4, 0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55] ); } function getVkAggregated8() internal pure returns(VerificationKey memory vk) { vk.domain_size = 16777216; vk.num_inputs = 1; vk.omega = PairingsBn254.new_fr(0x1951441010b2b95a6e47a6075066a50a036f5ba978c050f2821df86636c0facb); vk.gate_setup_commitments[0] = PairingsBn254.new_g1( 0x218bdb295b7207114aeea948e2d3baef158d4057812f94005d8ff54341b6ce6f, 0x1398585c039ba3cf336687301e95fbbf6b0638d31c64b1d815bb49091d0c1aad ); vk.gate_setup_commitments[1] = PairingsBn254.new_g1( 0x2e40b8a98e688c9e00f607a64520a850d35f277dc0b645628494337bb75870e8, 0x2da4ef753cc4869e53cff171009dbffea9166b8ffbafd17783d712278a79f13e ); vk.gate_setup_commitments[2] = PairingsBn254.new_g1( 0x1b638de3c6cc2e0badc48305ee3533678a45f52edf30277303551128772303a2, 0x2794c375cbebb7c28379e8abf42d529a1c291319020099935550c83796ba14ac ); vk.gate_setup_commitments[3] = PairingsBn254.new_g1( 0x189cd01d67b44cf2c1e10765c69adaafd6a5929952cf55732e312ecf00166956, 0x15976c99ef2c911bd3a72c9613b7fe9e66b03dd8963bfed705c96e3e88fdb1af ); vk.gate_setup_commitments[4] = PairingsBn254.new_g1( 0x0745a77052dc66afc61163ec3737651e5b846ca7ec7fae1853515d0f10a51bd9, 0x2bd27ecf4fb7f5053cc6de3ddb7a969fac5150a6fb5555ca917d16a7836e4c0a ); vk.gate_setup_commitments[5] = PairingsBn254.new_g1( 0x2787aea173d07508083893b02ea962be71c3b628d1da7d7c4db0def49f73ad8f, 0x22fdc951a97dc2ac7d8292a6c263898022f4623c643a56b9265b33c72e628886 ); vk.gate_setup_commitments[6] = PairingsBn254.new_g1( 0x0aafe35c49634858e44e9af259cac47a6f8402eb870f9f95217dcb8a33a73e64, 0x1b47a7641a7c918784e84fc2494bfd8014ebc77069b94650d25cb5e25fbb7003 ); vk.gate_selector_commitments[0] = PairingsBn254.new_g1( 0x11cfc3fe28dfd5d663d53ceacc5ec620da85ae5aa971f0f003f57e75cd05bf9f, 0x28b325f30984634fc46c6750f402026d4ff43e5325cbe34d35bf8ac4fc9cc533 ); vk.gate_selector_commitments[1] = PairingsBn254.new_g1( 0x2ada816636b9447def36e35dd3ab0e3f7a8bbe3ae32a5a4904dee3fc26e58015, 0x2cd12d1a50aaadef4e19e1b1955c932e992e688c2883da862bd7fad17aae66f6 ); vk.copy_permutation_commitments[0] = PairingsBn254.new_g1( 0x20cc506f273be4d114cbf2807c14a769d03169168892e2855cdfa78c3095c89d, 0x08f99d338aee985d780d036473c624de9fd7960b2a4a7ad361c8c125cf11899e ); vk.copy_permutation_commitments[1] = PairingsBn254.new_g1( 0x01260265d3b1167eac1030f3d04326f08a1f2bb1e026e54afec844e3729386e2, 0x16d75b53ec2552c63e84ea5f4bfe1507c3198045875457c1d9295d6699f39d56 ); vk.copy_permutation_commitments[2] = PairingsBn254.new_g1( 0x1f4d73c63d163c3f5ef1b5caa41988cacbdbca38334e8f54d7ee9bbbb622e200, 0x2f48f5f93d9845526ef0348f1c3def63cfc009645eb2a95d1746c7941e888a78 ); vk.copy_permutation_commitments[3] = PairingsBn254.new_g1( 0x1dbd386fe258366222becc570a7f6405b25ff52818b93bdd54eaa20a6b22025a, 0x2b2b4e978ac457d752f50b02609bd7d2054286b963821b2ec7cd3dd1507479fa ); vk.copy_permutation_non_residues[0] = PairingsBn254.new_fr( 0x0000000000000000000000000000000000000000000000000000000000000005 ); vk.copy_permutation_non_residues[1] = PairingsBn254.new_fr( 0x0000000000000000000000000000000000000000000000000000000000000007 ); vk.copy_permutation_non_residues[2] = PairingsBn254.new_fr( 0x000000000000000000000000000000000000000000000000000000000000000a ); vk.g2_x = PairingsBn254.new_g2( [0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1, 0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0], [0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4, 0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55] ); } } // Hardcoded constants to avoid accessing store contract KeysWithPlonkVerifierOld is VerifierWithDeserializeOld { function getVkExit() internal pure returns(VerificationKeyOld memory vk) { vk.domain_size = 524288; vk.num_inputs = 1; vk.omega = PairingsBn254.new_fr(0x0cf1526aaafac6bacbb67d11a4077806b123f767e4b0883d14cc0193568fc082); vk.selector_commitments[0] = PairingsBn254.new_g1( 0x114dd473f77a15b602201577dd4b64a32a783cb32fbc02911e512df6a219695d, 0x04c68f82a5dd7d0cc90318bdff493b3d552d148ad859c373ffe55275e043c43b ); vk.selector_commitments[1] = PairingsBn254.new_g1( 0x245e8c882af503cb5421f5135b4295a920ccf68b42ae7fb967f044f54e2aaa29, 0x071322ee387a9ce49fe7ef2edb6e9237203dee49ec47483af85e356b79fb06fd ); vk.selector_commitments[2] = PairingsBn254.new_g1( 0x0187754ab593b07a420b3b4d215c20ed49acf90fc4c97e4b06e8f5bc0a2eb3f4, 0x0170f9286ce950286a16ea25136c163c0b32019f31b89c256a612d40b863d0b6 ); vk.selector_commitments[3] = PairingsBn254.new_g1( 0x0defecfae1d2b9ec9b2ee4d4798c625fa50f6a4ddb7747a7293df0c17fcb90c2, 0x0f91d08fceebf85fb80f12cda78cefa1ee9dbf5cfe7c4f0704b3c6620fa50c55 ); vk.selector_commitments[4] = PairingsBn254.new_g1( 0x2f7fef3b3fb64af6640f93803a18b3e5ce4e0e60aecd4f924c833fa6fa6da961, 0x03908fc737113ac7f3529fe3b36efca200c66d1d85d2fc081973214c586de732 ); vk.selector_commitments[5] = PairingsBn254.new_g1( 0x14ce3c0e9b78fc331327249e707f58fa4bb0ed746bdc9c2262ad0cf905609627, 0x09e64fdac452b424e98fc4a92f7222693d0d84ab48aadd9c46151dbe5f1a34a9 ); // we only have access to value of the d(x) witness polynomial on the next // trace step, so we only need one element here and deal with it in other places // by having this in mind vk.next_step_selector_commitments[0] = PairingsBn254.new_g1( 0x1d10bfd923c17d9623ec02db00099355b373021432ae1edef69b0f5f461f78d6, 0x24e370a93f65f42888781d0158bb6ef9136c8bbd047d7993b8276bc8df8b640a ); vk.permutation_commitments[0] = PairingsBn254.new_g1( 0x1fd1755ed4d06d91d50db4771d332cfa2bc2ca0e10ac8b77e0d6b73b993e788e, 0x0bdbf3b7f0d3cffdcf818f1fba18b90914eda59b454bd1858c6c0916b817f883 ); vk.permutation_commitments[1] = PairingsBn254.new_g1( 0x1f3b8d12ffa2ceb2bb42d232ad2cf11bce3183472b622e11cc841d26f42ad507, 0x0ce815e32b3bd14311cde210cda1bd351617d539ed3e9d96a8605f364f3a29b0 ); vk.permutation_commitments[2] = PairingsBn254.new_g1( 0x123afa8c1cec1956d7330db062498a2a3e3a9862926c02e1228d9cfb63d3c301, 0x0f5af15ff0a3e35486c541f72956b53ff6d0740384ef6463c866146c1bd2afc8 ); vk.permutation_commitments[3] = PairingsBn254.new_g1( 0x01069e38ea6396af1623921101d3d3d14ee46942fb23bf1d110efb994c3ee573, 0x232a8ce7151e69601a7867f9dcac8e2de4dd8352d119c90bbb0fb84720c02513 ); vk.permutation_non_residues[0] = PairingsBn254.new_fr( 0x0000000000000000000000000000000000000000000000000000000000000005 ); vk.permutation_non_residues[1] = PairingsBn254.new_fr( 0x0000000000000000000000000000000000000000000000000000000000000007 ); vk.permutation_non_residues[2] = PairingsBn254.new_fr( 0x000000000000000000000000000000000000000000000000000000000000000a ); vk.g2_x = PairingsBn254.new_g2( [0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1, 0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0], [0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4, 0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55] ); } } pragma solidity >=0.5.0 <0.8.0; pragma experimental ABIEncoderV2; // SPDX-License-Identifier: MIT OR Apache-2.0 // solhint-disable library PairingsBn254 { uint256 constant q_mod = 21888242871839275222246405745257275088696311157297823662689037894645226208583; uint256 constant r_mod = 21888242871839275222246405745257275088548364400416034343698204186575808495617; uint256 constant bn254_b_coeff = 3; struct G1Point { uint256 X; uint256 Y; } struct Fr { uint256 value; } function new_fr(uint256 fr) internal pure returns (Fr memory) { require(fr < r_mod); return Fr({value: fr}); } function copy(Fr memory self) internal pure returns (Fr memory n) { n.value = self.value; } function assign(Fr memory self, Fr memory other) internal pure { self.value = other.value; } function inverse(Fr memory fr) internal view returns (Fr memory) { require(fr.value != 0); return pow(fr, r_mod - 2); } function add_assign(Fr memory self, Fr memory other) internal pure { self.value = addmod(self.value, other.value, r_mod); } function sub_assign(Fr memory self, Fr memory other) internal pure { self.value = addmod(self.value, r_mod - other.value, r_mod); } function mul_assign(Fr memory self, Fr memory other) internal pure { self.value = mulmod(self.value, other.value, r_mod); } function pow(Fr memory self, uint256 power) internal view returns (Fr memory) { uint256[6] memory input = [32, 32, 32, self.value, power, r_mod]; uint256[1] memory result; bool success; assembly { success := staticcall(gas(), 0x05, input, 0xc0, result, 0x20) } require(success); return Fr({value: result[0]}); } // Encoding of field elements is: X[0] * z + X[1] struct G2Point { uint256[2] X; uint256[2] Y; } function P1() internal pure returns (G1Point memory) { return G1Point(1, 2); } function new_g1(uint256 x, uint256 y) internal pure returns (G1Point memory) { return G1Point(x, y); } function new_g1_checked(uint256 x, uint256 y) internal pure returns (G1Point memory) { if (x == 0 && y == 0) { // point of infinity is (0,0) return G1Point(x, y); } // check encoding require(x < q_mod); require(y < q_mod); // check on curve uint256 lhs = mulmod(y, y, q_mod); // y^2 uint256 rhs = mulmod(x, x, q_mod); // x^2 rhs = mulmod(rhs, x, q_mod); // x^3 rhs = addmod(rhs, bn254_b_coeff, q_mod); // x^3 + b require(lhs == rhs); return G1Point(x, y); } function new_g2(uint256[2] memory x, uint256[2] memory y) internal pure returns (G2Point memory) { return G2Point(x, y); } function copy_g1(G1Point memory self) internal pure returns (G1Point memory result) { result.X = self.X; result.Y = self.Y; } function P2() internal pure returns (G2Point memory) { // for some reason ethereum expects to have c1*v + c0 form return G2Point( [ 0x198e9393920d483a7260bfb731fb5d25f1aa493335a9e71297e485b7aef312c2, 0x1800deef121f1e76426a00665e5c4479674322d4f75edadd46debd5cd992f6ed ], [ 0x090689d0585ff075ec9e99ad690c3395bc4b313370b38ef355acdadcd122975b, 0x12c85ea5db8c6deb4aab71808dcb408fe3d1e7690c43d37b4ce6cc0166fa7daa ] ); } function negate(G1Point memory self) internal pure { // The prime q in the base field F_q for G1 if (self.Y == 0) { require(self.X == 0); return; } self.Y = q_mod - self.Y; } function point_add(G1Point memory p1, G1Point memory p2) internal view returns (G1Point memory r) { point_add_into_dest(p1, p2, r); return r; } function point_add_assign(G1Point memory p1, G1Point memory p2) internal view { point_add_into_dest(p1, p2, p1); } function point_add_into_dest( G1Point memory p1, G1Point memory p2, G1Point memory dest ) internal view { if (p2.X == 0 && p2.Y == 0) { // we add zero, nothing happens dest.X = p1.X; dest.Y = p1.Y; return; } else if (p1.X == 0 && p1.Y == 0) { // we add into zero, and we add non-zero point dest.X = p2.X; dest.Y = p2.Y; return; } else { uint256[4] memory input; input[0] = p1.X; input[1] = p1.Y; input[2] = p2.X; input[3] = p2.Y; bool success = false; assembly { success := staticcall(gas(), 6, input, 0x80, dest, 0x40) } require(success); } } function point_sub_assign(G1Point memory p1, G1Point memory p2) internal view { point_sub_into_dest(p1, p2, p1); } function point_sub_into_dest( G1Point memory p1, G1Point memory p2, G1Point memory dest ) internal view { if (p2.X == 0 && p2.Y == 0) { // we subtracted zero, nothing happens dest.X = p1.X; dest.Y = p1.Y; return; } else if (p1.X == 0 && p1.Y == 0) { // we subtract from zero, and we subtract non-zero point dest.X = p2.X; dest.Y = q_mod - p2.Y; return; } else { uint256[4] memory input; input[0] = p1.X; input[1] = p1.Y; input[2] = p2.X; input[3] = q_mod - p2.Y; bool success = false; assembly { success := staticcall(gas(), 6, input, 0x80, dest, 0x40) } require(success); } } function point_mul(G1Point memory p, Fr memory s) internal view returns (G1Point memory r) { point_mul_into_dest(p, s, r); return r; } function point_mul_assign(G1Point memory p, Fr memory s) internal view { point_mul_into_dest(p, s, p); } function point_mul_into_dest( G1Point memory p, Fr memory s, G1Point memory dest ) internal view { uint256[3] memory input; input[0] = p.X; input[1] = p.Y; input[2] = s.value; bool success; assembly { success := staticcall(gas(), 7, input, 0x60, dest, 0x40) } require(success); } function pairing(G1Point[] memory p1, G2Point[] memory p2) internal view returns (bool) { require(p1.length == p2.length); uint256 elements = p1.length; uint256 inputSize = elements * 6; uint256[] memory input = new uint256[](inputSize); for (uint256 i = 0; i < elements; i++) { input[i * 6 + 0] = p1[i].X; input[i * 6 + 1] = p1[i].Y; input[i * 6 + 2] = p2[i].X[0]; input[i * 6 + 3] = p2[i].X[1]; input[i * 6 + 4] = p2[i].Y[0]; input[i * 6 + 5] = p2[i].Y[1]; } uint256[1] memory out; bool success; assembly { success := staticcall(gas(), 8, add(input, 0x20), mul(inputSize, 0x20), out, 0x20) } require(success); return out[0] != 0; } /// Convenience method for a pairing check for two pairs. function pairingProd2( G1Point memory a1, G2Point memory a2, G1Point memory b1, G2Point memory b2 ) internal view returns (bool) { G1Point[] memory p1 = new G1Point[](2); G2Point[] memory p2 = new G2Point[](2); p1[0] = a1; p1[1] = b1; p2[0] = a2; p2[1] = b2; return pairing(p1, p2); } } library TranscriptLibrary { // flip 0xe000000000000000000000000000000000000000000000000000000000000000; uint256 constant FR_MASK = 0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; uint32 constant DST_0 = 0; uint32 constant DST_1 = 1; uint32 constant DST_CHALLENGE = 2; struct Transcript { bytes32 state_0; bytes32 state_1; uint32 challenge_counter; } function new_transcript() internal pure returns (Transcript memory t) { t.state_0 = bytes32(0); t.state_1 = bytes32(0); t.challenge_counter = 0; } function update_with_u256(Transcript memory self, uint256 value) internal pure { bytes32 old_state_0 = self.state_0; self.state_0 = keccak256(abi.encodePacked(DST_0, old_state_0, self.state_1, value)); self.state_1 = keccak256(abi.encodePacked(DST_1, old_state_0, self.state_1, value)); } function update_with_fr(Transcript memory self, PairingsBn254.Fr memory value) internal pure { update_with_u256(self, value.value); } function update_with_g1(Transcript memory self, PairingsBn254.G1Point memory p) internal pure { update_with_u256(self, p.X); update_with_u256(self, p.Y); } function get_challenge(Transcript memory self) internal pure returns (PairingsBn254.Fr memory challenge) { bytes32 query = keccak256(abi.encodePacked(DST_CHALLENGE, self.state_0, self.state_1, self.challenge_counter)); self.challenge_counter += 1; challenge = PairingsBn254.Fr({value: uint256(query) & FR_MASK}); } } contract Plonk4VerifierWithAccessToDNext { uint256 constant r_mod = 21888242871839275222246405745257275088548364400416034343698204186575808495617; using PairingsBn254 for PairingsBn254.G1Point; using PairingsBn254 for PairingsBn254.G2Point; using PairingsBn254 for PairingsBn254.Fr; using TranscriptLibrary for TranscriptLibrary.Transcript; uint256 constant ZERO = 0; uint256 constant ONE = 1; uint256 constant TWO = 2; uint256 constant THREE = 3; uint256 constant FOUR = 4; uint256 constant STATE_WIDTH = 4; uint256 constant NUM_DIFFERENT_GATES = 2; uint256 constant NUM_SETUP_POLYS_FOR_MAIN_GATE = 7; uint256 constant NUM_SETUP_POLYS_RANGE_CHECK_GATE = 0; uint256 constant ACCESSIBLE_STATE_POLYS_ON_NEXT_STEP = 1; uint256 constant NUM_GATE_SELECTORS_OPENED_EXPLICITLY = 1; uint256 constant RECURSIVE_CIRCUIT_INPUT_COMMITMENT_MASK = 0x00ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; uint256 constant LIMB_WIDTH = 68; struct VerificationKey { uint256 domain_size; uint256 num_inputs; PairingsBn254.Fr omega; PairingsBn254.G1Point[NUM_SETUP_POLYS_FOR_MAIN_GATE + NUM_SETUP_POLYS_RANGE_CHECK_GATE] gate_setup_commitments; PairingsBn254.G1Point[NUM_DIFFERENT_GATES] gate_selector_commitments; PairingsBn254.G1Point[STATE_WIDTH] copy_permutation_commitments; PairingsBn254.Fr[STATE_WIDTH - 1] copy_permutation_non_residues; PairingsBn254.G2Point g2_x; } struct Proof { uint256[] input_values; PairingsBn254.G1Point[STATE_WIDTH] wire_commitments; PairingsBn254.G1Point copy_permutation_grand_product_commitment; PairingsBn254.G1Point[STATE_WIDTH] quotient_poly_commitments; PairingsBn254.Fr[STATE_WIDTH] wire_values_at_z; PairingsBn254.Fr[ACCESSIBLE_STATE_POLYS_ON_NEXT_STEP] wire_values_at_z_omega; PairingsBn254.Fr[NUM_GATE_SELECTORS_OPENED_EXPLICITLY] gate_selector_values_at_z; PairingsBn254.Fr copy_grand_product_at_z_omega; PairingsBn254.Fr quotient_polynomial_at_z; PairingsBn254.Fr linearization_polynomial_at_z; PairingsBn254.Fr[STATE_WIDTH - 1] permutation_polynomials_at_z; PairingsBn254.G1Point opening_at_z_proof; PairingsBn254.G1Point opening_at_z_omega_proof; } struct PartialVerifierState { PairingsBn254.Fr alpha; PairingsBn254.Fr beta; PairingsBn254.Fr gamma; PairingsBn254.Fr v; PairingsBn254.Fr u; PairingsBn254.Fr z; PairingsBn254.Fr[] cached_lagrange_evals; } function evaluate_lagrange_poly_out_of_domain( uint256 poly_num, uint256 domain_size, PairingsBn254.Fr memory omega, PairingsBn254.Fr memory at ) internal view returns (PairingsBn254.Fr memory res) { require(poly_num < domain_size); PairingsBn254.Fr memory one = PairingsBn254.new_fr(1); PairingsBn254.Fr memory omega_power = omega.pow(poly_num); res = at.pow(domain_size); res.sub_assign(one); require(res.value != 0); // Vanishing polynomial can not be zero at point `at` res.mul_assign(omega_power); PairingsBn254.Fr memory den = PairingsBn254.copy(at); den.sub_assign(omega_power); den.mul_assign(PairingsBn254.new_fr(domain_size)); den = den.inverse(); res.mul_assign(den); } function batch_evaluate_lagrange_poly_out_of_domain( uint256[] memory poly_nums, uint256 domain_size, PairingsBn254.Fr memory omega, PairingsBn254.Fr memory at ) internal view returns (PairingsBn254.Fr[] memory res) { PairingsBn254.Fr memory one = PairingsBn254.new_fr(1); PairingsBn254.Fr memory tmp_1 = PairingsBn254.new_fr(0); PairingsBn254.Fr memory tmp_2 = PairingsBn254.new_fr(domain_size); PairingsBn254.Fr memory vanishing_at_z = at.pow(domain_size); vanishing_at_z.sub_assign(one); // we can not have random point z be in domain require(vanishing_at_z.value != 0); PairingsBn254.Fr[] memory nums = new PairingsBn254.Fr[](poly_nums.length); PairingsBn254.Fr[] memory dens = new PairingsBn254.Fr[](poly_nums.length); // numerators in a form omega^i * (z^n - 1) // denoms in a form (z - omega^i) * N for (uint256 i = 0; i < poly_nums.length; i++) { tmp_1 = omega.pow(poly_nums[i]); // power of omega nums[i].assign(vanishing_at_z); nums[i].mul_assign(tmp_1); dens[i].assign(at); // (X - omega^i) * N dens[i].sub_assign(tmp_1); dens[i].mul_assign(tmp_2); // mul by domain size } PairingsBn254.Fr[] memory partial_products = new PairingsBn254.Fr[](poly_nums.length); partial_products[0].assign(PairingsBn254.new_fr(1)); for (uint256 i = 1; i < dens.length - 1; i++) { partial_products[i].assign(dens[i - 1]); partial_products[i].mul_assign(dens[i]); } tmp_2.assign(partial_products[partial_products.length - 1]); tmp_2.mul_assign(dens[dens.length - 1]); tmp_2 = tmp_2.inverse(); // tmp_2 contains a^-1 * b^-1 (with! the last one) for (uint256 i = dens.length - 1; i < dens.length; i--) { dens[i].assign(tmp_2); // all inversed dens[i].mul_assign(partial_products[i]); // clear lowest terms tmp_2.mul_assign(dens[i]); } for (uint256 i = 0; i < nums.length; i++) { nums[i].mul_assign(dens[i]); } return nums; } function evaluate_vanishing(uint256 domain_size, PairingsBn254.Fr memory at) internal view returns (PairingsBn254.Fr memory res) { res = at.pow(domain_size); res.sub_assign(PairingsBn254.new_fr(1)); } function verify_at_z( PartialVerifierState memory state, Proof memory proof, VerificationKey memory vk ) internal view returns (bool) { PairingsBn254.Fr memory lhs = evaluate_vanishing(vk.domain_size, state.z); require(lhs.value != 0); // we can not check a polynomial relationship if point `z` is in the domain lhs.mul_assign(proof.quotient_polynomial_at_z); PairingsBn254.Fr memory quotient_challenge = PairingsBn254.new_fr(1); PairingsBn254.Fr memory rhs = PairingsBn254.copy(proof.linearization_polynomial_at_z); // public inputs PairingsBn254.Fr memory tmp = PairingsBn254.new_fr(0); PairingsBn254.Fr memory inputs_term = PairingsBn254.new_fr(0); for (uint256 i = 0; i < proof.input_values.length; i++) { tmp.assign(state.cached_lagrange_evals[i]); tmp.mul_assign(PairingsBn254.new_fr(proof.input_values[i])); inputs_term.add_assign(tmp); } inputs_term.mul_assign(proof.gate_selector_values_at_z[0]); rhs.add_assign(inputs_term); // now we need 5th power quotient_challenge.mul_assign(state.alpha); quotient_challenge.mul_assign(state.alpha); quotient_challenge.mul_assign(state.alpha); quotient_challenge.mul_assign(state.alpha); quotient_challenge.mul_assign(state.alpha); PairingsBn254.Fr memory z_part = PairingsBn254.copy(proof.copy_grand_product_at_z_omega); for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) { tmp.assign(proof.permutation_polynomials_at_z[i]); tmp.mul_assign(state.beta); tmp.add_assign(state.gamma); tmp.add_assign(proof.wire_values_at_z[i]); z_part.mul_assign(tmp); } tmp.assign(state.gamma); // we need a wire value of the last polynomial in enumeration tmp.add_assign(proof.wire_values_at_z[STATE_WIDTH - 1]); z_part.mul_assign(tmp); z_part.mul_assign(quotient_challenge); rhs.sub_assign(z_part); quotient_challenge.mul_assign(state.alpha); tmp.assign(state.cached_lagrange_evals[0]); tmp.mul_assign(quotient_challenge); rhs.sub_assign(tmp); return lhs.value == rhs.value; } function add_contribution_from_range_constraint_gates( PartialVerifierState memory state, Proof memory proof, PairingsBn254.Fr memory current_alpha ) internal pure returns (PairingsBn254.Fr memory res) { // now add contribution from range constraint gate // we multiply selector commitment by all the factors (alpha*(c - 4d)(c - 4d - 1)(..-2)(..-3) + alpha^2 * (4b - c)()()() + {} + {}) PairingsBn254.Fr memory one_fr = PairingsBn254.new_fr(ONE); PairingsBn254.Fr memory two_fr = PairingsBn254.new_fr(TWO); PairingsBn254.Fr memory three_fr = PairingsBn254.new_fr(THREE); PairingsBn254.Fr memory four_fr = PairingsBn254.new_fr(FOUR); res = PairingsBn254.new_fr(0); PairingsBn254.Fr memory t0 = PairingsBn254.new_fr(0); PairingsBn254.Fr memory t1 = PairingsBn254.new_fr(0); PairingsBn254.Fr memory t2 = PairingsBn254.new_fr(0); for (uint256 i = 0; i < 3; i++) { current_alpha.mul_assign(state.alpha); // high - 4*low // this is 4*low t0 = PairingsBn254.copy(proof.wire_values_at_z[3 - i]); t0.mul_assign(four_fr); // high t1 = PairingsBn254.copy(proof.wire_values_at_z[2 - i]); t1.sub_assign(t0); // t0 is now t1 - {0,1,2,3} // first unroll manually for -0; t2 = PairingsBn254.copy(t1); // -1 t0 = PairingsBn254.copy(t1); t0.sub_assign(one_fr); t2.mul_assign(t0); // -2 t0 = PairingsBn254.copy(t1); t0.sub_assign(two_fr); t2.mul_assign(t0); // -3 t0 = PairingsBn254.copy(t1); t0.sub_assign(three_fr); t2.mul_assign(t0); t2.mul_assign(current_alpha); res.add_assign(t2); } // now also d_next - 4a current_alpha.mul_assign(state.alpha); // high - 4*low // this is 4*low t0 = PairingsBn254.copy(proof.wire_values_at_z[0]); t0.mul_assign(four_fr); // high t1 = PairingsBn254.copy(proof.wire_values_at_z_omega[0]); t1.sub_assign(t0); // t0 is now t1 - {0,1,2,3} // first unroll manually for -0; t2 = PairingsBn254.copy(t1); // -1 t0 = PairingsBn254.copy(t1); t0.sub_assign(one_fr); t2.mul_assign(t0); // -2 t0 = PairingsBn254.copy(t1); t0.sub_assign(two_fr); t2.mul_assign(t0); // -3 t0 = PairingsBn254.copy(t1); t0.sub_assign(three_fr); t2.mul_assign(t0); t2.mul_assign(current_alpha); res.add_assign(t2); return res; } function reconstruct_linearization_commitment( PartialVerifierState memory state, Proof memory proof, VerificationKey memory vk ) internal view returns (PairingsBn254.G1Point memory res) { // we compute what power of v is used as a delinearization factor in batch opening of // commitments. Let's label W(x) = 1 / (x - z) * // [ // t_0(x) + z^n * t_1(x) + z^2n * t_2(x) + z^3n * t_3(x) - t(z) // + v (r(x) - r(z)) // + v^{2..5} * (witness(x) - witness(z)) // + v^{6} * (selector(x) - selector(z)) // + v^{7..9} * (permutation(x) - permutation(z)) // ] // W'(x) = 1 / (x - z*omega) * // [ // + v^10 (z(x) - z(z*omega)) <- we need this power // + v^11 * (d(x) - d(z*omega)) // ] // // we reconstruct linearization polynomial virtual selector // for that purpose we first linearize over main gate (over all it's selectors) // and multiply them by value(!) of the corresponding main gate selector res = PairingsBn254.copy_g1(vk.gate_setup_commitments[STATE_WIDTH + 1]); // index of q_const(x) PairingsBn254.G1Point memory tmp_g1 = PairingsBn254.P1(); PairingsBn254.Fr memory tmp_fr = PairingsBn254.new_fr(0); // addition gates for (uint256 i = 0; i < STATE_WIDTH; i++) { tmp_g1 = vk.gate_setup_commitments[i].point_mul(proof.wire_values_at_z[i]); res.point_add_assign(tmp_g1); } // multiplication gate tmp_fr.assign(proof.wire_values_at_z[0]); tmp_fr.mul_assign(proof.wire_values_at_z[1]); tmp_g1 = vk.gate_setup_commitments[STATE_WIDTH].point_mul(tmp_fr); res.point_add_assign(tmp_g1); // d_next tmp_g1 = vk.gate_setup_commitments[STATE_WIDTH + 2].point_mul(proof.wire_values_at_z_omega[0]); // index of q_d_next(x) res.point_add_assign(tmp_g1); // multiply by main gate selector(z) res.point_mul_assign(proof.gate_selector_values_at_z[0]); // these is only one explicitly opened selector PairingsBn254.Fr memory current_alpha = PairingsBn254.new_fr(ONE); // calculate scalar contribution from the range check gate tmp_fr = add_contribution_from_range_constraint_gates(state, proof, current_alpha); tmp_g1 = vk.gate_selector_commitments[1].point_mul(tmp_fr); // selector commitment for range constraint gate * scalar res.point_add_assign(tmp_g1); // proceed as normal to copy permutation current_alpha.mul_assign(state.alpha); // alpha^5 PairingsBn254.Fr memory alpha_for_grand_product = PairingsBn254.copy(current_alpha); // z * non_res * beta + gamma + a PairingsBn254.Fr memory grand_product_part_at_z = PairingsBn254.copy(state.z); grand_product_part_at_z.mul_assign(state.beta); grand_product_part_at_z.add_assign(proof.wire_values_at_z[0]); grand_product_part_at_z.add_assign(state.gamma); for (uint256 i = 0; i < vk.copy_permutation_non_residues.length; i++) { tmp_fr.assign(state.z); tmp_fr.mul_assign(vk.copy_permutation_non_residues[i]); tmp_fr.mul_assign(state.beta); tmp_fr.add_assign(state.gamma); tmp_fr.add_assign(proof.wire_values_at_z[i + 1]); grand_product_part_at_z.mul_assign(tmp_fr); } grand_product_part_at_z.mul_assign(alpha_for_grand_product); // alpha^n & L_{0}(z), and we bump current_alpha current_alpha.mul_assign(state.alpha); tmp_fr.assign(state.cached_lagrange_evals[0]); tmp_fr.mul_assign(current_alpha); grand_product_part_at_z.add_assign(tmp_fr); // prefactor for grand_product(x) is complete // add to the linearization a part from the term // - (a(z) + beta*perm_a + gamma)*()*()*z(z*omega) * beta * perm_d(X) PairingsBn254.Fr memory last_permutation_part_at_z = PairingsBn254.new_fr(1); for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) { tmp_fr.assign(state.beta); tmp_fr.mul_assign(proof.permutation_polynomials_at_z[i]); tmp_fr.add_assign(state.gamma); tmp_fr.add_assign(proof.wire_values_at_z[i]); last_permutation_part_at_z.mul_assign(tmp_fr); } last_permutation_part_at_z.mul_assign(state.beta); last_permutation_part_at_z.mul_assign(proof.copy_grand_product_at_z_omega); last_permutation_part_at_z.mul_assign(alpha_for_grand_product); // we multiply by the power of alpha from the argument // actually multiply prefactors by z(x) and perm_d(x) and combine them tmp_g1 = proof.copy_permutation_grand_product_commitment.point_mul(grand_product_part_at_z); tmp_g1.point_sub_assign(vk.copy_permutation_commitments[STATE_WIDTH - 1].point_mul(last_permutation_part_at_z)); res.point_add_assign(tmp_g1); // multiply them by v immedately as linearization has a factor of v^1 res.point_mul_assign(state.v); // res now contains contribution from the gates linearization and // copy permutation part // now we need to add a part that is the rest // for z(x*omega): // - (a(z) + beta*perm_a + gamma)*()*()*(d(z) + gamma) * z(x*omega) } function aggregate_commitments( PartialVerifierState memory state, Proof memory proof, VerificationKey memory vk ) internal view returns (PairingsBn254.G1Point[2] memory res) { PairingsBn254.G1Point memory d = reconstruct_linearization_commitment(state, proof, vk); PairingsBn254.Fr memory z_in_domain_size = state.z.pow(vk.domain_size); PairingsBn254.G1Point memory tmp_g1 = PairingsBn254.P1(); PairingsBn254.Fr memory aggregation_challenge = PairingsBn254.new_fr(1); PairingsBn254.G1Point memory commitment_aggregation = PairingsBn254.copy_g1(proof.quotient_poly_commitments[0]); PairingsBn254.Fr memory tmp_fr = PairingsBn254.new_fr(1); for (uint256 i = 1; i < proof.quotient_poly_commitments.length; i++) { tmp_fr.mul_assign(z_in_domain_size); tmp_g1 = proof.quotient_poly_commitments[i].point_mul(tmp_fr); commitment_aggregation.point_add_assign(tmp_g1); } aggregation_challenge.mul_assign(state.v); commitment_aggregation.point_add_assign(d); for (uint256 i = 0; i < proof.wire_commitments.length; i++) { aggregation_challenge.mul_assign(state.v); tmp_g1 = proof.wire_commitments[i].point_mul(aggregation_challenge); commitment_aggregation.point_add_assign(tmp_g1); } for (uint256 i = 0; i < NUM_GATE_SELECTORS_OPENED_EXPLICITLY; i++) { aggregation_challenge.mul_assign(state.v); tmp_g1 = vk.gate_selector_commitments[0].point_mul(aggregation_challenge); commitment_aggregation.point_add_assign(tmp_g1); } for (uint256 i = 0; i < vk.copy_permutation_commitments.length - 1; i++) { aggregation_challenge.mul_assign(state.v); tmp_g1 = vk.copy_permutation_commitments[i].point_mul(aggregation_challenge); commitment_aggregation.point_add_assign(tmp_g1); } aggregation_challenge.mul_assign(state.v); // now do prefactor for grand_product(x*omega) tmp_fr.assign(aggregation_challenge); tmp_fr.mul_assign(state.u); commitment_aggregation.point_add_assign(proof.copy_permutation_grand_product_commitment.point_mul(tmp_fr)); aggregation_challenge.mul_assign(state.v); tmp_fr.assign(aggregation_challenge); tmp_fr.mul_assign(state.u); tmp_g1 = proof.wire_commitments[STATE_WIDTH - 1].point_mul(tmp_fr); commitment_aggregation.point_add_assign(tmp_g1); // collect opening values aggregation_challenge = PairingsBn254.new_fr(1); PairingsBn254.Fr memory aggregated_value = PairingsBn254.copy(proof.quotient_polynomial_at_z); aggregation_challenge.mul_assign(state.v); tmp_fr.assign(proof.linearization_polynomial_at_z); tmp_fr.mul_assign(aggregation_challenge); aggregated_value.add_assign(tmp_fr); for (uint256 i = 0; i < proof.wire_values_at_z.length; i++) { aggregation_challenge.mul_assign(state.v); tmp_fr.assign(proof.wire_values_at_z[i]); tmp_fr.mul_assign(aggregation_challenge); aggregated_value.add_assign(tmp_fr); } for (uint256 i = 0; i < proof.gate_selector_values_at_z.length; i++) { aggregation_challenge.mul_assign(state.v); tmp_fr.assign(proof.gate_selector_values_at_z[i]); tmp_fr.mul_assign(aggregation_challenge); aggregated_value.add_assign(tmp_fr); } for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) { aggregation_challenge.mul_assign(state.v); tmp_fr.assign(proof.permutation_polynomials_at_z[i]); tmp_fr.mul_assign(aggregation_challenge); aggregated_value.add_assign(tmp_fr); } aggregation_challenge.mul_assign(state.v); tmp_fr.assign(proof.copy_grand_product_at_z_omega); tmp_fr.mul_assign(aggregation_challenge); tmp_fr.mul_assign(state.u); aggregated_value.add_assign(tmp_fr); aggregation_challenge.mul_assign(state.v); tmp_fr.assign(proof.wire_values_at_z_omega[0]); tmp_fr.mul_assign(aggregation_challenge); tmp_fr.mul_assign(state.u); aggregated_value.add_assign(tmp_fr); commitment_aggregation.point_sub_assign(PairingsBn254.P1().point_mul(aggregated_value)); PairingsBn254.G1Point memory pair_with_generator = commitment_aggregation; pair_with_generator.point_add_assign(proof.opening_at_z_proof.point_mul(state.z)); tmp_fr.assign(state.z); tmp_fr.mul_assign(vk.omega); tmp_fr.mul_assign(state.u); pair_with_generator.point_add_assign(proof.opening_at_z_omega_proof.point_mul(tmp_fr)); PairingsBn254.G1Point memory pair_with_x = proof.opening_at_z_omega_proof.point_mul(state.u); pair_with_x.point_add_assign(proof.opening_at_z_proof); pair_with_x.negate(); res[0] = pair_with_generator; res[1] = pair_with_x; return res; } function verify_initial( PartialVerifierState memory state, Proof memory proof, VerificationKey memory vk ) internal view returns (bool) { require(proof.input_values.length == vk.num_inputs); require(vk.num_inputs >= 1); TranscriptLibrary.Transcript memory transcript = TranscriptLibrary.new_transcript(); for (uint256 i = 0; i < vk.num_inputs; i++) { transcript.update_with_u256(proof.input_values[i]); } for (uint256 i = 0; i < proof.wire_commitments.length; i++) { transcript.update_with_g1(proof.wire_commitments[i]); } state.beta = transcript.get_challenge(); state.gamma = transcript.get_challenge(); transcript.update_with_g1(proof.copy_permutation_grand_product_commitment); state.alpha = transcript.get_challenge(); for (uint256 i = 0; i < proof.quotient_poly_commitments.length; i++) { transcript.update_with_g1(proof.quotient_poly_commitments[i]); } state.z = transcript.get_challenge(); uint256[] memory lagrange_poly_numbers = new uint256[](vk.num_inputs); for (uint256 i = 0; i < lagrange_poly_numbers.length; i++) { lagrange_poly_numbers[i] = i; } state.cached_lagrange_evals = batch_evaluate_lagrange_poly_out_of_domain( lagrange_poly_numbers, vk.domain_size, vk.omega, state.z ); bool valid = verify_at_z(state, proof, vk); if (valid == false) { return false; } transcript.update_with_fr(proof.quotient_polynomial_at_z); for (uint256 i = 0; i < proof.wire_values_at_z.length; i++) { transcript.update_with_fr(proof.wire_values_at_z[i]); } for (uint256 i = 0; i < proof.wire_values_at_z_omega.length; i++) { transcript.update_with_fr(proof.wire_values_at_z_omega[i]); } transcript.update_with_fr(proof.gate_selector_values_at_z[0]); for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) { transcript.update_with_fr(proof.permutation_polynomials_at_z[i]); } transcript.update_with_fr(proof.copy_grand_product_at_z_omega); transcript.update_with_fr(proof.linearization_polynomial_at_z); state.v = transcript.get_challenge(); transcript.update_with_g1(proof.opening_at_z_proof); transcript.update_with_g1(proof.opening_at_z_omega_proof); state.u = transcript.get_challenge(); return true; } // This verifier is for a PLONK with a state width 4 // and main gate equation // q_a(X) * a(X) + // q_b(X) * b(X) + // q_c(X) * c(X) + // q_d(X) * d(X) + // q_m(X) * a(X) * b(X) + // q_constants(X)+ // q_d_next(X) * d(X*omega) // where q_{}(X) are selectors a, b, c, d - state (witness) polynomials // q_d_next(X) "peeks" into the next row of the trace, so it takes // the same d(X) polynomial, but shifted function aggregate_for_verification(Proof memory proof, VerificationKey memory vk) internal view returns (bool valid, PairingsBn254.G1Point[2] memory part) { PartialVerifierState memory state; valid = verify_initial(state, proof, vk); if (valid == false) { return (valid, part); } part = aggregate_commitments(state, proof, vk); (valid, part); } function verify(Proof memory proof, VerificationKey memory vk) internal view returns (bool) { (bool valid, PairingsBn254.G1Point[2] memory recursive_proof_part) = aggregate_for_verification(proof, vk); if (valid == false) { return false; } valid = PairingsBn254.pairingProd2( recursive_proof_part[0], PairingsBn254.P2(), recursive_proof_part[1], vk.g2_x ); return valid; } function verify_recursive( Proof memory proof, VerificationKey memory vk, uint256 recursive_vks_root, uint8 max_valid_index, uint8[] memory recursive_vks_indexes, uint256[] memory individual_vks_inputs, uint256[16] memory subproofs_limbs ) internal view returns (bool) { (uint256 recursive_input, PairingsBn254.G1Point[2] memory aggregated_g1s) = reconstruct_recursive_public_input( recursive_vks_root, max_valid_index, recursive_vks_indexes, individual_vks_inputs, subproofs_limbs ); assert(recursive_input == proof.input_values[0]); (bool valid, PairingsBn254.G1Point[2] memory recursive_proof_part) = aggregate_for_verification(proof, vk); if (valid == false) { return false; } // aggregated_g1s = inner // recursive_proof_part = outer PairingsBn254.G1Point[2] memory combined = combine_inner_and_outer(aggregated_g1s, recursive_proof_part); valid = PairingsBn254.pairingProd2(combined[0], PairingsBn254.P2(), combined[1], vk.g2_x); return valid; } function combine_inner_and_outer(PairingsBn254.G1Point[2] memory inner, PairingsBn254.G1Point[2] memory outer) internal view returns (PairingsBn254.G1Point[2] memory result) { // reuse the transcript primitive TranscriptLibrary.Transcript memory transcript = TranscriptLibrary.new_transcript(); transcript.update_with_g1(inner[0]); transcript.update_with_g1(inner[1]); transcript.update_with_g1(outer[0]); transcript.update_with_g1(outer[1]); PairingsBn254.Fr memory challenge = transcript.get_challenge(); // 1 * inner + challenge * outer result[0] = PairingsBn254.copy_g1(inner[0]); result[1] = PairingsBn254.copy_g1(inner[1]); PairingsBn254.G1Point memory tmp = outer[0].point_mul(challenge); result[0].point_add_assign(tmp); tmp = outer[1].point_mul(challenge); result[1].point_add_assign(tmp); return result; } function reconstruct_recursive_public_input( uint256 recursive_vks_root, uint8 max_valid_index, uint8[] memory recursive_vks_indexes, uint256[] memory individual_vks_inputs, uint256[16] memory subproofs_aggregated ) internal pure returns (uint256 recursive_input, PairingsBn254.G1Point[2] memory reconstructed_g1s) { assert(recursive_vks_indexes.length == individual_vks_inputs.length); bytes memory concatenated = abi.encodePacked(recursive_vks_root); uint8 index; for (uint256 i = 0; i < recursive_vks_indexes.length; i++) { index = recursive_vks_indexes[i]; assert(index <= max_valid_index); concatenated = abi.encodePacked(concatenated, index); } uint256 input; for (uint256 i = 0; i < recursive_vks_indexes.length; i++) { input = individual_vks_inputs[i]; assert(input < r_mod); concatenated = abi.encodePacked(concatenated, input); } concatenated = abi.encodePacked(concatenated, subproofs_aggregated); bytes32 commitment = sha256(concatenated); recursive_input = uint256(commitment) & RECURSIVE_CIRCUIT_INPUT_COMMITMENT_MASK; reconstructed_g1s[0] = PairingsBn254.new_g1_checked( subproofs_aggregated[0] + (subproofs_aggregated[1] << LIMB_WIDTH) + (subproofs_aggregated[2] << (2 * LIMB_WIDTH)) + (subproofs_aggregated[3] << (3 * LIMB_WIDTH)), subproofs_aggregated[4] + (subproofs_aggregated[5] << LIMB_WIDTH) + (subproofs_aggregated[6] << (2 * LIMB_WIDTH)) + (subproofs_aggregated[7] << (3 * LIMB_WIDTH)) ); reconstructed_g1s[1] = PairingsBn254.new_g1_checked( subproofs_aggregated[8] + (subproofs_aggregated[9] << LIMB_WIDTH) + (subproofs_aggregated[10] << (2 * LIMB_WIDTH)) + (subproofs_aggregated[11] << (3 * LIMB_WIDTH)), subproofs_aggregated[12] + (subproofs_aggregated[13] << LIMB_WIDTH) + (subproofs_aggregated[14] << (2 * LIMB_WIDTH)) + (subproofs_aggregated[15] << (3 * LIMB_WIDTH)) ); return (recursive_input, reconstructed_g1s); } } contract VerifierWithDeserialize is Plonk4VerifierWithAccessToDNext { uint256 constant SERIALIZED_PROOF_LENGTH = 34; function deserialize_proof(uint256[] memory public_inputs, uint256[] memory serialized_proof) internal pure returns (Proof memory proof) { require(serialized_proof.length == SERIALIZED_PROOF_LENGTH); proof.input_values = new uint256[](public_inputs.length); for (uint256 i = 0; i < public_inputs.length; i++) { proof.input_values[i] = public_inputs[i]; } uint256 j = 0; for (uint256 i = 0; i < STATE_WIDTH; i++) { proof.wire_commitments[i] = PairingsBn254.new_g1_checked(serialized_proof[j], serialized_proof[j + 1]); j += 2; } proof.copy_permutation_grand_product_commitment = PairingsBn254.new_g1_checked( serialized_proof[j], serialized_proof[j + 1] ); j += 2; for (uint256 i = 0; i < STATE_WIDTH; i++) { proof.quotient_poly_commitments[i] = PairingsBn254.new_g1_checked( serialized_proof[j], serialized_proof[j + 1] ); j += 2; } for (uint256 i = 0; i < STATE_WIDTH; i++) { proof.wire_values_at_z[i] = PairingsBn254.new_fr(serialized_proof[j]); j += 1; } for (uint256 i = 0; i < proof.wire_values_at_z_omega.length; i++) { proof.wire_values_at_z_omega[i] = PairingsBn254.new_fr(serialized_proof[j]); j += 1; } for (uint256 i = 0; i < proof.gate_selector_values_at_z.length; i++) { proof.gate_selector_values_at_z[i] = PairingsBn254.new_fr(serialized_proof[j]); j += 1; } for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) { proof.permutation_polynomials_at_z[i] = PairingsBn254.new_fr(serialized_proof[j]); j += 1; } proof.copy_grand_product_at_z_omega = PairingsBn254.new_fr(serialized_proof[j]); j += 1; proof.quotient_polynomial_at_z = PairingsBn254.new_fr(serialized_proof[j]); j += 1; proof.linearization_polynomial_at_z = PairingsBn254.new_fr(serialized_proof[j]); j += 1; proof.opening_at_z_proof = PairingsBn254.new_g1_checked(serialized_proof[j], serialized_proof[j + 1]); j += 2; proof.opening_at_z_omega_proof = PairingsBn254.new_g1_checked(serialized_proof[j], serialized_proof[j + 1]); } function verify_serialized_proof( uint256[] memory public_inputs, uint256[] memory serialized_proof, VerificationKey memory vk ) public view returns (bool) { require(vk.num_inputs == public_inputs.length); Proof memory proof = deserialize_proof(public_inputs, serialized_proof); bool valid = verify(proof, vk); return valid; } function verify_serialized_proof_with_recursion( uint256[] memory public_inputs, uint256[] memory serialized_proof, uint256 recursive_vks_root, uint8 max_valid_index, uint8[] memory recursive_vks_indexes, uint256[] memory individual_vks_inputs, uint256[16] memory subproofs_limbs, VerificationKey memory vk ) public view returns (bool) { require(vk.num_inputs == public_inputs.length); Proof memory proof = deserialize_proof(public_inputs, serialized_proof); bool valid = verify_recursive( proof, vk, recursive_vks_root, max_valid_index, recursive_vks_indexes, individual_vks_inputs, subproofs_limbs ); return valid; } } contract Plonk4VerifierWithAccessToDNextOld { using PairingsBn254 for PairingsBn254.G1Point; using PairingsBn254 for PairingsBn254.G2Point; using PairingsBn254 for PairingsBn254.Fr; using TranscriptLibrary for TranscriptLibrary.Transcript; uint256 constant STATE_WIDTH_OLD = 4; uint256 constant ACCESSIBLE_STATE_POLYS_ON_NEXT_STEP_OLD = 1; struct VerificationKeyOld { uint256 domain_size; uint256 num_inputs; PairingsBn254.Fr omega; PairingsBn254.G1Point[STATE_WIDTH_OLD + 2] selector_commitments; // STATE_WIDTH for witness + multiplication + constant PairingsBn254.G1Point[ACCESSIBLE_STATE_POLYS_ON_NEXT_STEP_OLD] next_step_selector_commitments; PairingsBn254.G1Point[STATE_WIDTH_OLD] permutation_commitments; PairingsBn254.Fr[STATE_WIDTH_OLD - 1] permutation_non_residues; PairingsBn254.G2Point g2_x; } struct ProofOld { uint256[] input_values; PairingsBn254.G1Point[STATE_WIDTH_OLD] wire_commitments; PairingsBn254.G1Point grand_product_commitment; PairingsBn254.G1Point[STATE_WIDTH_OLD] quotient_poly_commitments; PairingsBn254.Fr[STATE_WIDTH_OLD] wire_values_at_z; PairingsBn254.Fr[ACCESSIBLE_STATE_POLYS_ON_NEXT_STEP_OLD] wire_values_at_z_omega; PairingsBn254.Fr grand_product_at_z_omega; PairingsBn254.Fr quotient_polynomial_at_z; PairingsBn254.Fr linearization_polynomial_at_z; PairingsBn254.Fr[STATE_WIDTH_OLD - 1] permutation_polynomials_at_z; PairingsBn254.G1Point opening_at_z_proof; PairingsBn254.G1Point opening_at_z_omega_proof; } struct PartialVerifierStateOld { PairingsBn254.Fr alpha; PairingsBn254.Fr beta; PairingsBn254.Fr gamma; PairingsBn254.Fr v; PairingsBn254.Fr u; PairingsBn254.Fr z; PairingsBn254.Fr[] cached_lagrange_evals; } function evaluate_lagrange_poly_out_of_domain_old( uint256 poly_num, uint256 domain_size, PairingsBn254.Fr memory omega, PairingsBn254.Fr memory at ) internal view returns (PairingsBn254.Fr memory res) { require(poly_num < domain_size); PairingsBn254.Fr memory one = PairingsBn254.new_fr(1); PairingsBn254.Fr memory omega_power = omega.pow(poly_num); res = at.pow(domain_size); res.sub_assign(one); require(res.value != 0); // Vanishing polynomial can not be zero at point `at` res.mul_assign(omega_power); PairingsBn254.Fr memory den = PairingsBn254.copy(at); den.sub_assign(omega_power); den.mul_assign(PairingsBn254.new_fr(domain_size)); den = den.inverse(); res.mul_assign(den); } function batch_evaluate_lagrange_poly_out_of_domain_old( uint256[] memory poly_nums, uint256 domain_size, PairingsBn254.Fr memory omega, PairingsBn254.Fr memory at ) internal view returns (PairingsBn254.Fr[] memory res) { PairingsBn254.Fr memory one = PairingsBn254.new_fr(1); PairingsBn254.Fr memory tmp_1 = PairingsBn254.new_fr(0); PairingsBn254.Fr memory tmp_2 = PairingsBn254.new_fr(domain_size); PairingsBn254.Fr memory vanishing_at_z = at.pow(domain_size); vanishing_at_z.sub_assign(one); // we can not have random point z be in domain require(vanishing_at_z.value != 0); PairingsBn254.Fr[] memory nums = new PairingsBn254.Fr[](poly_nums.length); PairingsBn254.Fr[] memory dens = new PairingsBn254.Fr[](poly_nums.length); // numerators in a form omega^i * (z^n - 1) // denoms in a form (z - omega^i) * N for (uint256 i = 0; i < poly_nums.length; i++) { tmp_1 = omega.pow(poly_nums[i]); // power of omega nums[i].assign(vanishing_at_z); nums[i].mul_assign(tmp_1); dens[i].assign(at); // (X - omega^i) * N dens[i].sub_assign(tmp_1); dens[i].mul_assign(tmp_2); // mul by domain size } PairingsBn254.Fr[] memory partial_products = new PairingsBn254.Fr[](poly_nums.length); partial_products[0].assign(PairingsBn254.new_fr(1)); for (uint256 i = 1; i < dens.length - 1; i++) { partial_products[i].assign(dens[i - 1]); partial_products[i].mul_assign(dens[i]); } tmp_2.assign(partial_products[partial_products.length - 1]); tmp_2.mul_assign(dens[dens.length - 1]); tmp_2 = tmp_2.inverse(); // tmp_2 contains a^-1 * b^-1 (with! the last one) for (uint256 i = dens.length - 1; i < dens.length; i--) { dens[i].assign(tmp_2); // all inversed dens[i].mul_assign(partial_products[i]); // clear lowest terms tmp_2.mul_assign(dens[i]); } for (uint256 i = 0; i < nums.length; i++) { nums[i].mul_assign(dens[i]); } return nums; } function evaluate_vanishing_old(uint256 domain_size, PairingsBn254.Fr memory at) internal view returns (PairingsBn254.Fr memory res) { res = at.pow(domain_size); res.sub_assign(PairingsBn254.new_fr(1)); } function verify_at_z( PartialVerifierStateOld memory state, ProofOld memory proof, VerificationKeyOld memory vk ) internal view returns (bool) { PairingsBn254.Fr memory lhs = evaluate_vanishing_old(vk.domain_size, state.z); require(lhs.value != 0); // we can not check a polynomial relationship if point `z` is in the domain lhs.mul_assign(proof.quotient_polynomial_at_z); PairingsBn254.Fr memory quotient_challenge = PairingsBn254.new_fr(1); PairingsBn254.Fr memory rhs = PairingsBn254.copy(proof.linearization_polynomial_at_z); // public inputs PairingsBn254.Fr memory tmp = PairingsBn254.new_fr(0); for (uint256 i = 0; i < proof.input_values.length; i++) { tmp.assign(state.cached_lagrange_evals[i]); tmp.mul_assign(PairingsBn254.new_fr(proof.input_values[i])); rhs.add_assign(tmp); } quotient_challenge.mul_assign(state.alpha); PairingsBn254.Fr memory z_part = PairingsBn254.copy(proof.grand_product_at_z_omega); for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) { tmp.assign(proof.permutation_polynomials_at_z[i]); tmp.mul_assign(state.beta); tmp.add_assign(state.gamma); tmp.add_assign(proof.wire_values_at_z[i]); z_part.mul_assign(tmp); } tmp.assign(state.gamma); // we need a wire value of the last polynomial in enumeration tmp.add_assign(proof.wire_values_at_z[STATE_WIDTH_OLD - 1]); z_part.mul_assign(tmp); z_part.mul_assign(quotient_challenge); rhs.sub_assign(z_part); quotient_challenge.mul_assign(state.alpha); tmp.assign(state.cached_lagrange_evals[0]); tmp.mul_assign(quotient_challenge); rhs.sub_assign(tmp); return lhs.value == rhs.value; } function reconstruct_d( PartialVerifierStateOld memory state, ProofOld memory proof, VerificationKeyOld memory vk ) internal view returns (PairingsBn254.G1Point memory res) { // we compute what power of v is used as a delinearization factor in batch opening of // commitments. Let's label W(x) = 1 / (x - z) * // [ // t_0(x) + z^n * t_1(x) + z^2n * t_2(x) + z^3n * t_3(x) - t(z) // + v (r(x) - r(z)) // + v^{2..5} * (witness(x) - witness(z)) // + v^(6..8) * (permutation(x) - permutation(z)) // ] // W'(x) = 1 / (x - z*omega) * // [ // + v^9 (z(x) - z(z*omega)) <- we need this power // + v^10 * (d(x) - d(z*omega)) // ] // // we pay a little for a few arithmetic operations to not introduce another constant uint256 power_for_z_omega_opening = 1 + 1 + STATE_WIDTH_OLD + STATE_WIDTH_OLD - 1; res = PairingsBn254.copy_g1(vk.selector_commitments[STATE_WIDTH_OLD + 1]); PairingsBn254.G1Point memory tmp_g1 = PairingsBn254.P1(); PairingsBn254.Fr memory tmp_fr = PairingsBn254.new_fr(0); // addition gates for (uint256 i = 0; i < STATE_WIDTH_OLD; i++) { tmp_g1 = vk.selector_commitments[i].point_mul(proof.wire_values_at_z[i]); res.point_add_assign(tmp_g1); } // multiplication gate tmp_fr.assign(proof.wire_values_at_z[0]); tmp_fr.mul_assign(proof.wire_values_at_z[1]); tmp_g1 = vk.selector_commitments[STATE_WIDTH_OLD].point_mul(tmp_fr); res.point_add_assign(tmp_g1); // d_next tmp_g1 = vk.next_step_selector_commitments[0].point_mul(proof.wire_values_at_z_omega[0]); res.point_add_assign(tmp_g1); // z * non_res * beta + gamma + a PairingsBn254.Fr memory grand_product_part_at_z = PairingsBn254.copy(state.z); grand_product_part_at_z.mul_assign(state.beta); grand_product_part_at_z.add_assign(proof.wire_values_at_z[0]); grand_product_part_at_z.add_assign(state.gamma); for (uint256 i = 0; i < vk.permutation_non_residues.length; i++) { tmp_fr.assign(state.z); tmp_fr.mul_assign(vk.permutation_non_residues[i]); tmp_fr.mul_assign(state.beta); tmp_fr.add_assign(state.gamma); tmp_fr.add_assign(proof.wire_values_at_z[i + 1]); grand_product_part_at_z.mul_assign(tmp_fr); } grand_product_part_at_z.mul_assign(state.alpha); tmp_fr.assign(state.cached_lagrange_evals[0]); tmp_fr.mul_assign(state.alpha); tmp_fr.mul_assign(state.alpha); grand_product_part_at_z.add_assign(tmp_fr); PairingsBn254.Fr memory grand_product_part_at_z_omega = state.v.pow(power_for_z_omega_opening); grand_product_part_at_z_omega.mul_assign(state.u); PairingsBn254.Fr memory last_permutation_part_at_z = PairingsBn254.new_fr(1); for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) { tmp_fr.assign(state.beta); tmp_fr.mul_assign(proof.permutation_polynomials_at_z[i]); tmp_fr.add_assign(state.gamma); tmp_fr.add_assign(proof.wire_values_at_z[i]); last_permutation_part_at_z.mul_assign(tmp_fr); } last_permutation_part_at_z.mul_assign(state.beta); last_permutation_part_at_z.mul_assign(proof.grand_product_at_z_omega); last_permutation_part_at_z.mul_assign(state.alpha); // add to the linearization tmp_g1 = proof.grand_product_commitment.point_mul(grand_product_part_at_z); tmp_g1.point_sub_assign(vk.permutation_commitments[STATE_WIDTH_OLD - 1].point_mul(last_permutation_part_at_z)); res.point_add_assign(tmp_g1); res.point_mul_assign(state.v); res.point_add_assign(proof.grand_product_commitment.point_mul(grand_product_part_at_z_omega)); } function verify_commitments( PartialVerifierStateOld memory state, ProofOld memory proof, VerificationKeyOld memory vk ) internal view returns (bool) { PairingsBn254.G1Point memory d = reconstruct_d(state, proof, vk); PairingsBn254.Fr memory z_in_domain_size = state.z.pow(vk.domain_size); PairingsBn254.G1Point memory tmp_g1 = PairingsBn254.P1(); PairingsBn254.Fr memory aggregation_challenge = PairingsBn254.new_fr(1); PairingsBn254.G1Point memory commitment_aggregation = PairingsBn254.copy_g1(proof.quotient_poly_commitments[0]); PairingsBn254.Fr memory tmp_fr = PairingsBn254.new_fr(1); for (uint256 i = 1; i < proof.quotient_poly_commitments.length; i++) { tmp_fr.mul_assign(z_in_domain_size); tmp_g1 = proof.quotient_poly_commitments[i].point_mul(tmp_fr); commitment_aggregation.point_add_assign(tmp_g1); } aggregation_challenge.mul_assign(state.v); commitment_aggregation.point_add_assign(d); for (uint256 i = 0; i < proof.wire_commitments.length; i++) { aggregation_challenge.mul_assign(state.v); tmp_g1 = proof.wire_commitments[i].point_mul(aggregation_challenge); commitment_aggregation.point_add_assign(tmp_g1); } for (uint256 i = 0; i < vk.permutation_commitments.length - 1; i++) { aggregation_challenge.mul_assign(state.v); tmp_g1 = vk.permutation_commitments[i].point_mul(aggregation_challenge); commitment_aggregation.point_add_assign(tmp_g1); } aggregation_challenge.mul_assign(state.v); aggregation_challenge.mul_assign(state.v); tmp_fr.assign(aggregation_challenge); tmp_fr.mul_assign(state.u); tmp_g1 = proof.wire_commitments[STATE_WIDTH_OLD - 1].point_mul(tmp_fr); commitment_aggregation.point_add_assign(tmp_g1); // collect opening values aggregation_challenge = PairingsBn254.new_fr(1); PairingsBn254.Fr memory aggregated_value = PairingsBn254.copy(proof.quotient_polynomial_at_z); aggregation_challenge.mul_assign(state.v); tmp_fr.assign(proof.linearization_polynomial_at_z); tmp_fr.mul_assign(aggregation_challenge); aggregated_value.add_assign(tmp_fr); for (uint256 i = 0; i < proof.wire_values_at_z.length; i++) { aggregation_challenge.mul_assign(state.v); tmp_fr.assign(proof.wire_values_at_z[i]); tmp_fr.mul_assign(aggregation_challenge); aggregated_value.add_assign(tmp_fr); } for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) { aggregation_challenge.mul_assign(state.v); tmp_fr.assign(proof.permutation_polynomials_at_z[i]); tmp_fr.mul_assign(aggregation_challenge); aggregated_value.add_assign(tmp_fr); } aggregation_challenge.mul_assign(state.v); tmp_fr.assign(proof.grand_product_at_z_omega); tmp_fr.mul_assign(aggregation_challenge); tmp_fr.mul_assign(state.u); aggregated_value.add_assign(tmp_fr); aggregation_challenge.mul_assign(state.v); tmp_fr.assign(proof.wire_values_at_z_omega[0]); tmp_fr.mul_assign(aggregation_challenge); tmp_fr.mul_assign(state.u); aggregated_value.add_assign(tmp_fr); commitment_aggregation.point_sub_assign(PairingsBn254.P1().point_mul(aggregated_value)); PairingsBn254.G1Point memory pair_with_generator = commitment_aggregation; pair_with_generator.point_add_assign(proof.opening_at_z_proof.point_mul(state.z)); tmp_fr.assign(state.z); tmp_fr.mul_assign(vk.omega); tmp_fr.mul_assign(state.u); pair_with_generator.point_add_assign(proof.opening_at_z_omega_proof.point_mul(tmp_fr)); PairingsBn254.G1Point memory pair_with_x = proof.opening_at_z_omega_proof.point_mul(state.u); pair_with_x.point_add_assign(proof.opening_at_z_proof); pair_with_x.negate(); return PairingsBn254.pairingProd2(pair_with_generator, PairingsBn254.P2(), pair_with_x, vk.g2_x); } function verify_initial( PartialVerifierStateOld memory state, ProofOld memory proof, VerificationKeyOld memory vk ) internal view returns (bool) { require(proof.input_values.length == vk.num_inputs); require(vk.num_inputs >= 1); TranscriptLibrary.Transcript memory transcript = TranscriptLibrary.new_transcript(); for (uint256 i = 0; i < vk.num_inputs; i++) { transcript.update_with_u256(proof.input_values[i]); } for (uint256 i = 0; i < proof.wire_commitments.length; i++) { transcript.update_with_g1(proof.wire_commitments[i]); } state.beta = transcript.get_challenge(); state.gamma = transcript.get_challenge(); transcript.update_with_g1(proof.grand_product_commitment); state.alpha = transcript.get_challenge(); for (uint256 i = 0; i < proof.quotient_poly_commitments.length; i++) { transcript.update_with_g1(proof.quotient_poly_commitments[i]); } state.z = transcript.get_challenge(); uint256[] memory lagrange_poly_numbers = new uint256[](vk.num_inputs); for (uint256 i = 0; i < lagrange_poly_numbers.length; i++) { lagrange_poly_numbers[i] = i; } state.cached_lagrange_evals = batch_evaluate_lagrange_poly_out_of_domain_old( lagrange_poly_numbers, vk.domain_size, vk.omega, state.z ); bool valid = verify_at_z(state, proof, vk); if (valid == false) { return false; } for (uint256 i = 0; i < proof.wire_values_at_z.length; i++) { transcript.update_with_fr(proof.wire_values_at_z[i]); } for (uint256 i = 0; i < proof.wire_values_at_z_omega.length; i++) { transcript.update_with_fr(proof.wire_values_at_z_omega[i]); } for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) { transcript.update_with_fr(proof.permutation_polynomials_at_z[i]); } transcript.update_with_fr(proof.quotient_polynomial_at_z); transcript.update_with_fr(proof.linearization_polynomial_at_z); transcript.update_with_fr(proof.grand_product_at_z_omega); state.v = transcript.get_challenge(); transcript.update_with_g1(proof.opening_at_z_proof); transcript.update_with_g1(proof.opening_at_z_omega_proof); state.u = transcript.get_challenge(); return true; } // This verifier is for a PLONK with a state width 4 // and main gate equation // q_a(X) * a(X) + // q_b(X) * b(X) + // q_c(X) * c(X) + // q_d(X) * d(X) + // q_m(X) * a(X) * b(X) + // q_constants(X)+ // q_d_next(X) * d(X*omega) // where q_{}(X) are selectors a, b, c, d - state (witness) polynomials // q_d_next(X) "peeks" into the next row of the trace, so it takes // the same d(X) polynomial, but shifted function verify_old(ProofOld memory proof, VerificationKeyOld memory vk) internal view returns (bool) { PartialVerifierStateOld memory state; bool valid = verify_initial(state, proof, vk); if (valid == false) { return false; } valid = verify_commitments(state, proof, vk); return valid; } } contract VerifierWithDeserializeOld is Plonk4VerifierWithAccessToDNextOld { uint256 constant SERIALIZED_PROOF_LENGTH_OLD = 33; function deserialize_proof_old(uint256[] memory public_inputs, uint256[] memory serialized_proof) internal pure returns (ProofOld memory proof) { require(serialized_proof.length == SERIALIZED_PROOF_LENGTH_OLD); proof.input_values = new uint256[](public_inputs.length); for (uint256 i = 0; i < public_inputs.length; i++) { proof.input_values[i] = public_inputs[i]; } uint256 j = 0; for (uint256 i = 0; i < STATE_WIDTH_OLD; i++) { proof.wire_commitments[i] = PairingsBn254.new_g1_checked(serialized_proof[j], serialized_proof[j + 1]); j += 2; } proof.grand_product_commitment = PairingsBn254.new_g1_checked(serialized_proof[j], serialized_proof[j + 1]); j += 2; for (uint256 i = 0; i < STATE_WIDTH_OLD; i++) { proof.quotient_poly_commitments[i] = PairingsBn254.new_g1_checked( serialized_proof[j], serialized_proof[j + 1] ); j += 2; } for (uint256 i = 0; i < STATE_WIDTH_OLD; i++) { proof.wire_values_at_z[i] = PairingsBn254.new_fr(serialized_proof[j]); j += 1; } for (uint256 i = 0; i < proof.wire_values_at_z_omega.length; i++) { proof.wire_values_at_z_omega[i] = PairingsBn254.new_fr(serialized_proof[j]); j += 1; } proof.grand_product_at_z_omega = PairingsBn254.new_fr(serialized_proof[j]); j += 1; proof.quotient_polynomial_at_z = PairingsBn254.new_fr(serialized_proof[j]); j += 1; proof.linearization_polynomial_at_z = PairingsBn254.new_fr(serialized_proof[j]); j += 1; for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) { proof.permutation_polynomials_at_z[i] = PairingsBn254.new_fr(serialized_proof[j]); j += 1; } proof.opening_at_z_proof = PairingsBn254.new_g1_checked(serialized_proof[j], serialized_proof[j + 1]); j += 2; proof.opening_at_z_omega_proof = PairingsBn254.new_g1_checked(serialized_proof[j], serialized_proof[j + 1]); } } pragma solidity ^0.7.0; // SPDX-License-Identifier: MIT OR Apache-2.0 /// @title Interface of the upgradeable contract /// @author Matter Labs interface Upgradeable { /// @notice Upgrades target of upgradeable contract /// @param newTarget New target /// @param newTargetInitializationParameters New target initialization parameters function upgradeTarget(address newTarget, bytes calldata newTargetInitializationParameters) external; } pragma solidity ^0.7.0; // SPDX-License-Identifier: MIT OR Apache-2.0 /// @title Ownable Contract /// @author Matter Labs contract Ownable { /// @dev Storage position of the masters address (keccak256('eip1967.proxy.admin') - 1) bytes32 private constant MASTER_POSITION = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /// @notice Contract constructor /// @dev Sets msg sender address as masters address /// @param masterAddress Master address constructor(address masterAddress) { setMaster(masterAddress); } /// @notice Check if specified address is master /// @param _address Address to check function requireMaster(address _address) internal view { require(_address == getMaster(), "1c"); // oro11 - only by master } /// @notice Returns contract masters address /// @return master Master's address function getMaster() public view returns (address master) { bytes32 position = MASTER_POSITION; assembly { master := sload(position) } } /// @dev Sets new masters address /// @param _newMaster New master's address function setMaster(address _newMaster) internal { bytes32 position = MASTER_POSITION; assembly { sstore(position, _newMaster) } } /// @notice Transfer mastership of the contract to new master /// @param _newMaster New masters address function transferMastership(address _newMaster) external { requireMaster(msg.sender); require(_newMaster != address(0), "1d"); // otp11 - new masters address can't be zero address setMaster(_newMaster); } }
Register creator corresponding to the factory _creatorAccountId Creator's zkSync account ID _creatorAddress NFT creator address _signature Creator's signature
function registerNFTFactoryCreator( uint32 _creatorAccountId, address _creatorAddress, bytes memory _signature ) external { require(address(nftFactories[_creatorAccountId][_creatorAddress]) == address(0), "Q"); bytes32 messageHash = keccak256(packRegisterNFTFactoryMsg(_creatorAccountId, _creatorAddress, msg.sender)); address recoveredAddress = Utils.recoverAddressFromEthSignature(_signature, messageHash); require(recoveredAddress == _creatorAddress && recoveredAddress != address(0), "ws"); nftFactories[_creatorAccountId][_creatorAddress] = NFTFactory(msg.sender); emit NFTFactoryRegisteredCreator(_creatorAccountId, _creatorAddress, msg.sender); }
10,423,188
/** *Submitted for verification at Etherscan.io on 2022-04-20 */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // // // // .;dkkkkkkkkkkkkkkkkkkd' .:xkkkkkkkkd, .:dk0XXXXXXXK0xdl,. .lxkkkkkkkkkkkkkkkkkk:.,okkkkkkko. .cxkkkkkkxc. ;dkkkkkko. // // ;xNMMMMMMMMMMMMMMMMMMMX: .:kNWMMMMMMMMWx. .l0NWWWWWMMMMMMMMMWNO;..lKWMMMMMMMMMMMMMMMMMMMKkKWMMMMMMMK, .c0WMMMMMMMMX: .;xXWMMMMMNo. // // .,lddddddddddddddddxKMMMK; .,lddddddx0WMMMX; .;llc::;;::cox0XWMMMMMWXdcoddddddddddddddddONMW0ddddddxXMMMK, .:odddddONMMMMO' .,lddddd0WWd. // // .. .dWWKl. . :XMMMWx. ... .,oKWMMMMWx. ,KMNc .kMMM0, .. .xWMMMWx'. 'kNk. // // .. .dKo' .. .xWMMMK; .. .'.. ,OWWMMWx. ,Okc' .kMMMK, .. ,0MMMMXl. .dNO' // // .. .:ooo;......,' . :XMMMWd. . .l0XXOc. ;xKMWNo. ,looc'......'... .kMMMK, .. cXMMM0, .oNK; // // .. '0MMMk. .. .kWMMMK,.' ;KMMMWNo. .;kNkc,. .dWMMK: .. .kMMMK, .. .dWMXc cXK: // // .. '0MMMXkxxxxxxxxd' . .:. cXMMMWd,' '0MMMMM0l;;;;;;:c;. .. .dWMMW0xxxxxxxxx; .kMMMK, .. 'ONd. :KXc // // .. '0MMMMMMMMMMMMMNc .. :O: .kMMMMK:. 'd0NWMWWWWWWWNXOl'... .dWMMMMMMMMMMMMWl .kMMMK, . :d' ;0No. // // .. .lkkkkkkkkkKWMMNc . .dNd. cNMMMWo.. .':dOXWMMMMMMMWXk:. :xkkkkkkkk0NMMWl .kMMMK, . . 'ONd. // // .. .oNMXd... '0M0' .kMMMM0, .. .;o0NMMMMMMWx. ,0MN0: .kMMMK, .. .kW0' // // .. cKk, . lNMNl cNMMMNo .',.. .;xXWMMMWx. 'O0c'. .kMMMK, .. .xWMO. // // .. .,ccc,.....,,. .. .kMMMk. .OMMMW0;'d0XX0xc,. :d0MMWx. ':cc:'....';. .. .kMMMK, .. .oNMMO. // // .. '0MMMk. .. ,kKKKk' lNMMMN0KWWWMMMWNKl. cXMWx. .dWMMX: .. .kMMMK, .. .OMMMO. // // .. '0MMMk'.......... ..... 'OMMKo:::::cxNMMMKl'. .OMWx. .dWMMXc.......... .kMMMK:.........,' .OMMMO. // // .. '0MMMNXKKKKKKKKd. lNM0' ;XMMMWN0c .OMWd. .dWMMWXKKKKKKKK0c .kMMMWXKKKKKKKKK0: .OMMMO. // // .. 'OWWWWWWWWWWMMNc 'llc' . '0MNc .kWMMMMX: ,KXx:. .oNWWWWWWWWWWMMWl .xWWWWWWWWWWWMMMN: .OMMMO. // // .. ,:::::::::cOWO. .xWWO' . oNMO' .lkOOx;. .'cd,... .::::::::::dXMWl '::::::::::xWMMX: .OMMWx. // // .. dNl ,0Xd. .. ,0MNo. . ..'. .. ,0WK: :NWOo, .OWKo. // // .' .oO, .co, .. .oOc.... ... .. ,xo,.. ckl..'. 'dd' // // ............................. .......... . .. . ..................... ..................... ......... // // // // // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * The contracts below implement a lazy-minted, randomized collection of ERC721A. * It requires that the creator knows the total number of NFTs they want and all belong to a token * directory, commonly will be an IPFS hash, with all the metadata from 0 to the #NFTs - 1. * * It has two main methods to lazy-mint: * One allows the owner or alternate signer to approve single-use signatures for specific wallet addresses * The other allows a general mint, multi-use signature that anyone can use. * * Minting from this collection is always random, this can be done with either a reveal mechanism that * has an optional random offset, or on-chain randomness for revealed collections, or a mix of both! * * Only with a reveal mechanism, does the price of minting utilize ERC721A improvements. */ /** * @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); } /** * @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; } } /** * @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; } /** * @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); } /** * @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); } /** * @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; } } /** * @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 internal _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); } } /** * @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); } } } } /** * @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); } } /** * @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}. * * This ERC721A is set up to better handle batch transactions. It has two layers of optimization: * * First, it assumes tokens are sequentially minted starting at _startTokenId() (defaults to 0, e.g. 0, 1, 2, 3..) * which allows for up to 5 times cheaper MINT gas fees, but does increase first time TRANSFER gas fees. * Because of this, methods have also been optimized to only call ownerOf() once as it is not a direct lookup. * * Second, it allows a permanent switch to non-sequential mint with still reduced fees because the {_mint} * only updates {_owners} and not {_balances} so that a batch mint method can update _balances a single time. * * Additionally assumes that an owner cannot have more than 2**128 - 1 (max value of uint128) of supply. */ contract ERC721A is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; struct AddressData { uint128 balance; uint128 numberMinted; } // Token name string internal _name; // Token symbol string internal _symbol; // Tracking total minted // Only used when `_isSequential` is false uint256 internal _totalMinted; // Tracking total burned uint256 internal _totalBurned; // Tracking the next sequential mint uint256 internal _nextSequential; // This ensures that ownerOf() can still run in constant time with a max runtime // of checking 5 values, but is up to 5 times cheaper on batch mints. uint256 internal constant SEQ_MINT_LIMIT = 5; // Tracking if the collection is still sequentially minted bool internal _notSequentialMint; // Mapping from token ID to owner address mapping(uint256 => address) internal _owners; // Mapping from token ID to burned // This is necessary because to optimize gas fees for multiple mints a token with // `_owners[tokenId] = address(0)` is not necessarily a token with no owner. mapping(uint256 => bool) internal _burned; // Mapping owner address to token count mapping(address => AddressData) internal _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].balance; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: owner query for nonexistent token"); if (_owners[tokenId] != address(0)) { return _owners[tokenId]; } if (tokenId < _nextSequential) { uint256 lowestTokenToCheck; if (tokenId >= SEQ_MINT_LIMIT) { lowestTokenToCheck = tokenId - SEQ_MINT_LIMIT + 1; } for (uint256 i = tokenId - 1; i >= lowestTokenToCheck; i--) { if (_owners[i] != address(0)) { return _owners[i]; } } } return address(0); } /** * @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 Returns the total current supply of the contract. * * WARNING - Underlying variables do NOT get automatically updated on mints * so that we can save gas on transactions that mint multiple tokens. * */ function totalSupply() public view virtual returns (uint256) { return totalMinted() - _totalBurned; } /** * @dev Returns the total ever minted from this contract. * * WARNING - Underlying variable do NOT get automatically updated on mints * so that we can save gas on transactions that mint multiple tokens. * */ function totalMinted() public view virtual returns (uint256) { if (_notSequentialMint) { return _totalMinted; } return _nextSequential; } /** * @dev returns how many tokens the given address has minted. */ function mintCount(address addr) external view returns (uint256) { return _balances[addr].numberMinted; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721: 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 = 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, owner); } /** * @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 { address owner = ownerOf(tokenId); require( _isApprovedOrOwner(_msgSender(), tokenId, owner), "ERC721: transfer caller is not owner nor approved" ); require(owner == from, "ERC721: transfer of token that is not own"); _transferIgnoreOwner(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * This was modified to not call _safeTransfer because that would require fetching * ownerOf() twice which is more expensive than doing it together. * * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { address owner = ownerOf(tokenId); require( _isApprovedOrOwner(_msgSender(), tokenId, owner), "ERC721: transfer caller is not owner nor approved" ); require(owner == from, "ERC721: transfer of token that is not own"); _safeTransferIgnoreOwner(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 This is for functions which already get the owner of the tokenId and can do the check * for `ownerOf(tokenId) == from` because ownerOf() in 721A is potentially an expensive function * and should not be called twice if not needed * * WARNING this method does not check for tokenOwner. This is done because with the * gas optimization calling ownerOf can be an expensive calculation and should only be done once (in the outer most layer) */ function _safeTransferIgnoreOwner( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transferIgnoreOwner(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) { if (_burned[tokenId]) { return false; } if (tokenId < _nextSequential) { return true; } return _owners[tokenId] != address(0); } /** * @dev Returns whether `sender` is allowed to manage `tokenId`. * This is for functions which already get the owner of the tokenId because ownerOf() in * 721A is potentially an expensive function and should not be called twice if not needed * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner( address sender, uint256 tokenId, address owner ) internal view virtual returns (bool) { require( _exists(tokenId), "ERC721: operator query for nonexistent token" ); return (sender == owner || getApproved(tokenId) == sender || isApprovedForAll(owner, sender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * WARNING - this method does not update totalSupply or _balances, please update that externally. Doing so * will allow us to save gas on batch transactions * * 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. * * WARNING: This method does not update totalSupply, please update that externally. Doing so * will allow us to save gas on batch transactions */ 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 * WARNING: This method does not update totalSupply or _balances, please update that externally. Doing so * will allow us to save gas on transactions that mint more than one NFT * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(_notSequentialMint, "_notSequentialMint must be true"); require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } // Sequential mint doesn't match _beforeTokenTransfer and instead has a different optional override. function _beforeSequentialMint( address to, uint256 starting, uint256 quantity ) internal virtual {} /** * @dev Mints from `_nextSequential` to `_nextSequential + quantity` and transfers it to `to`. * * WARNING: This method does not update totalSupply or _balances, please update that externally. Doing so * will allow us to save gas on transactions that mint more than one NFT * * Requirements: * * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _safeMintSequential(address to, uint256 quantity) internal virtual { require(!_notSequentialMint, "_notSequentialMint must be false"); require(to != address(0), "ERC721: mint to the zero address"); _beforeSequentialMint(to, _nextSequential, quantity); uint256 lastNum = _nextSequential + quantity; // ensures ownerOf runs quickly even if user is minting a large number like 100 for (uint256 i = _nextSequential; i < lastNum; i += SEQ_MINT_LIMIT) { _owners[i] = to; } // Gas is cheaper to have two separate for loops for (uint256 i = _nextSequential; i < lastNum; i++) { require( _checkOnERC721Received(address(0), to, i, ""), "ERC721: transfer to non ERC721Receiver implementer" ); emit Transfer(address(0), to, i); } _balances[to] = AddressData( _balances[to].balance + uint128(quantity), _balances[to].numberMinted + uint128(quantity) ); _nextSequential = lastNum; } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. Since owners[tokenId] can be * the zero address for batch mints, this has been changed to modify _burned mapping instead * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ownerOf(tokenId); require( _isApprovedOrOwner(_msgSender(), tokenId, owner), "Caller is not owner nor approved" ); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId, owner); _balances[owner].balance -= 1; _totalBurned += 1; _burned[tokenId] = true; 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( ownerOf(tokenId) == from, "ERC721: transfer of token that is not own" ); _transferIgnoreOwner(from, to, tokenId); } /** * @dev This is for functions which already get the owner of the tokenId and can do the check * for `ownerOf(tokenId) == from` because ownerOf() in 721A is potentially an expensive function * and should not be called twice if not needed * * WARNING this method does not check for tokenOwner. This is done because with the * gas optimization calling ownerOf can be an expensive calculation and should only be done once (in the outer most layer) */ function _transferIgnoreOwner( address from, address to, uint256 tokenId ) internal virtual { require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId, from); _balances[from].balance -= 1; _balances[to].balance += 1; _owners[tokenId] = to; uint256 nextTokenId = tokenId + 1; if (nextTokenId < _nextSequential) { if (_owners[nextTokenId] == address(0)) { _owners[nextTokenId] = from; } } emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) internal virtual { if (_tokenApprovals[tokenId] != to) { _tokenApprovals[tokenId] = to; emit Approval(owner, 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 {} } /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and( vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff ) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if ( uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0 ) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256( abi.encodePacked("\x19Ethereum Signed Message:\n32", hash) ); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256( abi.encodePacked("\x19\x01", domainSeparator, structHash) ); } } /** * @dev Interface for the NFT Royalty Standard */ interface IERC2981 is IERC165 { /** * ERC165 bytes to add to interface array - set in parent contract * implementing this standard * * bytes4(keccak256("royaltyInfo(uint256,uint256)")) == 0x2a55205a * bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a; * _registerInterface(_INTERFACE_ID_ERC2981); */ /** * @notice Called with the sale price to determine how much royalty * is owed and to whom. * @param _tokenId - the NFT asset queried for royalty information * @param _salePrice - the sale price of the NFT asset specified by _tokenId * @return receiver - address of who should be sent the royalty payment * @return royaltyAmount - the royalty payment amount for _salePrice */ function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view returns (address receiver, uint256 royaltyAmount); } /** * @dev External interface of the EaselyPayout contract */ interface IEaselyPayout { /** * @dev Takes in a payable amount and splits it among the given royalties. * Also takes a cut of the payable amount depending on the sender and the primaryPayout address. * Ensures that this method never splits over 100% of the payin amount. */ function splitPayable( address primaryPayout, address[] memory royalties, uint256[] memory bps ) external payable; } /** * @dev Extension of the ERC721 contract that integrates a marketplace so that simple lazy-sales * do not have to be done on another contract. This saves gas fees on secondary sales because * buyers will not have to pay a gas fee to setApprovalForAll for another marketplace contract after buying. * * Easely will help power the lazy-selling as well as lazy minting that take place on * directly on the collection, which is why we take a cut of these transactions. Our cut can * be publically seen in the connected EaselyPayout contract and cannot exceed 5%. * * Owners also set a dual signer which they can change at any time. This dual signer helps enable * sales for large batches of addresses without needing to manually sign hundreds or thousands of hashes. * It also makes phishing scams harder as both signatures need to be compromised before an unwanted sale can occur. * * Owner also has an option to allow token owners to loan their tokens to other users which makes the token * untradeable until the original owner reclaims the token. */ abstract contract ERC721Marketplace is ERC721A, Ownable { using ECDSA for bytes32; using Strings for uint256; // Allows token owners to loan tokens to other addresses. bool public loaningActive; /* see {IEaselyPayout} for more */ address public constant PAYOUT_CONTRACT_ADDRESS = 0xa95850bB73459ADB9587A97F103a4A7CCe59B56E; uint256 private constant TIME_PER_DECREMENT = 300; /* Basis points or BPS are 1/100th of a percent, so 10000 basis points accounts for 100% */ uint256 public constant BPS_TOTAL = 10000; /* Max basis points for the owner for secondary sales of this collection */ uint256 public constant MAX_SECONDARY_BPS = 1000; /* Default payout percent if there is no signature set */ uint256 private constant DEFAULT_PAYOUT_BPS = 500; /* Signer for initializing splits to ensure splits were agreed upon by both parties */ address private constant VERIFIED_CONTRACT_SIGNER = 0x1BAAd9BFa20Eb279d2E3f3e859e3ae9ddE666c52; /* * Optional addresses to distribute referral commission for this collection * * Referral commission is taken from easely's cut */ address public referralAddress; /* * Optional addresses to distribute partnership comission for this collection * * Partnership commission is taken in addition to easely's cut */ address public partnershipAddress; /* Optional addresses to distribute revenue of primary sales of this collection */ address public revenueShareAddress; /* Enables dual address signatures to lazy mint */ address public dualSignerAddress; struct WithdrawSplits { /* Optional basis points for the owner for secondary sales of this collection */ uint64 ownerRoyaltyBPS; /* Basis points for easely's payout contract */ uint64 payoutBPS; /* Optional basis points for revenue sharing the owner wants to set up */ uint64 revenueShareBPS; /* * Optional basis points for collections that have been referred. * * Contracts with this will have a reduced easely's payout cut so that * the creator's cut is unaffected */ uint32 referralBPS; /* * Optional basis points for collections that require partnerships * * Contracts with this will have this fee on top of easely's payout cut because the partnership * will offer advanced web3 integration of this contract in some form beyond what easely provides. */ uint32 partnershipBPS; } WithdrawSplits public splits; mapping(uint256 => address) internal _tokenOwnersOnLoan; /* Mapping to the active version for all signed transactions */ mapping(address => uint256) internal _addressToActiveVersion; /* Cancelled or finalized sales by hash to determine buyabliity */ mapping(bytes32 => bool) internal _cancelledOrFinalizedSales; // Events related to lazy selling event SaleCancelled(address indexed seller, bytes32 hash); event SaleCompleted( address indexed seller, address indexed buyer, uint256 indexed tokenId, uint256 price, bytes32 hash ); // Events related to loaning event LoaningActive(bool active); event Loan( address indexed from, address indexed to, uint256 indexed tokenId ); event LoanRetrieved( address indexed from, address indexed to, uint256 indexed tokenId ); // Miscellaneous events event VersionChanged(address indexed seller, uint256 version); event DualSignerChanged(address newSigner); event BalanceWithdrawn(uint256 balance); event RoyaltyUpdated(uint256 bps); event WithdrawSplitsSet( address indexed revenueShareAddress, address indexed referralAddress, address indexed partnershipAddress, uint256 payoutBPS, uint256 revenueShareBPS, uint256 referralBPS, uint256 partnershipBPS ); /** * @dev initializes all of the addresses and percentage of withdrawn funds that * each address will get. These addresses and BPS splits must be signed by both the * verified easely wallet and the creator of the contract. If a signature is missing * the contract has a default of 5% to the easely payout wallet. */ function _initWithdrawSplits( address creator_, address revenueShareAddress_, address referralAddress_, address partnershipAddress_, uint256 payoutBPS_, uint256 ownerRoyaltyBPS_, uint256 revenueShareBPS_, uint256 referralBPS_, uint256 partnershipBPS_, bytes[2] memory signatures ) internal virtual { revenueShareAddress = revenueShareAddress_; require( ownerRoyaltyBPS_ <= MAX_SECONDARY_BPS, "Cannot take more than 10% of secondaries" ); if (signatures[1].length == 0) { require( DEFAULT_PAYOUT_BPS + revenueShareBPS_ <= BPS_TOTAL, "BPS splits too high" ); splits = WithdrawSplits( uint64(ownerRoyaltyBPS_), uint64(DEFAULT_PAYOUT_BPS), uint64(revenueShareBPS_), uint32(0), uint32(0) ); emit WithdrawSplitsSet( revenueShareAddress_, address(0), address(0), DEFAULT_PAYOUT_BPS, revenueShareBPS_, 0, 0 ); } else { require( payoutBPS_ + referralBPS_ + partnershipBPS_ + revenueShareBPS_ <= BPS_TOTAL, "BPS splits too high" ); bytes memory encoded = abi.encode( "InitializeSplits", creator_, revenueShareAddress_, referralAddress_, partnershipAddress_, payoutBPS_, revenueShareBPS_, referralBPS_, partnershipBPS_ ); bytes32 hash = ECDSA.toEthSignedMessageHash(keccak256(encoded)); require( hash.recover(signatures[0]) == creator_, "Not signed by creator" ); require( hash.recover(signatures[1]) == VERIFIED_CONTRACT_SIGNER, "Not signed by verified address" ); referralAddress = referralAddress_; partnershipAddress = partnershipAddress_; splits = WithdrawSplits( uint64(ownerRoyaltyBPS_), uint64(payoutBPS_), uint64(revenueShareBPS_), uint32(referralBPS_), uint32(partnershipBPS_) ); emit WithdrawSplitsSet( revenueShareAddress_, referralAddress_, partnershipAddress_, payoutBPS_, revenueShareBPS_, referralBPS_, partnershipBPS_ ); } emit RoyaltyUpdated(ownerRoyaltyBPS_); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(Ownable).interfaceId || interfaceId == type(IERC2981).interfaceId || super.supportsInterface(interfaceId); } /** * @dev see {IERC2981-supportsInterface} */ function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view returns (address receiver, uint256 royaltyAmount) { uint256 royalty = (_salePrice * splits.ownerRoyaltyBPS) / BPS_TOTAL; return (owner(), royalty); } /** * @dev See {_currentPrice} */ function getCurrentPrice(uint256[4] memory pricesAndTimestamps) external view returns (uint256) { return _currentPrice(pricesAndTimestamps); } /** * @dev Returns the current activeVersion of an address both used to create signatures * and to verify signatures of {buyToken} and {buyNewToken} */ function getActiveVersion(address address_) external view returns (uint256) { return _addressToActiveVersion[address_]; } /** * This function, while callable by anybody will always ONLY withdraw the * contract's balance to: * * the owner's account * the addresses the owner has set up for revenue share * the easely payout contract cut - capped at 5% but can be lower for some users * * This is callable by anybody so that Easely can set up automatic payouts * after a contract has reached a certain minimum to save creators the gas fees * involved in withdrawing balances. */ function withdrawBalance(uint256 withdrawAmount) external { if (withdrawAmount > address(this).balance) { withdrawAmount = address(this).balance; } uint256 payoutBasis = withdrawAmount / BPS_TOTAL; if (splits.revenueShareBPS > 0) { payable(revenueShareAddress).transfer( payoutBasis * splits.revenueShareBPS ); } if (splits.referralBPS > 0) { payable(referralAddress).transfer(payoutBasis * splits.referralBPS); } if (splits.partnershipBPS > 0) { payable(partnershipAddress).transfer( payoutBasis * splits.partnershipBPS ); } payable(PAYOUT_CONTRACT_ADDRESS).transfer( payoutBasis * splits.payoutBPS ); uint256 remainingAmount = withdrawAmount - payoutBasis * (splits.revenueShareBPS + splits.partnershipBPS + splits.referralBPS + splits.payoutBPS); payable(owner()).transfer(remainingAmount); emit BalanceWithdrawn(withdrawAmount); } /** * @dev Allows the owner to change who the dual signer is */ function setDualSigner(address alt) external onlyOwner { dualSignerAddress = alt; emit DualSignerChanged(alt); } /** * @dev see {_setSecondary} */ function setRoyaltiesBPS(uint256 newBPS) external onlyOwner { require( newBPS <= MAX_SECONDARY_BPS, "Cannot take more than 10% of secondaries" ); splits.ownerRoyaltyBPS = uint64(newBPS); emit RoyaltyUpdated(newBPS); } /** * @dev Usable by any user to update the version that they want their signatures to check. This is helpful if * an address wants to mass invalidate their signatures without having to call cancelSale on each one. */ function updateVersion(uint256 version) external { _addressToActiveVersion[_msgSender()] = version; emit VersionChanged(_msgSender(), version); } /** * @dev To be updated by contract owner to allow for the loan functionality to be toggled */ function setLoaningActive(bool _loaningActive) public onlyOwner { loaningActive = _loaningActive; emit LoaningActive(_loaningActive); } /** * @dev Returns who is loaning the given tokenId */ function tokenOwnerOnLoan(uint256 tokenId) external view returns (address) { require(_exists(tokenId), "This token does not exist"); return _tokenOwnersOnLoan[tokenId]; } /** * @notice Allow owner to loan their tokens to other addresses */ function loan(uint256 tokenId, address receiver) external { address msgSender = msg.sender; require(loaningActive, "Loans not active"); // Transfer the token // _safeTransfer checks that msgSender is the tokenOwner _safeTransfer(msgSender, receiver, tokenId, ""); // Add it to the mapping of originally loaned tokens _tokenOwnersOnLoan[tokenId] = msgSender; emit Loan(msgSender, receiver, tokenId); } /** * @notice Allow owner to loan their tokens to other addresses */ function retrieveLoan(uint256 tokenId) external { address borrowerAddress = ownerOf(tokenId); address msgSender = msg.sender; require( _tokenOwnersOnLoan[tokenId] == msgSender, "Sender is not the token loaner" ); // Remove it from the array of loaned out tokens delete _tokenOwnersOnLoan[tokenId]; // Transfer the token back _safeTransfer(borrowerAddress, msgSender, tokenId, ""); emit LoanRetrieved(borrowerAddress, msgSender, tokenId); } /** * @dev helper method get ownerRoyalties into an array form */ function _ownerRoyalties() internal view returns (address[] memory) { address[] memory ownerRoyalties = new address[](1); ownerRoyalties[0] = owner(); return ownerRoyalties; } /** * @dev helper method get secondary BPS into array form */ function _ownerBPS() internal view returns (uint256[] memory) { uint256[] memory ownerBPS = new uint256[](1); ownerBPS[0] = splits.ownerRoyaltyBPS; return ownerBPS; } /** * @dev See {ERC721-_beforeTokenTransfer}. * * makes sure tokens on loan can't be transferred */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override(ERC721A) { super._beforeTokenTransfer(from, to, tokenId); require( _tokenOwnersOnLoan[tokenId] == address(0), "Cannot transfer token on loan" ); } /** * @dev Checks if an address is either the owner, or the approved alternate signer. */ function _checkValidSigner(address signer) internal view { require( signer == owner() || signer == dualSignerAddress, "Not valid signer." ); } /** * @dev Hash an order, returning the hash that a client must sign, including the standard message prefix * @return Hash of message prefix and order hash per Ethereum format */ function _hashForSale( address owner, uint256 version, uint256 nonce, uint256 tokenId, uint256[4] memory pricesAndTimestamps ) internal view returns (bytes32) { return keccak256( abi.encode( address(this), block.chainid, owner, version, nonce, tokenId, pricesAndTimestamps ) ); } /** * @dev Hash an order, returning the hash that a client must sign, including the standard message prefix * @return Hash of message prefix and order hash per Ethereum format */ function _hashToCheckForSale( address owner, uint256 version, uint256 nonce, uint256 tokenId, uint256[4] memory pricesAndTimestamps ) internal view returns (bytes32) { return ECDSA.toEthSignedMessageHash( _hashForSale( owner, version, nonce, tokenId, pricesAndTimestamps ) ); } /** * @dev Current price for a sale which is calculated for the case of a descending sale. So * the ending price must be less than the starting price and the timestamp is active. * Standard single fare sales will have a matching starting and ending price. */ function _currentPrice(uint256[4] memory pricesAndTimestamps) internal view returns (uint256) { uint256 startingPrice = pricesAndTimestamps[0]; uint256 endingPrice = pricesAndTimestamps[1]; uint256 startingTimestamp = pricesAndTimestamps[2]; uint256 endingTimestamp = pricesAndTimestamps[3]; uint256 currTime = block.timestamp; require(currTime >= startingTimestamp, "Has not started yet"); require( startingTimestamp < endingTimestamp, "Must end after it starts" ); require(startingPrice >= endingPrice, "Ending price cannot be bigger"); if (startingPrice == endingPrice || currTime > endingTimestamp) { return endingPrice; } uint256 diff = startingPrice - endingPrice; uint256 decrements = (currTime - startingTimestamp) / TIME_PER_DECREMENT; if (decrements == 0) { return startingPrice; } // decrements will equal 0 before totalDecrements does so we will not divide by 0 uint256 totalDecrements = (endingTimestamp - startingTimestamp) / TIME_PER_DECREMENT; return startingPrice - (diff / totalDecrements) * decrements; } /** * @dev Checks if a hash has been signed by a signer, and if this contract has a dual signer, * that the dual signer has also signed the hash */ function _checkHashAndSignatures( bytes32 hash, address signer, bytes memory signature, bytes memory dualSignature ) internal view { require(!_cancelledOrFinalizedSales[hash], "Sale no longer active"); require( hash.recover(signature) == signer, "Not signed by current owner" ); require( dualSignerAddress == address(0) || hash.recover(dualSignature) == dualSignerAddress, "Not signed by dual signer" ); } /** * @dev Usable by the owner of any token initiate a sale for their token. This does not * lock the tokenId and the owner can freely trade their token, but doing so will * invalidate the ability for others to buy. */ function hashToSignToSellToken( uint256 version, uint256 nonce, uint256 tokenId, uint256[4] memory pricesAndTimestamps ) external view returns (bytes32) { require(_msgSender() == ownerOf(tokenId), "Not the owner of the token"); return _hashForSale( _msgSender(), version, nonce, tokenId, pricesAndTimestamps ); } /** * @dev Usable to cancel hashes generated from {hashToSignToSellToken} */ function cancelSale( uint256 version, uint256 nonce, uint256 tokenId, uint256[4] memory pricesAndTimestamps ) external { bytes32 hash = _hashToCheckForSale( _msgSender(), version, nonce, tokenId, pricesAndTimestamps ); _cancelledOrFinalizedSales[hash] = true; emit SaleCancelled(_msgSender(), hash); } /** * @dev With a hash signed by the method {hashToSignToSellToken} any user sending enough value can buy * the token from the seller. Tokens not owned by the contract owner are all considered secondary sales and * will give a cut to the owner of the contract based on the secondaryOwnerBPS. */ function buyToken( address seller, uint256 version, uint256 nonce, uint256 tokenId, uint256[4] memory pricesAndTimestamps, bytes memory signature, bytes memory dualSignature ) external payable { uint256 currentPrice = _currentPrice(pricesAndTimestamps); require( _addressToActiveVersion[seller] == version, "Incorrect signature version" ); require(msg.value >= currentPrice, "Not enough ETH to buy"); bytes32 hash = _hashToCheckForSale( seller, version, nonce, tokenId, pricesAndTimestamps ); _checkHashAndSignatures(hash, seller, signature, dualSignature); _cancelledOrFinalizedSales[hash] = true; emit SaleCompleted(seller, _msgSender(), tokenId, currentPrice, hash); _safeTransfer(seller, _msgSender(), tokenId, ""); if (seller != owner()) { IEaselyPayout(PAYOUT_CONTRACT_ADDRESS).splitPayable{ value: currentPrice }(seller, _ownerRoyalties(), _ownerBPS()); } payable(_msgSender()).transfer(msg.value - currentPrice); } } /** * @dev This implements a lazy-minted, randomized collection of ERC721A. * It requires that the creator knows the total number of NFTs they want and all belong to a token * directory, commonly will be an IPFS hash, with all the metadata from 0 to the #NFTs - 1. * * It has two main methods to lazy-mint: * One allows the owner or alternate signer to approve single-use signatures for specific wallet addresses * The other allows a general mint, multi-use signature that anyone can use. * * Minting from this collection is always random, this can be done with either a reveal mechanism that * has an optional random offset, or on-chain randomness for revealed collections, or a mix of both! * * Only with a reveal mechanism, does the price of minting utilize ERC721A improvements. */ contract ERC721ARandomizedCollection is ERC721Marketplace { using ECDSA for bytes32; using Strings for uint256; bool public burnable; // This returns whether or not a collection has been locked yet bool public isLocked; /* * If this is set to true the owner must complete a signature for each address on the allowlist. * If it is false, only the dualSignerAddress is required, which can be a programatic signer the * owner is associted with that can easily sign tens of thousands of signatures. */ bool private requireOwnerOnAllowlist; bool private hasInit = false; uint256 public maxSupply; // Limits how much any single transaction can be uint256 public transactionMax; // Limits how much any single wallet can mint on a collection. uint256 public maxMint; // Used to shuffle tokenURI upon reveal uint256 public offset; // This limit is necessary for onchain randomness uint256 public constant MAX_SUPPLY_LIMIT = 10**9; // Mapping to enable constant time onchain randomness uint256[MAX_SUPPLY_LIMIT] private indices; string public tokenDirectory; // Randomized Collection Events event Minted( address indexed buyer, uint256 amount, uint256 unitPrice, bytes32 hash ); event TokensRevealed(string tokenDirectory); event TokenSupplyLocked(uint256 supply); event TokenDirectoryLocked(); event RequireOwnerOnAllowList(bool required); /** * @dev Constructor function */ constructor( bool[2] memory bools, address[4] memory addresses, uint256[8] memory uints, string[3] memory strings, bytes[2] memory signatures ) ERC721A(strings[0], strings[1]) { _init(bools, addresses, uints, strings, signatures); } function init( bool[2] memory bools, address[4] memory addresses, uint256[8] memory uints, string[3] memory strings, bytes[2] memory signatures ) external { _init(bools, addresses, uints, strings, signatures); } function _init( bool[2] memory bools, address[4] memory addresses, uint256[8] memory uints, string[3] memory strings, bytes[2] memory signatures ) internal { require(!hasInit, "Already has be initiated"); hasInit = true; burnable = bools[0]; _notSequentialMint = bools[1]; _owner = msg.sender; _initWithdrawSplits( _owner, addresses[0], // revenue share address addresses[1], // referral address addresses[2], // partnership address uints[0], // payout BPS uints[1], // owner secondary BPS uints[2], // revenue share BPS uints[3], // referral BPS uints[4], // partnership BPS signatures ); dualSignerAddress = addresses[3]; maxSupply = uints[5]; require(maxSupply < MAX_SUPPLY_LIMIT, "Collection is too big"); // Do not allow more than 500 mints a transaction so users cannot exceed gas limit if (uints[6] == 0 || uints[6] >= 500) { transactionMax = 500; } else { transactionMax = uints[6]; } maxMint = uints[7]; _name = strings[0]; _symbol = strings[1]; tokenDirectory = strings[2]; if (_notSequentialMint) { emit TokensRevealed(tokenDirectory); } } /** * @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 override returns (string memory) { return "ipfs://"; } /** * @dev sets if the owner's signature is also necessary for dual signing. * * This is normally turned off because the dual signer can be an automated * process that can sign hundreds to thousands of sale permits instantly which * would be tedious for a human-operated wallet. */ function setRequireOwnerOnAllowlist(bool required) external onlyOwner { requireOwnerOnAllowlist = required; emit RequireOwnerOnAllowList(required); } /** * @dev If this collection was created with burnable on, owners of tokens * can use this method to burn their tokens. Easely will keep track of * burns in case creators want to reward users for burning tokens. */ function burn(uint256 tokenId) external { require(burnable, "Tokens from this collection are not burnable"); _burn(tokenId); } /** * @dev Method used if the creator wants to keep their collection hidden until * a later release date. On reveal, a collection no longer uses the mint savings * of ERC721A in favor of enabling on-chain randomness minting since the metadata * is no longer hidden. * * Additionally, this method has the option to set a random offset once upon reveal * but once that offset is set it cannot be changed to maintain user consistency. * * This method does not lock the tokenURI as there are cases when the initial metadata is * inaccurate and may need to be updated. The owner of the collection should call {lockTokenURI} * when they are certain of their metadata. */ function changeTokenURI( string calldata revealTokenDirectory, bool shouldOffset ) external onlyOwner { require(!isLocked, "The token URI has been locked"); if (shouldOffset && offset == 0) { offset = _random(maxSupply - 1) + 1; } tokenDirectory = revealTokenDirectory; _notSequentialMint = true; _totalMinted = _nextSequential; emit TokensRevealed(revealTokenDirectory); } /** * Prevents token metadata in this collection from ever changing. * * IMPORTANT - this function can only be called ONCE, if a wrong token directory * is submitted by the owner, it can NEVER be switched to a different one. */ function lockTokenURI() external onlyOwner { require(!isLocked, "Contract already locked"); isLocked = true; emit TokenDirectoryLocked(); } /** * Stops tokens from ever being minted past the current supply. * * IMPORTANT - this function can NEVER be undone. It is for collections * that have not sold out, and the owner choosing to essentially "burn" * the unminted tokens to give more value to the ones already minted. */ function lockTokenSupply() external onlyOwner { require(_notSequentialMint, "The token URI has not been set yet"); // This will lock the unminted tokens at reveal time maxSupply = _totalMinted; emit TokenSupplyLocked(_totalMinted); } /** * @dev tokenURI of a tokenId, will change to include the tokeId and an offset in * the URI once the collection has been revealed. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_notSequentialMint) { return string(abi.encodePacked(_baseURI(), tokenDirectory)); } require(_exists(tokenId), "URI query for nonexistent token"); uint256 offsetId = (tokenId + offset) % maxSupply; return string( abi.encodePacked( _baseURI(), tokenDirectory, "/", offsetId.toString() ) ); } /** * @dev Hash that the owner or alternate wallet must sign to enable a {mintAllow} for a user * @return Hash of message prefix and order hash per Ethereum format */ function _hashForAllowList( address allowedAddress, uint256 nonce, uint256 version, uint256 price, uint256 amount ) internal view returns (bytes32) { return keccak256( abi.encode( address(this), block.chainid, owner(), allowedAddress, nonce, version, price, amount ) ); } /** * @dev Hash an order that we need to check against the signature to see who the signer is. * see {_hashForAllowList} to see the hash that needs to be signed. */ function _hashToCheckForAllowList( address allowedAddress, uint256 nonce, uint256 version, uint256 price, uint256 amount ) internal view returns (bytes32) { return ECDSA.toEthSignedMessageHash( _hashForAllowList(allowedAddress, nonce, version, price, amount) ); } /** * @dev Hash that the owner or approved alternate signer then sign that the approved buyer * can use in order to call the {mintAllow} method. */ function hashToSignForAllowList( address allowedAddress, uint256 version, uint256 nonce, uint256 price, uint256 amount ) external view returns (bytes32) { _checkValidSigner(_msgSender()); return _hashForAllowList(allowedAddress, version, nonce, price, amount); } /** * @dev A way to invalidate a signature so the given params cannot be used in the {mintAllow} method. */ function cancelAllowList( address allowedAddress, uint256 version, uint256 nonce, uint256 price, uint256 amount ) external { _checkValidSigner(_msgSender()); bytes32 hash = _hashToCheckForAllowList( allowedAddress, version, nonce, price, amount ); _cancelledOrFinalizedSales[hash] = true; emit SaleCancelled(_msgSender(), hash); } /** * @dev Allows a user with an approved signature to mint at a price and quantity specified by the * contract. A user is still limited by totalSupply, transactionMax, and mintMax if populated. * signing with amount = 0 will allow any buyAmount less than the other limits. */ function mintAllow( address allowedAddress, uint256 version, uint256 nonce, uint256 price, uint256 amount, uint256 buyAmount, bytes memory signature, bytes memory dualSignature ) external payable { require( totalMinted() + buyAmount <= maxSupply, "Over token supply limit" ); require(buyAmount <= amount && buyAmount > 0, "Invalid buyAmount"); require(buyAmount <= transactionMax, "Over transaction limit"); require( version == _addressToActiveVersion[owner()], "This presale version is disabled" ); require(allowedAddress == _msgSender(), "Invalid sender"); require(!Address.isContract(_msgSender()), "Cannot mint from contract"); uint256 totalPrice = price * buyAmount; require(msg.value >= totalPrice, "Msg value too small"); bytes32 hash = _hashToCheckForAllowList( allowedAddress, version, nonce, price, amount ); require(!_cancelledOrFinalizedSales[hash], "Signature not active"); if (hash.recover(signature) != owner()) { require( !requireOwnerOnAllowlist && dualSignerAddress != address(0) && hash.recover(dualSignature) == dualSignerAddress, "Not signed by dual signer or owner" ); } _cancelledOrFinalizedSales[hash] = true; _mintRandom(_msgSender(), buyAmount); emit Minted(_msgSender(), buyAmount, price, hash); payable(_msgSender()).transfer(msg.value - totalPrice); } /** * @dev Hash that the owner or alternate wallet must sign to enable {mint} for all users */ function _hashForMint( uint256 version, uint256 amount, uint256[4] memory pricesAndTimestamps ) internal view returns (bytes32) { return keccak256( abi.encode( address(this), block.chainid, owner(), amount, pricesAndTimestamps, version ) ); } /** * @dev Hash an order that we need to check against the signature to see who the signer is. * see {_hashForMint} to see the hash that needs to be signed. */ function _hashToCheckForMint( uint256 version, uint256 amount, uint256[4] memory pricesAndTimestamps ) internal view returns (bytes32) { return ECDSA.toEthSignedMessageHash( _hashForMint(version, amount, pricesAndTimestamps) ); } /** * @dev Hash that the owner or approved alternate signer then sign that buyers use * in order to call the {mint} method. */ function hashToSignForMint( uint256 version, uint256 amount, uint256[4] memory pricesAndTimestamps ) external view returns (bytes32) { _checkValidSigner(_msgSender()); require(amount <= transactionMax, "Over transaction limit"); return _hashForMint(version, amount, pricesAndTimestamps); } /** * @dev A way to invalidate a signature so the given params cannot be used in the {mint} method. */ function cancelMint( uint256 version, uint256 amount, uint256[4] memory pricesAndTimestamps ) external { _checkValidSigner(_msgSender()); bytes32 hash = _hashToCheckForMint( version, amount, pricesAndTimestamps ); _cancelledOrFinalizedSales[hash] = true; emit SaleCancelled(_msgSender(), hash); } /** * @dev Allows anyone to buy an amount of tokens at a price which matches * the signature that the owner or alternate signer has approved */ function mint( uint256 version, uint256 amount, uint256 buyAmount, uint256[4] memory pricesAndTimestamps, bytes memory signature, bytes memory dualSignature ) external payable { require( totalMinted() + buyAmount <= maxSupply, "Over token supply limit" ); require(buyAmount != 0, "Invalid buyAmount"); require(buyAmount == amount || amount == 0, "Over signature amount"); require(buyAmount <= transactionMax, "Over transaction limit"); require(version == _addressToActiveVersion[owner()], "Invalid version"); require(!Address.isContract(_msgSender()), "Cannot mint from contract"); uint256 unitPrice = _currentPrice(pricesAndTimestamps); uint256 totalPrice = buyAmount * unitPrice; require(msg.value >= totalPrice, "Msg value too small"); bytes32 hash = _hashToCheckForMint( version, amount, pricesAndTimestamps ); _checkHashAndSignatures(hash, owner(), signature, dualSignature); _mintRandom(_msgSender(), buyAmount); emit Minted(_msgSender(), buyAmount, unitPrice, hash); payable(_msgSender()).transfer(msg.value - totalPrice); } /// @notice Generates a pseudo random index of our tokens that has not been used so far function _mintRandomIndex(address buyer, uint256 amount) internal { // number of tokens left to create uint256 supplyLeft = maxSupply - _totalMinted; for (uint256 i = 0; i < amount; i++) { // generate a random index uint256 index = _random(supplyLeft); uint256 tokenAtPlace = indices[index]; uint256 tokenId; // if we havent stored a replacement token... if (tokenAtPlace == 0) { //... we just return the current index tokenId = index; } else { // else we take the replace we stored with logic below tokenId = tokenAtPlace; } // get the highest token id we havent handed out uint256 lastTokenAvailable = indices[supplyLeft - 1]; // we need to store a replacement token for the next time we roll the same index // if the last token is still unused... if (lastTokenAvailable == 0) { // ... we store the last token as index indices[index] = supplyLeft - 1; } else { // ... we store the token that was stored for the last token indices[index] = lastTokenAvailable; } _safeMint(buyer, tokenId + _nextSequential); supplyLeft--; } _balances[buyer] = AddressData( _balances[buyer].balance + uint128(amount), _balances[buyer].numberMinted + uint128(amount) ); } /// @notice Generates a pseudo random number based on arguments with decent entropy /// @param max The maximum value we want to receive /// @return A random number less than the max function _random(uint256 max) internal view returns (uint256) { if (max == 0) { return 0; } uint256 rand = uint256( keccak256( abi.encode( msg.sender, block.difficulty, block.timestamp, blockhash(block.number - 1) ) ) ); return rand % max; } /** * @dev Wrapper around {_mintRandomIndex} that incrementally if the collection has not * been revealed yet, which also checks the buyer has not exceeded maxMint count */ function _mintRandom(address buyer, uint256 amount) internal { require( maxMint == 0 || _balances[buyer].numberMinted + amount <= maxMint, "Buyer over mint maximum" ); if (_notSequentialMint) { _mintRandomIndex(buyer, amount); _totalMinted += amount; } else { _safeMintSequential(buyer, amount); } } }
Generates a pseudo random index of our tokens that has not been used so far number of tokens left to create generate a random index if we havent stored a replacement token...... we just return the current index else we take the replace we stored with logic below we need to store a replacement token for the next time we roll the same index if the last token is still unused... ... we store the last token as index ... we store the token that was stored for the last token
function _mintRandomIndex(address buyer, uint256 amount) internal { uint256 supplyLeft = maxSupply - _totalMinted; for (uint256 i = 0; i < amount; i++) { uint256 index = _random(supplyLeft); uint256 tokenAtPlace = indices[index]; uint256 tokenId; if (tokenAtPlace == 0) { tokenId = index; tokenId = tokenAtPlace; } if (lastTokenAvailable == 0) { indices[index] = supplyLeft - 1; indices[index] = lastTokenAvailable; } _safeMint(buyer, tokenId + _nextSequential); supplyLeft--; } _balances[buyer] = AddressData( _balances[buyer].balance + uint128(amount), _balances[buyer].numberMinted + uint128(amount) ); }
6,735,497
pragma solidity ^0.4.24; import "../common/Owned.sol"; import "../common/SafeMath.sol"; import "./IFund.sol"; /**@dev This contract is used to split incoming ether in proportions between 2 or more receivers The share of each one is stored in sharePermille mapping.*/ contract EtherFund is Owned, SafeMath, IFund { event EtherWithdrawn(address indexed receiver, address indexed to, uint256 amount); event EtherReceived(address indexed sender, uint256 amount); event ReceiverChanged(address indexed oldOne, address indexed newOne); event ShareChanged(address indexed receiver, uint16 share); uint16 constant MAXPERMILLE = 1000; /**@dev The share of a specific address, in permille (1/1000) */ mapping (address => uint16) public sharePermille; /**@dev Ether balance to withdraw */ mapping (address => uint256) public etherBalance; /**@dev The contract balance at last claim (transfer or withdraw) */ uint public lastBalance; /**@dev The totalDeposits at the time of last claim */ mapping (address => uint256) public lastSumDeposits; /**@dev The summation of ether deposited up to when a receiver last triggered a claim */ uint public sumDeposits; constructor(address receiver1, uint16 share1, address receiver2, uint16 share2) public { require(share1 <= MAXPERMILLE && share2 <= MAXPERMILLE); require(share1 + share2 == MAXPERMILLE); sharePermille[receiver1] = share1; sharePermille[receiver2] = share2; emit ShareChanged(receiver1, share1); emit ShareChanged(receiver2, share2); } /**@dev allows to receive Ether */ function () public payable { emit EtherReceived(msg.sender, msg.value); } /**@dev Transfers all stored Ether to the new fund */ function migrate(address newFund) public ownerOnly { newFund.transfer(address(this).balance); } /**@dev Copies internal state of another fund for specific receiver */ function copyStateFor(EtherFund otherFund, address [] receivers) public ownerOnly { uint256 sum = 0; for(uint256 i = 0; i < receivers.length; ++i) { sharePermille[receivers[i]] = otherFund.sharePermille(receivers[i]); etherBalance[receivers[i]] = otherFund.etherBalance(receivers[i]); lastSumDeposits[receivers[i]] = otherFund.lastSumDeposits(receivers[i]); sum = safeAdd(sum, sharePermille[receivers[i]]); require(sharePermille[receivers[i]] <= MAXPERMILLE); } //check that all the receivers are copied, sum of their shares should equal 1000 require(sum == MAXPERMILLE); lastBalance = otherFund.lastBalance(); sumDeposits = otherFund.sumDeposits(); } /**@dev Returns total ether deposits to date */ function deposits() public view returns (uint) { return safeAdd(sumDeposits, safeSub(address(this).balance, lastBalance)); } /**@dev Returns how much ether can be claimed */ function etherBalanceOf(address receiver) public view returns (uint) { return safeAdd(etherBalance[receiver], claimableEther(receiver)); } /**@dev Withdraw share. Throws on failure */ function withdraw(uint amount) public { withdrawTo(msg.sender, amount); } function withdrawTo(address to, uint amount) public { update(msg.sender); // check balance and withdraw on valid amount require(amount <= etherBalance[msg.sender]); etherBalance[msg.sender] = safeSub(etherBalance[msg.sender], amount); lastBalance = safeSub(lastBalance, amount); emit EtherWithdrawn(msg.sender, to, amount); to.transfer(amount); } /**@dev Changes receiver to the new one */ function changeReceiver(address oldReceiver, address newReceiver) public ownerOnly { sharePermille[newReceiver] = sharePermille[oldReceiver]; sharePermille[oldReceiver] = 0; etherBalance[newReceiver] = etherBalance[oldReceiver]; etherBalance[oldReceiver] = 0; lastSumDeposits[newReceiver] = lastSumDeposits[oldReceiver]; lastSumDeposits[oldReceiver] = 0; emit ReceiverChanged(oldReceiver, newReceiver); } /**@dev Changes the share of 2 given addresses. Requires 2 addresses: increased and decreased, to ensure that sum of shares is unchanged */ function changeShares(address receiver1, uint16 share1, address receiver2, uint16 share2) public ownerOnly { require(share1 <= MAXPERMILLE && share2 <= MAXPERMILLE); //check the input parameters, sum should be unchanged require(share1 + share2 == sharePermille[receiver1] + sharePermille[receiver2]); update(receiver1); update(receiver2); sharePermille[receiver1] = share1; sharePermille[receiver2] = share2; emit ShareChanged(receiver1, share1); emit ShareChanged(receiver2, share2); } /**@dev Changes the share of 3 given addresses. Requires 3 addresses, to ensure that sum of shares is unchanged */ function changeShares3(address receiver1, uint16 share1, address receiver2, uint16 share2, address receiver3, uint16 share3) public ownerOnly { require(share1 <= MAXPERMILLE && share2 <= MAXPERMILLE && share3 <= MAXPERMILLE); //check the input parameters, sum should be unchanged require(share1 + share2 + share3 == sharePermille[receiver1] + sharePermille[receiver2] + sharePermille[receiver3]); update(receiver1); update(receiver2); update(receiver3); sharePermille[receiver1] = share1; sharePermille[receiver2] = share2; sharePermille[receiver3] = share3; emit ShareChanged(receiver1, share1); emit ShareChanged(receiver2, share2); emit ShareChanged(receiver3, share3); } /**@dev updates state of receiver at the moment of ether withdraw */ function update(address receiver) internal { // Update unprocessed deposits if (lastBalance != address(this).balance) { sumDeposits = deposits(); //first update depoists! lastBalance = address(this).balance; //only then make lastBalanve equal to the current! } // Claim share of deposits since last claim etherBalance[receiver] = etherBalanceOf(receiver); // Snapshot deposits summation lastSumDeposits[receiver] = sumDeposits; } /**@dev How much ether since last deposit can be claimed */ function claimableEther(address receiver) internal view returns (uint256) { return safeSub(deposits(), lastSumDeposits[receiver]) * sharePermille[receiver] / MAXPERMILLE; } }
check the input parameters, sum should be unchanged
function changeShares3(address receiver1, uint16 share1, address receiver2, uint16 share2, address receiver3, uint16 share3) public ownerOnly { require(share1 <= MAXPERMILLE && share2 <= MAXPERMILLE && share3 <= MAXPERMILLE); require(share1 + share2 + share3 == sharePermille[receiver1] + sharePermille[receiver2] + sharePermille[receiver3]); update(receiver1); update(receiver2); update(receiver3); sharePermille[receiver1] = share1; sharePermille[receiver2] = share2; sharePermille[receiver3] = share3; emit ShareChanged(receiver1, share1); emit ShareChanged(receiver2, share2); emit ShareChanged(receiver3, share3); }
14,057,642
./full_match/1/0xa3a592a37803f48da9cA6c0558Ef1Fe96181c175/sources/lib/rain.interface.interpreter/src/LibEncodedDispatch.sol
Decodes an `EncodedDispatch` to its constituent parts. dispatch_ The `EncodedDispatch` to decode. return The expression, source index, and max outputs as per `encode`.
function decode(EncodedDispatch dispatch_) internal pure returns (address, SourceIndex, uint16) { return ( address(uint160(EncodedDispatch.unwrap(dispatch_) >> 32)), SourceIndex.wrap(uint16(EncodedDispatch.unwrap(dispatch_) >> 16)), uint16(EncodedDispatch.unwrap(dispatch_)) ); }
17,080,392
./partial_match/4/0xdc629dC4a89eC8d533b3D7Da0D9FF3a7a0d2c105/sources/UpgradeableToken.sol
Somebody has upgraded some of his tokens./ New upgrade agent available./ Do not allow construction without upgrade master set./
function UpgradeableToken(address master) internal { setUpgradeMaster(master); }
8,690,772
// SPDX-License-Identifier: MIT pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /// @title Un contrat de passeport animaliers /// @author Théo, Streed, Nico, Mika /// @notice Ce contrat permet d'associer des animaux à des utilisateurs via des vétérinaires contract Noe is ERC721, Ownable { using Counters for Counters.Counter; // Utilisation du contract Counter d'openzeppelin importait en ligne 6 Counters.Counter private _tokenIds; // Utilisation de la fonction Counter pour associer un _tokenIds address payable private _superAdmin; // Adresse de la personne qui déploie /// @notice Name and symbol of the non fungible token, as defined in ERC721. constructor(address payable superAdmin) public ERC721("Noe", "NOE") { // Constucteur transferFrom(superAdmin); } enum Animals {dog, cat, ferret} // Enumération event MemberCreated(address indexed _address); // Event pour la créaction d'un membre event VeterinaryCreated(address indexed _address); // Event pour la créaction d'un vétérinaire event VeterinaryApprove(address indexed _address); // Event pour que superAdmin approuve un vétérinaire event AnimalToken(address indexed _address); // Event pour qu'un vétérinaire crée un animal struct Member { // Structure membres string name; // Nom du membre string tel; // Numéro de téléphone du membre bool isMember; // False par défaut, true si la pérsonne est déjà enregistré } struct Animal { // Structure animales string name; // Nom de l'animal string dateBirth; // Date de naissance de l'animal string sexe; // Sexe de l'animal bool vaccin; // Si il est vacciné ou non Animals animals; // Enumération de chien chat furret } struct Veterinary { // Structure vétérinaire string name; // Nom du vétérinaire string tel; // Numéro de téléphone du vétérinaire bool diploma; // False par defaut, le super admin approuve le vétérinaire une fois les diplomes valide bool isVeterinary; // False par defaut, il devient vétérinaire une fois que le super admin approuve } uint256 public animalsCount; // Variable de statut pour compter le nombre d'animaux /// @dev Mapping de la struct Animal mapping(uint256 => Animal) private _animal; /// @dev Mapping de la struct Member mapping(address => Member) public member; /// @dev Mapping de la struct Veterinary mapping(address => Veterinary) public veterinary; // This modifer, vérifie si c'est le super admin modifier isSuperAdmin() { require(msg.sender == _superAdmin, "Vous n'avez pas le droit d'utiliser cette fonction"); _; } // This modifer, vérifie si le membre est déjà enregistré modifier onlyMember() { require(member[msg.sender].isMember == true, "Vous n'étes pas membre"); _; } // This modifer, vérifie si le membre n'est pas déjà enregistré modifier onlyNotMember() { require(member[msg.sender].isMember == false, "Vous étes déjà membre"); _; } // This modifer, vérifie si le vétérinaire est déjà enregistré modifier onlyVeterinary() { require(veterinary[msg.sender].isVeterinary == true, "Vous n'étes pas vétérinaire"); _; } // This modifer, vérifie si le vétérinaire est déjà enregistré et approuvé modifier onlyVeterinaryApprove() { require(veterinary[msg.sender].diploma == true, "Vous n'étes pas un vétérinaire approuvé"); _; } // This modifer, vérifie si le vétérinaire n'est pas déjà enregistré modifier onlyNotVeterinary() { require(veterinary[msg.sender].isVeterinary == false, "Vous étes déjà vétérinaire"); _; } // This modifer, vérifie si l'animal éxiste ou pas modifier animalIdCheck(uint256 animalId) { require(animalId < animalsCount, "L'animal n'éxiste pas"); _; } /// @dev Permet de créer un nouveau membre en vérifiant qu'il n'est pas déjà membre /// @param _name set le nom du membre dans la struct Member /// @param _tel set le numéro de téléphone dans la struct Member function createMember(string memory _name, string memory _tel) public onlyNotMember() { member[msg.sender] = Member({name: _name, tel: _tel, isMember: true}); emit MemberCreated(msg.sender); /// emit de l'event MemberCreated } /// @dev Permet de récuperer les infos function getMember() public view returns (Member memory) { return member[msg.sender]; } /// @dev Permet de créer un compte vétérinaire sous réserve de validation du diplôme par le super admin et la fonction approveVeterinary /// @param _name set le nom du membre dans la struct vétérinaire /// @param _tel set le nom du téléphone dans la struct vétérinaire function createVeterinary(string memory _name, string memory _tel) public onlyNotVeterinary() { veterinary[msg.sender] = Veterinary({name: _name, tel: _tel, diploma: false, isVeterinary: true}); emit VeterinaryCreated(msg.sender); } /// @dev Permet de récuperer les infos function getVeterinary() public view returns (Veterinary memory) { return veterinary[msg.sender]; } /// @dev Permet de valider le compte vétérinaire après vérification du diplôme /// @param _addr passe l'adresse du vétérinaire à approuver function approveVeterinary(address _addr) public isSuperAdmin { veterinary[_addr].diploma = true; // Set à true le diplome dans la struct Veterinary emit VeterinaryApprove(msg.sender); /// emit de l'event VeterinaryApprove } /// @dev Crée un animal et lui associe un token ERC721 /// @param _member du membre à qui attibuer l'animal/token /// @param _name le nom de l'animal /// @param _dateBirth date de naissance de l'animal /// @param _sexe le sex de l'animal /// @param _vaccin si l'animal est vacciné ou non /// @param animals_ le type d'animal de l'énunération /// @return le numéro de token function animalToken( address _member, string memory _name, string memory _dateBirth, string memory _sexe, bool _vaccin, Animals animals_ ) public onlyVeterinaryApprove() returns (uint256) { animalsCount++; _tokenIds.increment(); uint256 newTokenId = _tokenIds.current(); _mint(_member, newTokenId); _animal[newTokenId] = Animal({ name: _name, dateBirth: _dateBirth, sexe: _sexe, vaccin: _vaccin, animals: animals_ }); emit AnimalToken(msg.sender); /// emit de l'event AnimalToken return newTokenId; } /// @dev Permet de retrouver un animal en fonction de son numéro de token /// @param tokenId retrouver un animal via son numéro de token function getAnimalById(uint256 tokenId) public view returns (Animal memory) { require(_exists(tokenId), "NOE: Animal query for no nexistent token"); return _animal[tokenId]; } }
Permet de récuperer les infos
function getMember() public view returns (Member memory) { return member[msg.sender]; }
14,086,642
pragma solidity ^0.4.24; import "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol"; import "@evolutionland/common/contracts/interfaces/ISettingsRegistry.sol"; import "@evolutionland/common/contracts/interfaces/ERC223.sol"; import "@evolutionland/common/contracts/interfaces/ITokenUse.sol"; import "./interfaces/IApostleBase.sol"; import "./SiringAuctionBase.sol"; /// @title Clock auction for non-fungible tokens. contract SiringClockAuction is SiringAuctionBase { bool private singletonLock = false; /* * Modifiers */ modifier singletonLockCall() { require(!singletonLock, "Only can call once"); _; singletonLock = true; } function initializeContract(ISettingsRegistry _registry) public singletonLockCall { owner = msg.sender; emit LogSetOwner(msg.sender); registry = _registry; } /// @dev Cancels an auction that hasn't been won yet. /// Returns the NFT 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(uint256 _tokenId) public { 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 NFTs are returned to /// the seller. This should only be used in emergencies. /// @param _tokenId - ID of the NFT on auction to cancel. function cancelAuctionWhenPaused(uint256 _tokenId) whenPaused onlyOwner public { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); _cancelAuction(_tokenId, auction.seller); } /// @dev Returns auction info for an NFT on auction. /// @param _tokenId - ID of NFT on auction. function getAuction(uint256 _tokenId) public view returns ( address seller, uint256 startingPrice, uint256 endingPrice, uint256 duration, uint256 startedAt, address token ) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return ( auction.seller, uint256(auction.startingPriceInToken), uint256(auction.endingPriceInToken), uint256(auction.duration), uint256(auction.startedAt), auction.token ); } /// @dev Returns the current price of an auction. /// @param _tokenId - ID of the token price we are checking. function getCurrentPriceInToken(uint256 _tokenId) public view returns (uint256) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return _currentPrice(auction); } function receiveApproval( address _from, uint256 _tokenId, bytes //_extraData ) public whenNotPaused { if (msg.sender == registry.addressOf(SettingIds.CONTRACT_OBJECT_OWNERSHIP)) { uint256 startingPriceInRING; uint256 endingPriceInRING; uint256 duration; address seller; assembly { let ptr := mload(0x40) calldatacopy(ptr, 0, calldatasize) startingPriceInRING := mload(add(ptr, 132)) endingPriceInRING := mload(add(ptr, 164)) duration := mload(add(ptr, 196)) seller := mload(add(ptr, 228)) } // TODO: add parameter _token _createAuction(_from, _tokenId, startingPriceInRING, endingPriceInRING, duration, now, seller, registry.addressOf(SettingIds.CONTRACT_RING_ERC20_TOKEN)); } } function tokenFallback(address _from, uint256 _valueInToken, bytes _data) public whenNotPaused { uint sireId; uint matronId; assembly { let ptr := mload(0x40) calldatacopy(ptr, 0, calldatasize) matronId := mload(add(ptr, 132)) sireId := mload(add(ptr, 164)) } // safer for users require(msg.sender == tokenIdToAuction[sireId].token); require(tokenIdToAuction[sireId].startedAt > 0); uint256 autoBirthFee = registry.uintOf(UINT_AUTOBIRTH_FEE); // Check that the incoming bid is higher than the current price uint priceInToken = getCurrentPriceInToken(sireId); require(_valueInToken >= (priceInToken + autoBirthFee), "your offer is lower than the current price, try again with a higher one."); Auction storage auction = tokenIdToAuction[sireId]; require(now >= uint256(auction.startedAt), "you cant bid before the auction starts."); address seller = auction.seller; _removeAuction(sireId); uint refund = _valueInToken - priceInToken - autoBirthFee; if (refund > 0) { ERC20(msg.sender).transfer(_from, refund); } if (priceInToken > 0) { _bidWithToken(msg.sender, _from, seller, sireId, matronId, priceInToken, autoBirthFee); } } function _bidWithToken( address _auctionToken, address _from, address _seller, uint256 _sireId, uint256 _matronId, uint256 _priceInToken, uint256 _autoBirthFee) internal { //uint256 ownerCutAmount = _computeCut(priceInToken); uint cut = _computeCut(_priceInToken); ERC223(_auctionToken).transfer(_seller, (_priceInToken - cut), toBytes(_from)); ERC223(_auctionToken).transfer(registry.addressOf(CONTRACT_REVENUE_POOL), (cut + _autoBirthFee), toBytes(_from)); IApostleBase(registry.addressOf(CONTRACT_APOSTLE_BASE)).approveSiring(_from, _sireId); address apostleBase = registry.addressOf(CONTRACT_APOSTLE_BASE); require(IApostleBase(apostleBase).breedWithInAuction(_matronId, _sireId)); ERC721(registry.addressOf(SettingIds.CONTRACT_OBJECT_OWNERSHIP)).transferFrom(address(this), _seller, _sireId); // Tell the world! emit AuctionSuccessful(_sireId, _priceInToken, _from); } function toBytes(address x) public pure returns (bytes b) { b = new bytes(32); assembly {mstore(add(b, 32), x)} } // to apply for the safeTransferFrom function onERC721Received( address, //_operator, address, //_from, uint256, // _tokenId, bytes //_data ) public returns (bytes4) { return bytes4(keccak256("onERC721Received(address,address,uint256,bytes)")); } }
Returns auction info for an NFT on auction. _tokenId - ID of NFT on auction.
function getAuction(uint256 _tokenId) public view returns ( address seller, uint256 startingPrice, uint256 endingPrice, uint256 duration, uint256 startedAt, address token ) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return ( auction.seller, uint256(auction.startingPriceInToken), uint256(auction.endingPriceInToken), uint256(auction.duration), uint256(auction.startedAt), auction.token ); }
2,571,181
./full_match/1/0xA2A7c7DC114765B21E7D167d9665D3992152E6d9/sources/src/abstracts/BaseVault.sol
@inheritdoc IERC4626
function convertToAssets(uint256 shares) public view virtual override returns (uint256 assets) { return _convertToAssets(shares, Math.Rounding.Down); }
16,499,476
pragma solidity ^0.4.24; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "./interfaces/IOwnable.sol"; import "./interfaces/ISTFactory.sol"; import "./interfaces/IERC20.sol"; import "./interfaces/ISecurityTokenRegistry.sol"; import "./storage/EternalStorage.sol"; import "./libraries/Util.sol"; import "./libraries/Encoder.sol"; import "./libraries/VersionUtils.sol"; /** * @title Registry contract for issuers to register their tickers and security tokens */ contract SecurityTokenRegistry is ISecurityTokenRegistry, EternalStorage { /** * @notice state variables address public polyToken; uint256 public stLaunchFee; uint256 public tickerRegFee; uint256 public expiryLimit; uint256 public latestProtocolVersion; bool public paused; address public owner; address public polymathRegistry; address[] public activeUsers; mapping(address => bool) public seenUsers; mapping(address => bytes32[]) userToTickers; mapping(string => address) tickerToSecurityToken; mapping(string => uint) tickerIndex; mapping(string => TickerDetails) registeredTickers; mapping(address => SecurityTokenData) securityTokens; mapping(bytes32 => address) protocolVersionST; mapping(uint256 => ProtocolVersion) versionData; struct ProtocolVersion { uint8 major; uint8 minor; uint8 patch; } struct TickerDetails { address owner; uint256 registrationDate; uint256 expiryDate; string tokenName; bool status; } struct SecurityTokenData { string ticker; string tokenDetails; uint256 deployedAt; } */ using SafeMath for uint256; bytes32 constant INITIALIZE = 0x9ef7257c3339b099aacf96e55122ee78fb65a36bd2a6c19249882be9c98633bf; bytes32 constant POLYTOKEN = 0xacf8fbd51bb4b83ba426cdb12f63be74db97c412515797993d2a385542e311d7; bytes32 constant STLAUNCHFEE = 0xd677304bb45536bb7fdfa6b9e47a3c58fe413f9e8f01474b0a4b9c6e0275baf2; bytes32 constant TICKERREGFEE = 0x2fcc69711628630fb5a42566c68bd1092bc4aa26826736293969fddcd11cb2d2; bytes32 constant EXPIRYLIMIT = 0x604268e9a73dfd777dcecb8a614493dd65c638bad2f5e7d709d378bd2fb0baee; bytes32 constant PAUSED = 0xee35723ac350a69d2a92d3703f17439cbaadf2f093a21ba5bf5f1a53eb2a14d9; bytes32 constant OWNER = 0x02016836a56b71f0d02689e69e326f4f4c1b9057164ef592671cf0d37c8040c0; bytes32 constant POLYMATHREGISTRY = 0x90eeab7c36075577c7cc5ff366e389fefa8a18289b949bab3529ab4471139d4d; // Emit when network becomes paused event Pause(uint256 _timestammp); // Emit when network becomes unpaused event Unpause(uint256 _timestamp); // Emit when the ticker is removed from the registry event TickerRemoved(string _ticker, uint256 _removedAt, address _removedBy); // Emit when the token ticker expiry is changed event ChangeExpiryLimit(uint256 _oldExpiry, uint256 _newExpiry); // Emit when changeSecurityLaunchFee is called event ChangeSecurityLaunchFee(uint256 _oldFee, uint256 _newFee); // Emit when changeTickerRegistrationFee is called event ChangeTickerRegistrationFee(uint256 _oldFee, uint256 _newFee); // Emit when ownership gets transferred event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); // Emit when ownership of the ticker gets changed event ChangeTickerOwnership(string _ticker, address indexed _oldOwner, address indexed _newOwner); // Emit at the time of launching a new security token event NewSecurityToken( string _ticker, string _name, address indexed _securityTokenAddress, address indexed _owner, uint256 _addedAt, address _registrant, bool _fromAdmin, uint256 _registrationFee ); // Emit after ticker registration event RegisterTicker( address indexed _owner, string _ticker, string _name, uint256 indexed _registrationDate, uint256 indexed _expiryDate, bool _fromAdmin, uint256 _registrationFee ); ///////////////////////////// // Modifiers ///////////////////////////// /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner(),"sender must be owner"); _; } /** * @notice Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPausedOrOwner() { if (msg.sender == owner()) _; else { require(!isPaused(), "Already paused"); _; } } /** * @notice Modifier to make a function callable only when the contract is not paused and ignore is msg.sender is owner. */ modifier whenNotPaused() { require(!isPaused(), "Already paused"); _; } /** * @notice Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(isPaused(), "Should not be paused"); _; } ///////////////////////////// // Initialization ///////////////////////////// /** * @notice Initializes instance of STR * @param _polymathRegistry is the address of the Polymath Registry * @param _STFactory is the address of the Proxy contract for Security Tokens * @param _stLaunchFee is the fee in POLY required to launch a token * @param _tickerRegFee is the fee in POLY required to register a ticker * @param _polyToken is the address of the POLY ERC20 token * @param _owner is the owner of the STR */ function initialize( address _polymathRegistry, address _STFactory, uint256 _stLaunchFee, uint256 _tickerRegFee, address _polyToken, address _owner ) external payable { require(!getBool(INITIALIZE),"already initialized"); require( _STFactory != address(0) && _polyToken != address(0) && _owner != address(0) && _polymathRegistry != address(0), "Invalid address" ); require(_stLaunchFee != 0 && _tickerRegFee != 0, "Fees should not be 0"); set(POLYTOKEN, _polyToken); set(STLAUNCHFEE, _stLaunchFee); set(TICKERREGFEE, _tickerRegFee); set(EXPIRYLIMIT, uint256(60 * 1 days)); set(PAUSED, false); set(OWNER, _owner); set(POLYMATHREGISTRY, _polymathRegistry); _setProtocolVersion(_STFactory, uint8(2), uint8(0), uint8(0)); set(INITIALIZE, true); } ///////////////////////////// // Token Ticker Management ///////////////////////////// /** * @notice Registers the token ticker to the selected owner * @notice Once the token ticker is registered to its owner then no other issuer can claim * @notice its ownership. If the ticker expires and its issuer hasn't used it, then someone else can take it. * @param _owner is address of the owner of the token * @param _ticker is unique token ticker * @param _tokenName is the name of the token */ function registerTicker(address _owner, string _ticker, string _tokenName) external whenNotPausedOrOwner { require(_owner != address(0), "Owner should not be 0x"); require(bytes(_ticker).length > 0 && bytes(_ticker).length <= 10, "Ticker length range (0,10]"); // Attempt to charge the reg fee if it is > 0 POLY uint256 tickerFee = getTickerRegistrationFee(); if (tickerFee > 0) require(IERC20(getAddress(POLYTOKEN)).transferFrom(msg.sender, address(this), tickerFee), "Insufficent allowance"); string memory ticker = Util.upper(_ticker); require(_tickerAvailable(ticker), "Ticker is reserved"); // Check whether ticker was previously registered (and expired) address previousOwner = _tickerOwner(ticker); if (previousOwner != address(0)) { _deleteTickerOwnership(previousOwner, ticker); } /*solium-disable-next-line security/no-block-members*/ _addTicker(_owner, ticker, _tokenName, now, now.add(getExpiryLimit()), false, false, tickerFee); } /** * @notice Internal - Sets the details of the ticker */ function _addTicker( address _owner, string _ticker, string _tokenName, uint256 _registrationDate, uint256 _expiryDate, bool _status, bool _fromAdmin, uint256 _fee ) internal { _setTickerOwnership(_owner, _ticker); _storeTickerDetails(_ticker, _owner, _registrationDate, _expiryDate, _tokenName, _status); emit RegisterTicker(_owner, _ticker, _tokenName, _registrationDate, _expiryDate, _fromAdmin, _fee); } /** * @notice Modifies the ticker details. Only Polymath has the ability to do so. * @notice Only allowed to modify the tickers which are not yet deployed. * @param _owner is the owner of the token * @param _ticker is the token ticker * @param _tokenName is the name of the token * @param _registrationDate is the date at which ticker is registered * @param _expiryDate is the expiry date for the ticker * @param _status is the token deployment status */ function modifyTicker( address _owner, string _ticker, string _tokenName, uint256 _registrationDate, uint256 _expiryDate, bool _status ) external onlyOwner { require(bytes(_ticker).length > 0 && bytes(_ticker).length <= 10, "Ticker length range (0,10]"); require(_expiryDate != 0 && _registrationDate != 0, "Dates should not be 0"); require(_registrationDate <= _expiryDate, "Registration date should < expiry date"); require(_owner != address(0), "Invalid address"); string memory ticker = Util.upper(_ticker); _modifyTicker(_owner, ticker, _tokenName, _registrationDate, _expiryDate, _status); } /** * @notice Internal -- Modifies the ticker details. */ function _modifyTicker( address _owner, string _ticker, string _tokenName, uint256 _registrationDate, uint256 _expiryDate, bool _status ) internal { address currentOwner = _tickerOwner(_ticker); if (currentOwner != address(0)) { _deleteTickerOwnership(currentOwner, _ticker); } if (_tickerStatus(_ticker) && !_status) { set(Encoder.getKey("tickerToSecurityToken", _ticker), address(0)); } // If status is true, there must be a security token linked to the ticker already if (_status) { require(getAddress(Encoder.getKey("tickerToSecurityToken", _ticker)) != address(0), "Token not registered"); } _addTicker(_owner, _ticker, _tokenName, _registrationDate, _expiryDate, _status, true, uint256(0)); } function _tickerOwner(string _ticker) internal view returns(address) { return getAddress(Encoder.getKey("registeredTickers_owner", _ticker)); } /** * @notice Removes the ticker details, associated ownership & security token mapping * @param _ticker is the token ticker */ function removeTicker(string _ticker) external onlyOwner { string memory ticker = Util.upper(_ticker); address owner = _tickerOwner(ticker); require(owner != address(0), "Ticker doesn't exist"); _deleteTickerOwnership(owner, ticker); set(Encoder.getKey("tickerToSecurityToken", ticker), address(0)); _storeTickerDetails(ticker, address(0), 0, 0, "", false); /*solium-disable-next-line security/no-block-members*/ emit TickerRemoved(ticker, now, msg.sender); } /** * @notice Internal - Checks if the entered ticker is registered and has not expired * @param _ticker is the token ticker * @return bool */ function _tickerAvailable(string _ticker) internal view returns(bool) { if (_tickerOwner(_ticker) != address(0)) { /*solium-disable-next-line security/no-block-members*/ if ((now > getUint(Encoder.getKey("registeredTickers_expiryDate", _ticker))) && !_tickerStatus(_ticker)) { return true; } else return false; } return true; } function _tickerStatus(string _ticker) internal view returns(bool) { return getBool(Encoder.getKey("registeredTickers_status", _ticker)); } /** * @notice Internal - Sets the ticker owner * @param _owner is the address of the owner of the ticker * @param _ticker is the ticker symbol */ function _setTickerOwnership(address _owner, string _ticker) internal { bytes32 _ownerKey = Encoder.getKey("userToTickers", _owner); uint256 length = uint256(getArrayBytes32(_ownerKey).length); pushArray(_ownerKey, Util.stringToBytes32(_ticker)); set(Encoder.getKey("tickerIndex", _ticker), length); bytes32 seenKey = Encoder.getKey("seenUsers", _owner); if (!getBool(seenKey)) { pushArray(Encoder.getKey("activeUsers"), _owner); set(seenKey, true); } } /** * @notice Internal - Stores the ticker details */ function _storeTickerDetails( string _ticker, address _owner, uint256 _registrationDate, uint256 _expiryDate, string _tokenName, bool _status ) internal { bytes32 key = Encoder.getKey("registeredTickers_owner", _ticker); if (getAddress(key) != _owner) set(key, _owner); key = Encoder.getKey("registeredTickers_registrationDate", _ticker); if (getUint(key) != _registrationDate) set(key, _registrationDate); key = Encoder.getKey("registeredTickers_expiryDate", _ticker); if (getUint(key) != _expiryDate) set(key, _expiryDate); key = Encoder.getKey("registeredTickers_tokenName", _ticker); if (Encoder.getKey(getString(key)) != Encoder.getKey(_tokenName)) set(key, _tokenName); key = Encoder.getKey("registeredTickers_status", _ticker); if (getBool(key) != _status) set(key, _status); } /** * @notice Transfers the ownership of the ticker * @param _newOwner is the address of the new owner of the ticker * @param _ticker is the ticker symbol */ function transferTickerOwnership(address _newOwner, string _ticker) external whenNotPausedOrOwner { string memory ticker = Util.upper(_ticker); require(_newOwner != address(0), "Invalid address"); bytes32 ownerKey = Encoder.getKey("registeredTickers_owner", ticker); require(getAddress(ownerKey) == msg.sender, "Not authorised"); if (_tickerStatus(ticker)) require(IOwnable(getAddress(Encoder.getKey("tickerToSecurityToken", ticker))).owner() == _newOwner, "New owner does not match token owner"); _deleteTickerOwnership(msg.sender, ticker); _setTickerOwnership(_newOwner, ticker); set(ownerKey, _newOwner); emit ChangeTickerOwnership(ticker, msg.sender, _newOwner); } /** * @notice Internal - Removes the owner of a ticker */ function _deleteTickerOwnership(address _owner, string _ticker) internal { uint256 index = uint256(getUint(Encoder.getKey("tickerIndex", _ticker))); bytes32 ownerKey = Encoder.getKey("userToTickers", _owner); bytes32[] memory tickers = getArrayBytes32(ownerKey); assert(index < tickers.length); assert(_tickerOwner(_ticker) == _owner); deleteArrayBytes32(ownerKey, index); if (getArrayBytes32(ownerKey).length > index) { bytes32 switchedTicker = getArrayBytes32(ownerKey)[index]; set(Encoder.getKey("tickerIndex", Util.bytes32ToString(switchedTicker)), index); } } /** * @notice Changes the expiry time for the token ticker. Only available to Polymath. * @param _newExpiry is the new expiry for newly generated tickers */ function changeExpiryLimit(uint256 _newExpiry) external onlyOwner { require(_newExpiry >= 1 days, "Expiry should >= 1 day"); emit ChangeExpiryLimit(getUint(EXPIRYLIMIT), _newExpiry); set(EXPIRYLIMIT, _newExpiry); } /** * @notice Returns the list of tickers owned by the selected address * @param _owner is the address which owns the list of tickers */ function getTickersByOwner(address _owner) external view returns(bytes32[]) { uint counter = 0; // accessing the data structure userTotickers[_owner].length bytes32[] memory tickers = getArrayBytes32(Encoder.getKey("userToTickers", _owner)); for (uint i = 0; i < tickers.length; i++) { string memory ticker = Util.bytes32ToString(tickers[i]); /*solium-disable-next-line security/no-block-members*/ if (getUint(Encoder.getKey("registeredTickers_expiryDate", ticker)) >= now || _tickerStatus(ticker)) { counter ++; } } bytes32[] memory tempList = new bytes32[](counter); counter = 0; for (i = 0; i < tickers.length; i++) { ticker = Util.bytes32ToString(tickers[i]); /*solium-disable-next-line security/no-block-members*/ if (getUint(Encoder.getKey("registeredTickers_expiryDate", ticker)) >= now || _tickerStatus(ticker)) { tempList[counter] = tickers[i]; counter ++; } } return tempList; } /** * @notice Returns the list of tokens owned by the selected address * @param _owner is the address which owns the list of tickers * @dev Intention is that this is called off-chain so block gas limit is not relevant */ function getTokensByOwner(address _owner) external view returns(address[]) { // Loop over all active users, then all associated tickers of those users // This ensures we find tokens, even if their owner has been modified address[] memory activeUsers = getArrayAddress(Encoder.getKey("activeUsers")); bytes32[] memory tickers; address token; uint256 count = 0; uint256 i = 0; uint256 j = 0; for (i = 0; i < activeUsers.length; i++) { tickers = getArrayBytes32(Encoder.getKey("userToTickers", activeUsers[i])); for (j = 0; j < tickers.length; j++) { token = getAddress(Encoder.getKey("tickerToSecurityToken", Util.bytes32ToString(tickers[j]))); if (token != address(0)) { if (IOwnable(token).owner() == _owner) { count = count + 1; } } } } uint256 index = 0; address[] memory result = new address[](count); for (i = 0; i < activeUsers.length; i++) { tickers = getArrayBytes32(Encoder.getKey("userToTickers", activeUsers[i])); for (j = 0; j < tickers.length; j++) { token = getAddress(Encoder.getKey("tickerToSecurityToken", Util.bytes32ToString(tickers[j]))); if (token != address(0)) { if (IOwnable(token).owner() == _owner) { result[index] = token; index = index + 1; } } } } return result; } /** * @notice Returns the owner and timestamp for a given ticker * @param _ticker is the ticker symbol * @return address * @return uint256 * @return uint256 * @return string * @return bool */ function getTickerDetails(string _ticker) external view returns (address, uint256, uint256, string, bool) { string memory ticker = Util.upper(_ticker); bool tickerStatus = _tickerStatus(ticker); uint256 expiryDate = getUint(Encoder.getKey("registeredTickers_expiryDate", ticker)); /*solium-disable-next-line security/no-block-members*/ if ((tickerStatus == true) || (expiryDate > now)) { return ( _tickerOwner(ticker), getUint(Encoder.getKey("registeredTickers_registrationDate", ticker)), expiryDate, getString(Encoder.getKey("registeredTickers_tokenName", ticker)), tickerStatus ); } else return (address(0), uint256(0), uint256(0), "", false); } ///////////////////////////// // Security Token Management ///////////////////////////// /** * @notice Deploys an instance of a new Security Token and records it to the registry * @param _name is the name of the token * @param _ticker is the ticker symbol of the security token * @param _tokenDetails is the off-chain details of the token * @param _divisible is whether or not the token is divisible */ function generateSecurityToken(string _name, string _ticker, string _tokenDetails, bool _divisible) external whenNotPausedOrOwner { require(bytes(_name).length > 0 && bytes(_ticker).length > 0, "Ticker length > 0"); string memory ticker = Util.upper(_ticker); bytes32 statusKey = Encoder.getKey("registeredTickers_status", ticker); require(!getBool(statusKey), "Already deployed"); set(statusKey, true); require(_tickerOwner(ticker) == msg.sender, "Not authorised"); /*solium-disable-next-line security/no-block-members*/ require(getUint(Encoder.getKey("registeredTickers_expiryDate", ticker)) >= now, "Ticker gets expired"); uint256 launchFee = getSecurityTokenLaunchFee(); if (launchFee > 0) require(IERC20(getAddress(POLYTOKEN)).transferFrom(msg.sender, address(this), launchFee), "Insufficient allowance"); address newSecurityTokenAddress = ISTFactory(getSTFactoryAddress()).deployToken( _name, ticker, 18, _tokenDetails, msg.sender, _divisible, getAddress(POLYMATHREGISTRY) ); /*solium-disable-next-line security/no-block-members*/ _storeSecurityTokenData(newSecurityTokenAddress, ticker, _tokenDetails, now); set(Encoder.getKey("tickerToSecurityToken", ticker), newSecurityTokenAddress); /*solium-disable-next-line security/no-block-members*/ emit NewSecurityToken(ticker, _name, newSecurityTokenAddress, msg.sender, now, msg.sender, false, launchFee); } /** * @notice Adds a new custom Security Token and saves it to the registry. (Token should follow the ISecurityToken interface) * @param _name is the name of the token * @param _ticker is the ticker symbol of the security token * @param _owner is the owner of the token * @param _securityToken is the address of the securityToken * @param _tokenDetails is the off-chain details of the token * @param _deployedAt is the timestamp at which the security token is deployed */ function modifySecurityToken( string _name, string _ticker, address _owner, address _securityToken, string _tokenDetails, uint256 _deployedAt ) external onlyOwner { require(bytes(_name).length > 0 && bytes(_ticker).length > 0, "String length > 0"); require(bytes(_ticker).length <= 10, "Ticker length range (0,10]"); require(_deployedAt != 0 && _owner != address(0), "0 value params not allowed"); string memory ticker = Util.upper(_ticker); require(_securityToken != address(0), "ST address is 0x"); uint256 registrationTime = getUint(Encoder.getKey("registeredTickers_registrationDate", ticker)); uint256 expiryTime = getUint(Encoder.getKey("registeredTickers_expiryDate", ticker)); if (registrationTime == 0) { /*solium-disable-next-line security/no-block-members*/ registrationTime = now; expiryTime = registrationTime.add(getExpiryLimit()); } set(Encoder.getKey("tickerToSecurityToken", ticker), _securityToken); _modifyTicker(_owner, ticker, _name, registrationTime, expiryTime, true); _storeSecurityTokenData(_securityToken, ticker, _tokenDetails, _deployedAt); emit NewSecurityToken(ticker, _name, _securityToken, _owner, _deployedAt, msg.sender, true, getSecurityTokenLaunchFee()); } /** * @notice Internal - Stores the security token details */ function _storeSecurityTokenData(address _securityToken, string _ticker, string _tokenDetails, uint256 _deployedAt) internal { set(Encoder.getKey("securityTokens_ticker", _securityToken), _ticker); set(Encoder.getKey("securityTokens_tokenDetails", _securityToken), _tokenDetails); set(Encoder.getKey("securityTokens_deployedAt", _securityToken), _deployedAt); } /** * @notice Checks that Security Token is registered * @param _securityToken is the address of the security token * @return bool */ function isSecurityToken(address _securityToken) external view returns (bool) { return (keccak256(bytes(getString(Encoder.getKey("securityTokens_ticker", _securityToken)))) != keccak256("")); } /** * @notice Returns the security token address by ticker symbol * @param _ticker is the ticker of the security token * @return address */ function getSecurityTokenAddress(string _ticker) external view returns (address) { string memory ticker = Util.upper(_ticker); return getAddress(Encoder.getKey("tickerToSecurityToken", ticker)); } /** * @notice Returns the security token data by address * @param _securityToken is the address of the security token. * @return string is the ticker of the security Token. * @return address is the issuer of the security Token. * @return string is the details of the security token. * @return uint256 is the timestamp at which security Token was deployed. */ function getSecurityTokenData(address _securityToken) external view returns (string, address, string, uint256) { return ( getString(Encoder.getKey("securityTokens_ticker", _securityToken)), IOwnable(_securityToken).owner(), getString(Encoder.getKey("securityTokens_tokenDetails", _securityToken)), getUint(Encoder.getKey("securityTokens_deployedAt", _securityToken)) ); } ///////////////////////////// // Ownership, lifecycle & Utility ///////////////////////////// /** * @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) external onlyOwner { require(_newOwner != address(0), "Invalid address"); emit OwnershipTransferred(getAddress(OWNER), _newOwner); set(OWNER, _newOwner); } /** * @notice Called by the owner to pause, triggers stopped state */ function pause() external whenNotPaused onlyOwner { set(PAUSED, true); /*solium-disable-next-line security/no-block-members*/ emit Pause(now); } /** * @notice Called by the owner to unpause, returns to normal state */ function unpause() external whenPaused onlyOwner { set(PAUSED, false); /*solium-disable-next-line security/no-block-members*/ emit Unpause(now); } /** * @notice Sets the ticker registration fee in POLY tokens. Only Polymath. * @param _tickerRegFee is the registration fee in POLY tokens (base 18 decimals) */ function changeTickerRegistrationFee(uint256 _tickerRegFee) external onlyOwner { uint256 fee = getUint(TICKERREGFEE); require(fee != _tickerRegFee, "Fee not changed"); emit ChangeTickerRegistrationFee(fee, _tickerRegFee); set(TICKERREGFEE, _tickerRegFee); } /** * @notice Sets the ticker registration fee in POLY tokens. Only Polymath. * @param _stLaunchFee is the registration fee in POLY tokens (base 18 decimals) */ function changeSecurityLaunchFee(uint256 _stLaunchFee) external onlyOwner { uint256 fee = getUint(STLAUNCHFEE); require(fee != _stLaunchFee, "Fee not changed"); emit ChangeSecurityLaunchFee(fee, _stLaunchFee); set(STLAUNCHFEE, _stLaunchFee); } /** * @notice Reclaims all ERC20Basic compatible tokens * @param _tokenContract is the address of the token contract */ function reclaimERC20(address _tokenContract) external onlyOwner { require(_tokenContract != address(0), "Invalid address"); IERC20 token = IERC20(_tokenContract); uint256 balance = token.balanceOf(address(this)); require(token.transfer(owner(), balance), "Transfer failed"); } /** * @notice Changes the protocol version and the SecurityToken contract * @notice Used only by Polymath to upgrade the SecurityToken contract and add more functionalities to future versions * @notice Changing versions does not affect existing tokens. * @param _STFactoryAddress is the address of the proxy. * @param _major Major version of the proxy. * @param _minor Minor version of the proxy. * @param _patch Patch version of the proxy */ function setProtocolVersion(address _STFactoryAddress, uint8 _major, uint8 _minor, uint8 _patch) external onlyOwner { require(_STFactoryAddress != address(0), "0x address is not allowed"); _setProtocolVersion(_STFactoryAddress, _major, _minor, _patch); } /** * @notice Internal - Changes the protocol version and the SecurityToken contract */ function _setProtocolVersion(address _STFactoryAddress, uint8 _major, uint8 _minor, uint8 _patch) internal { uint8[] memory _version = new uint8[](3); _version[0] = _major; _version[1] = _minor; _version[2] = _patch; uint24 _packedVersion = VersionUtils.pack(_major, _minor, _patch); require(VersionUtils.isValidVersion(getProtocolVersion(), _version),"In-valid version"); set(Encoder.getKey("latestVersion"), uint256(_packedVersion)); set(Encoder.getKey("protocolVersionST", getUint(Encoder.getKey("latestVersion"))), _STFactoryAddress); } /** * @notice Returns the current STFactory Address */ function getSTFactoryAddress() public view returns(address) { return getAddress(Encoder.getKey("protocolVersionST", getUint(Encoder.getKey("latestVersion")))); } /** * @notice Gets Protocol version */ function getProtocolVersion() public view returns(uint8[]) { return VersionUtils.unpack(uint24(getUint(Encoder.getKey("latestVersion")))); } /** * @notice Changes the PolyToken address. Only Polymath. * @param _newAddress is the address of the polytoken. */ function updatePolyTokenAddress(address _newAddress) external onlyOwner { require(_newAddress != address(0), "Invalid address"); set(POLYTOKEN, _newAddress); } /** * @notice Gets the security token launch fee * @return Fee amount */ function getSecurityTokenLaunchFee() public view returns(uint256) { return getUint(STLAUNCHFEE); } /** * @notice Gets the ticker registration fee * @return Fee amount */ function getTickerRegistrationFee() public view returns(uint256) { return getUint(TICKERREGFEE); } /** * @notice Gets the expiry limit * @return Expiry limit */ function getExpiryLimit() public view returns(uint256) { return getUint(EXPIRYLIMIT); } /** * @notice Check whether the registry is paused or not * @return bool */ function isPaused() public view returns(bool) { return getBool(PAUSED); } /** * @notice Gets the owner of the contract * @return address owner */ function owner() public view returns(address) { return getAddress(OWNER); } }
Called by the owner to pause, triggers stopped state/
function pause() external whenNotPaused onlyOwner { set(PAUSED, true); emit Pause(now);
12,831,577
./partial_match/1/0x5bCDC405Cb237996d29fe3Ec779209e65fF2d39C/sources/OperatorFilterRegistry.sol
Returns true if operator is filtered by a given address or its subscription./
function isOperatorFiltered(address registrant, address operator) external view returns (bool) { address registration = _registrations[registrant]; if (registration != registrant) { return _filteredOperators[registration].contains(operator); } return _filteredOperators[registrant].contains(operator); }
2,831,676
./full_match/1/0x4f272815fb641082b0291025016aebEBBC6Cf0D7/sources/contracts/NarfexFiat.sol
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 {BEP20-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] - subtractedValue ); return true; }
4,846,417
// SPDX-License-Identifier: MIT // 2nd part of the transition applier due to contract size restrictions pragma solidity 0.8.6; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; /* Internal Imports */ import {DataTypes as dt} from "./libraries/DataTypes.sol"; import {Transitions as tn} from "./libraries/Transitions.sol"; import "./libraries/ErrMsg.sol"; contract TransitionApplier2 { uint256 public constant STAKING_SCALE_FACTOR = 1e12; /********************** * External Functions * **********************/ /** * @notice Apply an AggregateOrdersTransition. * * @param _transition The disputed transition. * @param _strategyInfo The involved strategy from the previous transition. * @return new strategy info after applying the disputed transition */ function applyAggregateOrdersTransition( dt.AggregateOrdersTransition memory _transition, dt.StrategyInfo memory _strategyInfo ) public pure returns (dt.StrategyInfo memory) { uint256 npend = _strategyInfo.pending.length; require(npend > 0, ErrMsg.REQ_NO_PEND); dt.PendingStrategyInfo memory psi = _strategyInfo.pending[npend - 1]; require(_transition.buyAmount == psi.buyAmount, ErrMsg.REQ_BAD_AMOUNT); require(_transition.sellShares == psi.sellShares, ErrMsg.REQ_BAD_SHARES); uint256 minSharesFromBuy = (_transition.buyAmount * 1e18) / psi.maxSharePriceForBuy; uint256 minAmountFromSell = (_transition.sellShares * psi.minSharePriceForSell) / 1e18; require(_transition.minSharesFromBuy == minSharesFromBuy, ErrMsg.REQ_BAD_SHARES); require(_transition.minAmountFromSell == minAmountFromSell, ErrMsg.REQ_BAD_AMOUNT); _strategyInfo.nextAggregateId++; return _strategyInfo; } /** * @notice Apply a ExecutionResultTransition. * * @param _transition The disputed transition. * @param _strategyInfo The involved strategy from the previous transition. * @param _globalInfo The involved global info from the previous transition. * @return new strategy info after applying the disputed transition */ function applyExecutionResultTransition( dt.ExecutionResultTransition memory _transition, dt.StrategyInfo memory _strategyInfo, dt.GlobalInfo memory _globalInfo ) public pure returns (dt.StrategyInfo memory, dt.GlobalInfo memory) { uint256 idx; bool found = false; for (uint256 i = 0; i < _strategyInfo.pending.length; i++) { if (_strategyInfo.pending[i].aggregateId == _transition.aggregateId) { idx = i; found = true; break; } } require(found, ErrMsg.REQ_BAD_AGGR); if (_transition.success) { _strategyInfo.pending[idx].sharesFromBuy = _transition.sharesFromBuy; _strategyInfo.pending[idx].amountFromSell = _transition.amountFromSell; } _strategyInfo.pending[idx].executionSucceed = _transition.success; _strategyInfo.pending[idx].unsettledBuyAmount = _strategyInfo.pending[idx].buyAmount; _strategyInfo.pending[idx].unsettledSellShares = _strategyInfo.pending[idx].sellShares; _strategyInfo.lastExecAggregateId = _transition.aggregateId; return (_strategyInfo, _globalInfo); } /** * @notice Apply a WithdrawProtocolFeeTransition. * * @param _transition The disputed transition. * @param _globalInfo The involved global info from the previous transition. * @return new global info after applying the disputed transition */ function applyWithdrawProtocolFeeTransition( dt.WithdrawProtocolFeeTransition memory _transition, dt.GlobalInfo memory _globalInfo ) public pure returns (dt.GlobalInfo memory) { _globalInfo.protoFees[_transition.assetId] -= _transition.amount; return _globalInfo; } /** * @notice Apply a TransferOperatorFeeTransition. * * @param _transition The disputed transition. * @param _accountInfo The involved account from the previous transition. * @param _globalInfo The involved global info from the previous transition. * @return new account info and global info after applying the disputed transition */ function applyTransferOperatorFeeTransition( dt.TransferOperatorFeeTransition memory _transition, dt.AccountInfo memory _accountInfo, dt.GlobalInfo memory _globalInfo ) external pure returns (dt.AccountInfo memory, dt.GlobalInfo memory) { require(_accountInfo.accountId == _transition.accountId, ErrMsg.REQ_BAD_ACCT); require(_accountInfo.account != address(0), ErrMsg.REQ_BAD_ACCT); uint32 assetFeeLen = uint32(_globalInfo.opFees.assets.length); if (assetFeeLen > 1) { tn.adjustAccountIdleAssetEntries(_accountInfo, assetFeeLen - 1); for (uint256 i = 1; i < assetFeeLen; i++) { _accountInfo.idleAssets[i] += _globalInfo.opFees.assets[i]; _globalInfo.opFees.assets[i] = 0; } } uint32 shareFeeLen = uint32(_globalInfo.opFees.shares.length); if (shareFeeLen > 1) { tn.adjustAccountShareEntries(_accountInfo, shareFeeLen - 1); for (uint256 i = 1; i < shareFeeLen; i++) { _accountInfo.shares[i] += _globalInfo.opFees.shares[i]; _globalInfo.opFees.shares[i] = 0; } } return (_accountInfo, _globalInfo); } /** * @notice Apply a UpdateEpochTransition. * * @param _transition The disputed transition. * @param _globalInfo The involved global info from the previous transition. * @return new global info after applying the disputed transition */ function applyUpdateEpochTransition(dt.UpdateEpochTransition memory _transition, dt.GlobalInfo memory _globalInfo) public pure returns (dt.GlobalInfo memory) { if (_transition.epoch >= _globalInfo.currEpoch) { _globalInfo.currEpoch = _transition.epoch; } return _globalInfo; } /** * @notice Apply a StakeTransition. * * @param _transition The disputed transition. * @param _accountInfo The involved account from the previous transition. * @param _stakingPoolInfo The involved staking pool from the previous transition. * @param _globalInfo The involved global info from the previous transition. * @return new account, staking pool and global info after applying the disputed transition */ function applyStakeTransition( dt.StakeTransition memory _transition, dt.AccountInfo memory _accountInfo, dt.StakingPoolInfo memory _stakingPoolInfo, dt.GlobalInfo memory _globalInfo ) external pure returns ( dt.AccountInfo memory, dt.StakingPoolInfo memory, dt.GlobalInfo memory ) { require( ECDSA.recover( ECDSA.toEthSignedMessageHash( keccak256( abi.encodePacked( _transition.transitionType, _transition.poolId, _transition.shares, _transition.fee, _transition.timestamp ) ) ), _transition.v, _transition.r, _transition.s ) == _accountInfo.account, ErrMsg.REQ_BAD_SIG ); require(_accountInfo.accountId == _transition.accountId, ErrMsg.REQ_BAD_ACCT); require(_accountInfo.timestamp < _transition.timestamp, ErrMsg.REQ_BAD_TS); require(_stakingPoolInfo.strategyId > 0, ErrMsg.REQ_BAD_SP); _accountInfo.timestamp = _transition.timestamp; uint32 poolId = _transition.poolId; uint256 feeInShares; (bool isCelr, uint256 fee) = tn.getFeeInfo(_transition.fee); if (isCelr) { _accountInfo.idleAssets[1] -= fee; tn.updateOpFee(_globalInfo, true, 1, fee); } else { feeInShares = fee; tn.updateOpFee(_globalInfo, false, _stakingPoolInfo.strategyId, fee); } uint256 addedShares = _transition.shares - feeInShares; _updatePoolStates(_stakingPoolInfo, _globalInfo); _adjustAccountStakedShareAndStakeEntries(_accountInfo, poolId); _adjustAccountRewardDebtEntries(_accountInfo, poolId, uint32(_stakingPoolInfo.rewardPerEpoch.length - 1)); if (addedShares > 0) { uint256 addedStake = _getAdjustedStake( _accountInfo.stakedShares[poolId] + addedShares, _stakingPoolInfo.stakeAdjustmentFactor ) - _accountInfo.stakes[poolId]; _accountInfo.stakedShares[poolId] += addedShares; _accountInfo.stakes[poolId] += addedStake; _stakingPoolInfo.totalShares += addedShares; _stakingPoolInfo.totalStakes += addedStake; for (uint32 rewardTokenId = 0; rewardTokenId < _stakingPoolInfo.rewardPerEpoch.length; rewardTokenId++) { _accountInfo.rewardDebts[poolId][rewardTokenId] += (addedStake * _stakingPoolInfo.accumulatedRewardPerUnit[rewardTokenId]) / STAKING_SCALE_FACTOR; } } tn.adjustAccountShareEntries(_accountInfo, _stakingPoolInfo.strategyId); _accountInfo.shares[_stakingPoolInfo.strategyId] -= _transition.shares; return (_accountInfo, _stakingPoolInfo, _globalInfo); } /** * @notice Apply an UnstakeTransition. * * @param _transition The disputed transition. * @param _accountInfo The involved account from the previous transition. * @param _stakingPoolInfo The involved staking pool from the previous transition. * @param _globalInfo The involved global info from the previous transition. * @return new account, staking pool and global info after applying the disputed transition */ function applyUnstakeTransition( dt.UnstakeTransition memory _transition, dt.AccountInfo memory _accountInfo, dt.StakingPoolInfo memory _stakingPoolInfo, dt.GlobalInfo memory _globalInfo ) external pure returns ( dt.AccountInfo memory, dt.StakingPoolInfo memory, dt.GlobalInfo memory ) { require( ECDSA.recover( ECDSA.toEthSignedMessageHash( keccak256( abi.encodePacked( _transition.transitionType, _transition.poolId, _transition.shares, _transition.fee, _transition.timestamp ) ) ), _transition.v, _transition.r, _transition.s ) == _accountInfo.account, ErrMsg.REQ_BAD_SIG ); require(_accountInfo.accountId == _transition.accountId, ErrMsg.REQ_BAD_ACCT); require(_accountInfo.timestamp < _transition.timestamp, ErrMsg.REQ_BAD_TS); require(_stakingPoolInfo.strategyId > 0, ErrMsg.REQ_BAD_SP); _accountInfo.timestamp = _transition.timestamp; uint32 poolId = _transition.poolId; uint256 feeInShares; (bool isCelr, uint256 fee) = tn.getFeeInfo(_transition.fee); if (isCelr) { _accountInfo.idleAssets[1] -= fee; tn.updateOpFee(_globalInfo, true, 1, fee); } else { feeInShares = fee; tn.updateOpFee(_globalInfo, false, _stakingPoolInfo.strategyId, fee); } uint256 removedShares = _transition.shares; _updatePoolStates(_stakingPoolInfo, _globalInfo); require(_accountInfo.stakes.length > poolId, ErrMsg.REQ_BAD_AMOUNT); _adjustAccountRewardDebtEntries(_accountInfo, poolId, uint32(_stakingPoolInfo.rewardPerEpoch.length - 1)); uint256 originalStake = _accountInfo.stakes[poolId]; if (removedShares > 0) { uint256 removedStake = _accountInfo.stakes[poolId] - _getAdjustedStake( _accountInfo.stakedShares[poolId] - removedShares, _stakingPoolInfo.stakeAdjustmentFactor ); _accountInfo.stakedShares[poolId] -= removedShares; _accountInfo.stakes[poolId] -= removedStake; _stakingPoolInfo.totalShares -= removedShares; _stakingPoolInfo.totalStakes -= removedStake; } // Harvest for (uint32 rewardTokenId = 0; rewardTokenId < _stakingPoolInfo.rewardPerEpoch.length; rewardTokenId++) { // NOTE: Calculate pending reward using original stake to avoid rounding down twice uint256 pendingReward = (originalStake * _stakingPoolInfo.accumulatedRewardPerUnit[rewardTokenId]) / STAKING_SCALE_FACTOR - _accountInfo.rewardDebts[poolId][rewardTokenId]; _accountInfo.rewardDebts[poolId][rewardTokenId] = (_accountInfo.stakes[poolId] * _stakingPoolInfo.accumulatedRewardPerUnit[rewardTokenId]) / STAKING_SCALE_FACTOR; uint32 assetId = _stakingPoolInfo.rewardAssetIds[rewardTokenId]; _globalInfo.rewards = tn.adjustUint256Array(_globalInfo.rewards, assetId); // Cap to available reward if (pendingReward > _globalInfo.rewards[assetId]) { pendingReward = _globalInfo.rewards[assetId]; } _accountInfo.idleAssets[assetId] += pendingReward; _globalInfo.rewards[assetId] -= pendingReward; } tn.adjustAccountShareEntries(_accountInfo, _stakingPoolInfo.strategyId); _accountInfo.shares[_stakingPoolInfo.strategyId] += _transition.shares - feeInShares; return (_accountInfo, _stakingPoolInfo, _globalInfo); } /** * @notice Apply an AddPoolTransition. * * @param _transition The disputed transition. * @param _stakingPoolInfo The involved staking pool from the previous transition. * @param _globalInfo The involved global info from the previous transition. * @return new staking pool info after applying the disputed transition */ function applyAddPoolTransition( dt.AddPoolTransition memory _transition, dt.StakingPoolInfo memory _stakingPoolInfo, dt.GlobalInfo memory _globalInfo ) external pure returns (dt.StakingPoolInfo memory) { require(_transition.rewardAssetIds.length > 0, ErrMsg.REQ_BAD_LEN); require(_transition.rewardAssetIds.length == _transition.rewardPerEpoch.length, ErrMsg.REQ_BAD_LEN); require(_stakingPoolInfo.strategyId == 0, ErrMsg.REQ_BAD_SP); require(_transition.startEpoch >= _globalInfo.currEpoch, ErrMsg.REQ_BAD_EPOCH); _stakingPoolInfo.lastRewardEpoch = _transition.startEpoch; _stakingPoolInfo.stakeAdjustmentFactor = _transition.stakeAdjustmentFactor; _stakingPoolInfo.strategyId = _transition.strategyId; _stakingPoolInfo.rewardAssetIds = new uint32[](_transition.rewardAssetIds.length); for (uint256 i = 0; i < _transition.rewardAssetIds.length; i++) { _stakingPoolInfo.rewardAssetIds[i] = _transition.rewardAssetIds[i]; } _stakingPoolInfo.accumulatedRewardPerUnit = tn.adjustUint256Array( _stakingPoolInfo.accumulatedRewardPerUnit, uint32(_transition.rewardAssetIds.length - 1) ); _stakingPoolInfo.rewardPerEpoch = new uint256[](_transition.rewardPerEpoch.length); for (uint256 i = 0; i < _transition.rewardPerEpoch.length; i++) { _stakingPoolInfo.rewardPerEpoch[i] = _transition.rewardPerEpoch[i]; } return _stakingPoolInfo; } /** * @notice Apply an UpdatePoolTransition. * * @param _transition The disputed transition. * @param _stakingPoolInfo The involved staking pool from the previous transition. * @param _globalInfo The involved global info from the previous transition. * @return new staking pool info after applying the disputed transition */ function applyUpdatePoolTransition( dt.UpdatePoolTransition memory _transition, dt.StakingPoolInfo memory _stakingPoolInfo, dt.GlobalInfo memory _globalInfo ) external pure returns (dt.StakingPoolInfo memory) { require(_transition.rewardPerEpoch.length == _stakingPoolInfo.rewardPerEpoch.length, ErrMsg.REQ_BAD_LEN); require(_stakingPoolInfo.strategyId > 0, ErrMsg.REQ_BAD_SP); _updatePoolStates(_stakingPoolInfo, _globalInfo); _stakingPoolInfo.rewardPerEpoch = new uint256[](_transition.rewardPerEpoch.length); for (uint256 i = 0; i < _transition.rewardPerEpoch.length; i++) { _stakingPoolInfo.rewardPerEpoch[i] = _transition.rewardPerEpoch[i]; } return _stakingPoolInfo; } /** * @notice Apply a DepositRewardTransition. * * @param _transition The disputed transition. * @param _globalInfo The involved global info from the previous transition. * @return new global info after applying the disputed transition */ function applyDepositRewardTransition( dt.DepositRewardTransition memory _transition, dt.GlobalInfo memory _globalInfo ) public pure returns (dt.GlobalInfo memory) { _globalInfo.rewards = tn.adjustUint256Array(_globalInfo.rewards, _transition.assetId); _globalInfo.rewards[_transition.assetId] += _transition.amount; return _globalInfo; } /********************* * Private Functions * *********************/ function _updatePoolStates(dt.StakingPoolInfo memory _stakingPoolInfo, dt.GlobalInfo memory _globalInfo) private pure { if (_globalInfo.currEpoch > _stakingPoolInfo.lastRewardEpoch) { uint256 totalStakes = _stakingPoolInfo.totalStakes; if (totalStakes > 0) { uint64 numEpochs = _globalInfo.currEpoch - _stakingPoolInfo.lastRewardEpoch; for ( uint32 rewardTokenId = 0; rewardTokenId < _stakingPoolInfo.rewardPerEpoch.length; rewardTokenId++ ) { uint256 pendingReward = numEpochs * _stakingPoolInfo.rewardPerEpoch[rewardTokenId]; _stakingPoolInfo.accumulatedRewardPerUnit[rewardTokenId] += ((pendingReward * STAKING_SCALE_FACTOR) / totalStakes); } } _stakingPoolInfo.lastRewardEpoch = _globalInfo.currEpoch; } } /** * Helper to expand the account array of staked shares and stakes if needed. */ function _adjustAccountStakedShareAndStakeEntries(dt.AccountInfo memory _accountInfo, uint32 poolId) private pure { uint32 n = uint32(_accountInfo.stakedShares.length); if (n <= poolId) { uint256[] memory arr = new uint256[](poolId + 1); for (uint32 i = 0; i < n; i++) { arr[i] = _accountInfo.stakedShares[i]; } for (uint32 i = n; i <= poolId; i++) { arr[i] = 0; } _accountInfo.stakedShares = arr; } n = uint32(_accountInfo.stakes.length); if (n <= poolId) { uint256[] memory arr = new uint256[](poolId + 1); for (uint32 i = 0; i < n; i++) { arr[i] = _accountInfo.stakes[i]; } for (uint32 i = n; i <= poolId; i++) { arr[i] = 0; } _accountInfo.stakes = arr; } } /** * Helper to expand the 2D array of account reward debt entries per pool and reward token IDs. */ function _adjustAccountRewardDebtEntries( dt.AccountInfo memory _accountInfo, uint32 poolId, uint32 rewardTokenId ) private pure { uint32 n = uint32(_accountInfo.rewardDebts.length); if (n <= poolId) { uint256[][] memory rewardDebts = new uint256[][](poolId + 1); for (uint32 i = 0; i < n; i++) { rewardDebts[i] = _accountInfo.rewardDebts[i]; } for (uint32 i = n; i < poolId; i++) { rewardDebts[i] = new uint256[](0); } rewardDebts[poolId] = new uint256[](rewardTokenId + 1); _accountInfo.rewardDebts = rewardDebts; } uint32 nRewardTokens = uint32(_accountInfo.rewardDebts[poolId].length); if (nRewardTokens <= rewardTokenId) { uint256[] memory debts = new uint256[](rewardTokenId + 1); for (uint32 i = 0; i < nRewardTokens; i++) { debts[i] = _accountInfo.rewardDebts[poolId][i]; } for (uint32 i = nRewardTokens; i <= rewardTokenId; i++) { debts[i] = 0; } _accountInfo.rewardDebts[poolId] = debts; } } /** * @notice Calculates the adjusted stake from staked shares. * @param _stakedShares The staked shares * @param _adjustmentFactor The adjustment factor, a value from (0, 1) * STAKING_SCALE_FACTOR */ function _getAdjustedStake(uint256 _stakedShares, uint256 _adjustmentFactor) private pure returns (uint256) { return ((STAKING_SCALE_FACTOR - _adjustmentFactor) * _stakedShares + _sqrt(STAKING_SCALE_FACTOR * _adjustmentFactor * _stakedShares)) / STAKING_SCALE_FACTOR; } /** * @notice Implements square root with Babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method). * @param _y The input */ function _sqrt(uint256 _y) private pure returns (uint256) { uint256 z; if (_y > 3) { z = _y; uint256 x = _y / 2 + 1; while (x < z) { z = x; x = (_y / x + x) / 2; } } else if (_y != 0) { z = 1; } return z; } }
Apply a TransferOperatorFeeTransition. _transition The disputed transition. _accountInfo The involved account from the previous transition. _globalInfo The involved global info from the previous transition. return new account info and global info after applying the disputed transition/
function applyTransferOperatorFeeTransition( dt.TransferOperatorFeeTransition memory _transition, dt.AccountInfo memory _accountInfo, dt.GlobalInfo memory _globalInfo ) external pure returns (dt.AccountInfo memory, dt.GlobalInfo memory) { require(_accountInfo.accountId == _transition.accountId, ErrMsg.REQ_BAD_ACCT); require(_accountInfo.account != address(0), ErrMsg.REQ_BAD_ACCT); uint32 assetFeeLen = uint32(_globalInfo.opFees.assets.length); if (assetFeeLen > 1) { tn.adjustAccountIdleAssetEntries(_accountInfo, assetFeeLen - 1); for (uint256 i = 1; i < assetFeeLen; i++) { _accountInfo.idleAssets[i] += _globalInfo.opFees.assets[i]; _globalInfo.opFees.assets[i] = 0; } } uint32 shareFeeLen = uint32(_globalInfo.opFees.shares.length); if (shareFeeLen > 1) { tn.adjustAccountShareEntries(_accountInfo, shareFeeLen - 1); for (uint256 i = 1; i < shareFeeLen; i++) { _accountInfo.shares[i] += _globalInfo.opFees.shares[i]; _globalInfo.opFees.shares[i] = 0; } } return (_accountInfo, _globalInfo); }
12,924,559
./full_match/1/0xa9F60bF2676D5069A279496076cabF8aE713Af44/sources/contracts/client.sol
Purchase multiple NFTs at once
function purchaseTokens(uint256 _howMany) external payable tokensAvailable(_howMany) { require(isSaleActive, "Sale is not active"); require(_howMany > 0, "Mint min 1"); require(msg.value >= _howMany * itemPrice, "Try to send more ETH"); uint256 ownerMintedCount = addressMintedBalance[msg.sender]; require(ownerMintedCount + _howMany <= nftPerAddressLimit, "max NFT per address exceeded"); _safeMint(msg.sender, _howMany); }
16,429,701
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "./open-zeppelin/interfaces/IERC20.sol"; import "./open-zeppelin/libraries/SafeERC20.sol"; import "./open-zeppelin/utils/Ownable.sol"; import "./open-zeppelin/utils/Pausable.sol"; import "./open-zeppelin/utils/ReentrancyGuard.sol"; import "./interfaces/IVotingEscrow.sol"; import "./interfaces/IVotingEscrowDelegation.sol"; import "./utils/Errors.sol"; /** @title Warden contract */ /// @author Paladin /* Delegation market based on Curve VotingEscrowDelegation contract */ contract Warden is Ownable, Pausable, ReentrancyGuard { using SafeERC20 for IERC20; // Constants : uint256 public constant UNIT = 1e18; uint256 public constant MAX_PCT = 10000; uint256 public constant WEEK = 7 * 86400; // Storage : /** @notice Offer made by an user to buy a given amount of his votes user : Address of the user making the offer pricePerVote : Price per vote per second, set by the user minPerc : Minimum percent of users voting token balance to buy for a Boost (in BPS) maxPerc : Maximum percent of users total voting token balance available to delegate (in BPS) */ struct BoostOffer { // Address of the user making the offer address user; // Price per vote per second, set by the user uint256 pricePerVote; // Max duration a Boost from this offer can last uint64 maxDuration; // Timestamp of expiry of the Offer uint64 expiryTime; // Minimum percent of users voting token balance to buy for a Boost uint16 minPerc; //bps // Maximum percent of users total voting token balance available to delegate uint16 maxPerc; //bps // Use the advised price instead of the Offer one bool useAdvicePrice; } /** @notice ERC20 used to pay for DelegationBoost */ IERC20 public feeToken; /** @notice Address of the votingToken to delegate */ IVotingEscrow public votingEscrow; /** @notice Address of the Delegation Boost contract */ IVotingEscrowDelegation public delegationBoost; /** @notice ratio of fees to be set as Reserve (in BPS) */ uint256 public feeReserveRatio; //bps /** @notice Total Amount in the Reserve */ uint256 public reserveAmount; /** @notice Address allowed to withdraw from the Reserve */ address public reserveManager; /** @notice Min Percent of delegator votes to buy required to purchase a Delegation Boost (in BPS) */ uint256 public minPercRequired; //bps /** @notice Minimum delegation time, taken from veBoost contract */ uint256 public minDelegationTime = 1 weeks; /** @notice List of all current registered users and their delegation offer */ BoostOffer[] public offers; /** @notice Index of the user in the offers array */ mapping(address => uint256) public userIndex; /** @notice Amount of fees earned by users through Boost selling */ mapping(address => uint256) public earnedFees; bool private _claimBlocked; /** @notice Price per vote advised by the maangers for users that don't handle their pricing themselves */ uint256 public advisedPrice; /** @notice Address approved to mamange the advised price */ mapping(address => bool) public approvedManagers; /** @notice Next period to update for the Reward State */ uint256 public nextUpdatePeriod; /** @notice Reward Index by period */ mapping(uint256 => uint256) public periodRewardIndex; /** @notice Base amount of reward to distribute weekly for each veCRV purchased */ uint256 public baseWeeklyDropPerVote; /** @notice Minimum amount of reward to distribute weekly for each veCRV purchased */ uint256 public minWeeklyDropPerVote; /** @notice Target amount of veCRV Boosts to be purchased in a period */ uint256 public targetPurchaseAmount; /** @notice Amount of reward to distribute for the period */ mapping(uint256 => uint256) public periodDropPerVote; /** @notice Amount of veCRV Boosts pruchased for the period */ mapping(uint256 => uint256) public periodPurchasedAmount; /** @notice Decrease of the Purchased amount at the end of the period (since veBoost amounts decrease over time) */ mapping(uint256 => uint256) public periodEndPurchasedDecrease; /** @notice Changes in the periodEndPurchasedDecrease for the period */ mapping(uint256 => uint256) public periodPurchasedDecreaseChanges; /** @notice Amount of rewards paid in extra during last periods */ uint256 public extraPaidPast; /** @notice Reamining rewards not distributed from last periods */ uint256 public remainingRewardPastPeriod; struct PurchasedBoost { uint256 amount; uint256 startIndex; uint128 startTimestamp; uint128 endTimestamp; address buyer; bool claimed; } /** @notice Mapping of a Boost purchase info, stored by the Boost token ID */ mapping(uint256 => PurchasedBoost) public purchasedBoosts; /** @notice List of the Boost purchased by an user */ mapping(address => uint256[]) public userPurchasedBoosts; /** @notice Reward token to distribute to buyers */ IERC20 public rewardToken; // Events : event Registred(address indexed user, uint256 price); event UpdateOffer(address indexed user, uint256 newPrice); event UpdateOfferPrice(address indexed user, uint256 newPrice); event Quit(address indexed user); event BoostPurchase( address indexed delegator, address indexed receiver, uint256 tokenId, uint256 percent, //bps uint256 price, uint256 paidFeeAmount, uint256 expiryTime ); event Claim(address indexed user, uint256 amount); event ClaimReward(uint256 boostId, address indexed user, uint256 amount); event NewAdvisedPrice(uint256 newPrice); modifier onlyAllowed(){ if(msg.sender != reserveManager && msg.sender != owner()) revert Errors.CallerNotAllowed(); _; } // Constructor : /** * @dev Creates the contract, set the given base parameters * @param _feeToken address of the token used to pay fees * @param _votingEscrow address of the voting token to delegate * @param _delegationBoost address of the contract handling delegation * @param _feeReserveRatio Percent of fees to be set as Reserve (bps) * @param _minPercRequired Minimum percent of user */ constructor( address _feeToken, address _votingEscrow, address _delegationBoost, uint256 _feeReserveRatio, //bps uint256 _minPercRequired, //bps uint256 _advisedPrice ) { feeToken = IERC20(_feeToken); votingEscrow = IVotingEscrow(_votingEscrow); delegationBoost = IVotingEscrowDelegation(_delegationBoost); require(_advisedPrice > 0); advisedPrice = _advisedPrice; require(_feeReserveRatio <= 5000); require(_minPercRequired > 0 && _minPercRequired <= 10000); feeReserveRatio = _feeReserveRatio; minPercRequired = _minPercRequired; // fill index 0 in the offers array // since we want to use index 0 for unregistered users offers.push(BoostOffer(address(0), 0, 0, 0, 0, 0, false)); } // Modifiers : modifier rewardStateUpdate() { if(!updateRewardState()) revert Errors.FailRewardUpdate(); _; } // Functions : /** * @notice Amount of Offer listed in this market * @dev Amount of Offer listed in this market */ function offersIndex() external view returns(uint256){ return offers.length; } /** * @notice Returns the current period * @dev Calculates and returns the current period based on current timestamp */ function currentPeriod() public view returns(uint256) { return (block.timestamp / WEEK) * WEEK; } /** * @notice Updates the reward state for all past periods * @dev Updates the reward state for all past periods */ function updateRewardState() public whenNotPaused returns(bool){ if(nextUpdatePeriod == 0) return true; // Reward distribution not initialized // Updates once a week // If last update is less than a week ago, simply return uint256 _currentPeriod = currentPeriod(); if(_currentPeriod <= nextUpdatePeriod) return true; uint256 period = nextUpdatePeriod; // Only update 100 period at a time for(uint256 i; i < 100;){ if(period >= _currentPeriod) break; uint256 nextPeriod = period + WEEK; // Calculate the expected amount ot be distributed for the week (the period) // And how much was distributed for that period (based on purchased amounts & period drop per vote) uint256 weeklyDropAmount = (baseWeeklyDropPerVote * targetPurchaseAmount) / UNIT; uint256 periodRewardAmount = (periodPurchasedAmount[period] * periodDropPerVote[period]) / UNIT; // In case we distributed less than the objective if(periodRewardAmount <= weeklyDropAmount){ uint256 undistributedAmount = weeklyDropAmount - periodRewardAmount; // Remove any extra amount distributed from past periods // And set any remaining rewards to be distributed as surplus for next period if(extraPaidPast != 0){ if(undistributedAmount >= extraPaidPast){ undistributedAmount -= extraPaidPast; extraPaidPast = 0; } else{ extraPaidPast -= undistributedAmount; undistributedAmount = 0; } } remainingRewardPastPeriod += undistributedAmount; } else { // In case we distributed more than the objective uint256 overdistributedAmount = periodRewardAmount - weeklyDropAmount; // Remove the extra distributed from the remaining rewards from past period (if there is any) // And set the rest of the extra distributed rewards to be accounted for next period if(remainingRewardPastPeriod != 0){ if(overdistributedAmount >= remainingRewardPastPeriod){ overdistributedAmount -= remainingRewardPastPeriod; remainingRewardPastPeriod = 0; } else{ remainingRewardPastPeriod -= overdistributedAmount; overdistributedAmount = 0; } } extraPaidPast += overdistributedAmount; } // Calculate nextPeriod new drop // Based on the basic weekly drop, and any extra reward paid past periods, or remaining rewards from last period // In case remainingRewardPastPeriod > 0, then the nextPeriodDropPerVote should be higher than the base one // And in case there is extraPaidPast >0, the nextPeriodDropPerVote should be less // But nextPeriodDropPerVote can never be less than minWeeklyDropPerVote // (In that case, we expected the next period to have extra rewards paid again, and to reach back the objective on future periods) uint256 nextPeriodDropPerVote; if(extraPaidPast >= weeklyDropAmount + remainingRewardPastPeriod){ nextPeriodDropPerVote = minWeeklyDropPerVote; } else { uint256 tempWeeklyDropPerVote = ((weeklyDropAmount + remainingRewardPastPeriod - extraPaidPast) * UNIT) / targetPurchaseAmount; nextPeriodDropPerVote = tempWeeklyDropPerVote > minWeeklyDropPerVote ? tempWeeklyDropPerVote : minWeeklyDropPerVote; } periodDropPerVote[nextPeriod] = nextPeriodDropPerVote; // Update the index for the period, based on the period DropPerVote periodRewardIndex[nextPeriod] = periodRewardIndex[period] + periodDropPerVote[period]; // Make next period purchased amount decrease changes if(periodPurchasedAmount[period] >= periodEndPurchasedDecrease[period]){ periodPurchasedAmount[nextPeriod] += periodPurchasedAmount[period] - periodEndPurchasedDecrease[period]; // Else, we consider the current period purchased amount as totally removed } if(periodEndPurchasedDecrease[period] >= periodPurchasedDecreaseChanges[nextPeriod]){ periodEndPurchasedDecrease[nextPeriod] += periodEndPurchasedDecrease[period] - periodPurchasedDecreaseChanges[nextPeriod]; // Else the decrease from the current period does not need to be kept for the next period } // Go to next period period = nextPeriod; unchecked{ ++i; } } // Set the period where we stopped (and not updated), as the next period to be updated nextUpdatePeriod = period; return true; } /** * @notice Registers a new user wanting to sell its delegation * @dev Regsiters a new user, creates a BoostOffer with the given parameters * @param pricePerVote Price of 1 vote per second (in wei) * @param minPerc Minimum percent of users voting token balance to buy for a Boost (in BPS) * @param maxPerc Maximum percent of users total voting token balance available to delegate (in BPS) */ function register( uint256 pricePerVote, uint64 maxDuration, uint64 expiryTime, uint16 minPerc, uint16 maxPerc, bool useAdvicePrice ) external whenNotPaused rewardStateUpdate returns(bool) { address user = msg.sender; if(userIndex[user] != 0) revert Errors.AlreadyRegistered(); if(!delegationBoost.isApprovedForAll(user, address(this))) revert Errors.WardenNotOperator(); if(pricePerVote == 0) revert Errors.NullPrice(); if(maxPerc > 10000) revert Errors.MaxPercTooHigh(); if(minPerc > maxPerc) revert Errors.MinPercOverMaxPerc(); if(minPerc < minPercRequired) revert Errors.MinPercTooLow(); if(maxDuration == 0) revert Errors.NullMaxDuration(); if(expiryTime != 0 && expiryTime < (block.timestamp + WEEK)) revert Errors.IncorrectExpiry(); if(expiryTime == 0) expiryTime = uint64(votingEscrow.locked__end(user)); // Create the BoostOffer for the new user, and add it to the storage userIndex[user] = offers.length; offers.push(BoostOffer(user, pricePerVote, maxDuration, expiryTime, minPerc, maxPerc, useAdvicePrice)); emit Registred(user, pricePerVote); return true; } /** * @notice Updates an user BoostOffer parameters * @dev Updates parameters for the user's BoostOffer * @param pricePerVote Price of 1 vote per second (in wei) * @param minPerc Minimum percent of users voting token balance to buy for a Boost (in BPS) * @param maxPerc Maximum percent of users total voting token balance available to delegate (in BPS) */ function updateOffer( uint256 pricePerVote, uint64 maxDuration, uint64 expiryTime, uint16 minPerc, uint16 maxPerc, bool useAdvicePrice ) external whenNotPaused rewardStateUpdate returns(bool) { // Fetch the user index, and check for registration address user = msg.sender; uint256 index = userIndex[user]; if(index == 0) revert Errors.NotRegistered(); // Fetch the BoostOffer to update BoostOffer storage offer = offers[index]; if(offer.user != msg.sender) revert Errors.NotOfferOwner(); if(pricePerVote == 0) revert Errors.NullPrice(); if(maxPerc > 10000) revert Errors.MaxPercTooHigh(); if(minPerc > maxPerc) revert Errors.MinPercOverMaxPerc(); if(minPerc < minPercRequired) revert Errors.MinPercTooLow(); if(maxDuration == 0) revert Errors.NullMaxDuration(); if(expiryTime != 0 && expiryTime < (block.timestamp + WEEK)) revert Errors.IncorrectExpiry(); if(expiryTime == 0) expiryTime = uint64(votingEscrow.locked__end(user)); // Update the parameters offer.pricePerVote = pricePerVote; offer.maxDuration = maxDuration; offer.expiryTime = expiryTime; offer.minPerc = minPerc; offer.maxPerc = maxPerc; offer.useAdvicePrice = useAdvicePrice; emit UpdateOffer(user, useAdvicePrice ? advisedPrice : pricePerVote); return true; } /** * @notice Updates an user BoostOffer price parameters * @dev Updates an user BoostOffer price parameters * @param pricePerVote Price of 1 vote per second (in wei) * @param useAdvicePrice Bool: use advised price */ function updateOfferPrice( uint256 pricePerVote, bool useAdvicePrice ) external whenNotPaused rewardStateUpdate returns(bool) { // Fet the user index, and check for registration address user = msg.sender; uint256 index = userIndex[user]; if(index == 0) revert Errors.NotRegistered(); // Fetch the BoostOffer to update BoostOffer storage offer = offers[index]; if(offer.user != msg.sender) revert Errors.NotOfferOwner(); if(pricePerVote == 0) revert Errors.NullPrice(); // Update the parameters offer.pricePerVote = pricePerVote; offer.useAdvicePrice = useAdvicePrice; emit UpdateOfferPrice(user, useAdvicePrice ? advisedPrice : pricePerVote); return true; } /** * @notice Returns the Offer data * @dev Returns the Offer struct from storage * @param index Index of the Offer in the list */ function getOffer(uint256 index) external view returns( address user, uint256 pricePerVote, uint64 maxDuration, uint64 expiryTime, uint16 minPerc, uint16 maxPerc ) { BoostOffer storage offer = offers[index]; return( offer.user, offer.useAdvicePrice ? advisedPrice : offer.pricePerVote, offer.maxDuration, offer.expiryTime, offer.minPerc, offer.maxPerc ); } /** * @notice Remove the BoostOffer of the user, and claim any remaining fees earned * @dev User's BoostOffer is removed from the listing, and any unclaimed fees is sent */ function quit() external whenNotPaused nonReentrant rewardStateUpdate returns(bool) { address user = msg.sender; if(userIndex[user] == 0) revert Errors.NotRegistered(); // Check for unclaimed fees, claim it if needed if (earnedFees[user] > 0) { _claim(user, earnedFees[user]); } // Find the BoostOffer to remove uint256 currentIndex = userIndex[user]; // If BoostOffer is not the last of the list // Replace last of the list with the one to remove if (currentIndex < offers.length) { uint256 lastIndex = offers.length - 1; address lastUser = offers[lastIndex].user; offers[currentIndex] = offers[lastIndex]; userIndex[lastUser] = currentIndex; } //Remove the last item of the list offers.pop(); userIndex[user] = 0; emit Quit(user); return true; } /** * @notice Gives an estimate of fees to pay for a given Boost Delegation * @dev Calculates the amount of fees for a Boost Delegation with the given amount (through the percent) and the duration * @param delegator Address of the delegator for the Boost * @param percent Percent of the delegator balance to delegate (in BPS) * @param duration Duration (in weeks) of the Boost to purchase */ function estimateFees( address delegator, uint256 percent, uint256 duration //in weeks ) external view returns (uint256) { if(delegator == address(0)) revert Errors.ZeroAddress(); if(userIndex[delegator] == 0) revert Errors.NotRegistered(); if(percent < minPercRequired) revert Errors.PercentUnderMinRequired(); if(percent > MAX_PCT) revert Errors.PercentOverMax(); // Fetch the BoostOffer for the delegator BoostOffer storage offer = offers[userIndex[delegator]]; //Check that the duration is less or equal to Offer maxDuration if(duration > offer.maxDuration) revert Errors.DurationOverOfferMaxDuration(); if(block.timestamp > offer.expiryTime) revert Errors.OfferExpired(); // Get the duration in seconds, and check it's more than the minimum required uint256 durationSeconds = duration * 1 weeks; if(durationSeconds < minDelegationTime) revert Errors.DurationTooShort(); if(percent < offer.minPerc || percent > offer.maxPerc) revert Errors.PercentOutOfferBonds(); uint256 expiryTime = ((block.timestamp + durationSeconds) / WEEK) * WEEK; expiryTime = (expiryTime < block.timestamp + durationSeconds) ? ((block.timestamp + durationSeconds + WEEK) / WEEK) * WEEK : expiryTime; if(expiryTime > votingEscrow.locked__end(delegator)) revert Errors.LockEndTooShort(); // Find how much of the delegator's tokens the given percent represents uint256 delegatorBalance = votingEscrow.balanceOf(delegator); uint256 toDelegateAmount = (delegatorBalance * percent) / MAX_PCT; //Should we use the Offer price or the advised one uint256 pricePerVote = offer.useAdvicePrice ? advisedPrice : offer.pricePerVote; // Get the price for the whole Amount (price fer second) uint256 priceForAmount = (toDelegateAmount * pricePerVote) / UNIT; // Then multiply it by the duration (in seconds) to get the cost of the Boost return priceForAmount * durationSeconds; } /** All local variables used in the buyDelegationBoost function */ struct BuyVars { uint256 boostDuration; uint256 delegatorBalance; uint256 toDelegateAmount; uint256 pricePerVote; uint256 realFeeAmount; uint256 expiryTime; uint256 cancelTime; uint256 boostPercent; uint256 newId; uint256 newTokenId; uint256 currentPeriod; uint256 currentRewardIndex; uint256 boostWeeklyDecrease; } /** * @notice Buy a Delegation Boost for a Delegator Offer * @dev If all parameters match the offer from the delegator, creates a Boost for the caller * @param delegator Address of the delegator for the Boost * @param receiver Address of the receiver of the Boost * @param percent Percent of the delegator balance to delegate (in BPS) * @param duration Duration (in weeks) of the Boost to purchase * @param maxFeeAmount Maximum amount of feeToken available to pay to cover the Boost Duration (in wei) * returns the id of the new veBoost */ function buyDelegationBoost( address delegator, address receiver, uint256 percent, uint256 duration, //in weeks uint256 maxFeeAmount ) external nonReentrant whenNotPaused rewardStateUpdate returns(uint256) { if(delegator == address(0) || receiver == address(0)) revert Errors.ZeroAddress(); if(userIndex[delegator] == 0) revert Errors.NotRegistered(); if(maxFeeAmount == 0) revert Errors.NullFees(); if(percent < minPercRequired) revert Errors.PercentUnderMinRequired(); if(percent > MAX_PCT) revert Errors.PercentOverMax(); BuyVars memory vars; // Fetch the BoostOffer for the delegator BoostOffer storage offer = offers[userIndex[delegator]]; //Check that the duration is less or equal to Offer maxDuration if(duration > offer.maxDuration) revert Errors.DurationOverOfferMaxDuration(); if(block.timestamp > offer.expiryTime) revert Errors.OfferExpired(); // Get the duration of the wanted Boost in seconds vars.boostDuration = duration * 1 weeks; if(vars.boostDuration < minDelegationTime) revert Errors.DurationTooShort(); if(percent < offer.minPerc || percent > offer.maxPerc) revert Errors.PercentOutOfferBonds(); // Find how much of the delegator's tokens the given percent represents vars.delegatorBalance = votingEscrow.balanceOf(delegator); vars.toDelegateAmount = (vars.delegatorBalance * percent) / MAX_PCT; // Check if delegator can delegate the amount, without exceeding the maximum percent allowed by the delegator // _canDelegate will also try to cancel expired Boosts of the deelgator to free more tokens for delegation if(!_canDelegate(delegator, vars.toDelegateAmount, offer.maxPerc)) revert Errors.CannotDelegate(); //Should we use the Offer price or the advised one vars.pricePerVote = offer.useAdvicePrice ? advisedPrice : offer.pricePerVote; // Calculate the price for the given duration, get the real amount of fees to pay, // and check the maxFeeAmount provided (and approved beforehand) is enough. // Calculated using the pricePerVote set by the delegator vars.realFeeAmount = (vars.toDelegateAmount * vars.pricePerVote * vars.boostDuration) / UNIT; if(vars.realFeeAmount > maxFeeAmount) revert Errors.FeesTooLow(); // Pull the tokens from the buyer, setting it as earned fees for the delegator (and part of it for the Reserve) _pullFees(msg.sender, vars.realFeeAmount, delegator); // Calcualte the expiry time for the Boost = now + duration vars.expiryTime = ((block.timestamp + vars.boostDuration) / WEEK) * WEEK; // Hack needed because veBoost contract rounds down expire_time // We don't want buyers to receive less than they pay for // So an "extra" week is added if needed to get an expire_time covering the required duration // But cancel_time will be set for the exact paid duration, so any "bonus days" received can be canceled // if a new buyer wants to take the offer vars.expiryTime = (vars.expiryTime < block.timestamp + vars.boostDuration) ? ((block.timestamp + vars.boostDuration + WEEK) / WEEK) * WEEK : vars.expiryTime; if(vars.expiryTime > votingEscrow.locked__end(delegator)) revert Errors.LockEndTooShort(); // VotingEscrowDelegation needs the percent of available tokens for delegation when creating the boost, instead of // the percent of the users balance. We calculate this percent representing the amount of tokens wanted by the buyer vars.boostPercent = (vars.toDelegateAmount * MAX_PCT) / (vars.delegatorBalance - delegationBoost.delegated_boost(delegator)); // Get the id (depending on the delegator) for the new Boost vars.newId = delegationBoost.total_minted(delegator); unchecked { // cancelTime stays current timestamp + paid duration // Should not overflow : Since expiryTime is the same + some extra time, expiryTime >= cancelTime vars.cancelTime = block.timestamp + vars.boostDuration; } // Creates the DelegationBoost delegationBoost.create_boost( delegator, receiver, int256(vars.boostPercent), vars.cancelTime, vars.expiryTime, vars.newId ); // Fetch the tokenId for the new DelegationBoost that was created, and check it was set for the correct delegator vars.newTokenId = delegationBoost.get_token_id(delegator, vars.newId); if( vars.newTokenId != delegationBoost.token_of_delegator_by_index(delegator, vars.newId) ) revert Errors.FailDelegationBoost(); // If rewards were started, otherwise no need to write for that Boost if(nextUpdatePeriod != 0) { // Find the current reward index vars.currentPeriod = currentPeriod(); vars.currentRewardIndex = periodRewardIndex[vars.currentPeriod] + ( (periodDropPerVote[vars.currentPeriod] * (block.timestamp - vars.currentPeriod)) / WEEK ); // Add the amount purchased to the period purchased amount (& the decrease + decrease change) vars.boostWeeklyDecrease = (vars.toDelegateAmount * WEEK) / (vars.expiryTime - block.timestamp); uint256 nextPeriod = vars.currentPeriod + WEEK; periodPurchasedAmount[vars.currentPeriod] += vars.toDelegateAmount; periodEndPurchasedDecrease[vars.currentPeriod] += (vars.boostWeeklyDecrease * (nextPeriod - block.timestamp)) / WEEK; periodPurchasedDecreaseChanges[nextPeriod] += (vars.boostWeeklyDecrease * (nextPeriod - block.timestamp)) / WEEK; if(vars.expiryTime != (nextPeriod)){ periodEndPurchasedDecrease[nextPeriod] += vars.boostWeeklyDecrease; periodPurchasedDecreaseChanges[vars.expiryTime] += vars.boostWeeklyDecrease; } // Write the Purchase for rewards purchasedBoosts[vars.newTokenId] = PurchasedBoost( vars.toDelegateAmount, vars.currentRewardIndex, uint128(block.timestamp), uint128(vars.expiryTime), receiver, false ); userPurchasedBoosts[receiver].push(vars.newTokenId); } emit BoostPurchase( delegator, receiver, vars.newTokenId, percent, vars.pricePerVote, vars.realFeeAmount, vars.expiryTime ); return vars.newTokenId; } /** * @notice Cancels a DelegationBoost * @dev Cancels a DelegationBoost : * In case the caller is the owner of the Boost, at any time * In case the caller is the delegator for the Boost, after cancel_time * Else, after expiry_time * @param tokenId Id of the DelegationBoost token to cancel */ function cancelDelegationBoost(uint256 tokenId) external whenNotPaused rewardStateUpdate returns(bool) { address tokenOwner = delegationBoost.ownerOf(tokenId); // If the caller own the token, and this contract is operator for the owner // we try to burn the token directly if ( msg.sender == tokenOwner && delegationBoost.isApprovedForAll(tokenOwner, address(this)) ) { delegationBoost.burn(tokenId); return true; } uint256 currentTime = block.timestamp; // Delegator can cancel the Boost if Cancel Time passed address delegator = _getTokenDelegator(tokenId); if ( delegationBoost.token_cancel_time(tokenId) < currentTime && (msg.sender == delegator && delegationBoost.isApprovedForAll(delegator, address(this))) ) { delegationBoost.cancel_boost(tokenId); return true; } // Else, we wait Exipiry Time, so anyone can cancel the delegation if (delegationBoost.token_expiry(tokenId) < currentTime) { delegationBoost.cancel_boost(tokenId); return true; } revert Errors.CannotCancelBoost(); } /** * @notice Returns the amount of fees earned by the user that can be claimed * @dev Returns the value in earnedFees for the given user * @param user Address of the user */ function claimable(address user) external view returns (uint256) { return earnedFees[user]; } /** * @notice Claims all earned fees * @dev Send all the user's earned fees */ function claim() external nonReentrant rewardStateUpdate returns(bool) { if(earnedFees[msg.sender] == 0) revert Errors.NullClaimAmount(); return _claim(msg.sender, earnedFees[msg.sender]); } /** * @notice Claims all earned fees, and cancel all expired Delegation Boost for the user * @dev Send all the user's earned fees, and fetch all expired Boosts to cancel them */ function claimAndCancel() external nonReentrant rewardStateUpdate returns(bool) { _cancelAllExpired(msg.sender); return _claim(msg.sender, earnedFees[msg.sender]); } /** * @notice Claims an amount of earned fees through Boost Delegation selling * @dev Send the given amount of earned fees (if amount is correct) * @param amount Amount of earned fees to claim */ function claim(uint256 amount) external nonReentrant rewardStateUpdate returns(bool) { if(amount > earnedFees[msg.sender]) revert Errors.AmountTooHigh(); if(amount == 0) revert Errors.NullClaimAmount(); return _claim(msg.sender, amount); } /** * @notice Get all Boosts purchased by an user * @dev Get all Boosts purchased by an user * @param user Address of the buyer */ function getUserPurchasedBoosts(address user) external view returns(uint256[] memory) { return userPurchasedBoosts[user]; } /** * @notice Get the Purchased Boost data * @dev Get the Purchased Boost struct from storage * @param boostId Id of the veBoost */ function getPurchasedBoost(uint256 boostId) external view returns(PurchasedBoost memory) { return purchasedBoosts[boostId]; } /** * @notice Get the amount of rewards for a Boost * @dev Get the amount of rewards for a Boost * @param boostId Id of the veBoost */ function getBoostReward(uint256 boostId) external view returns(uint256) { if(boostId == 0) revert Errors.InvalidBoostId(); return _getBoostRewardAmount(boostId); } /** * @notice Claim the rewards for a purchased Boost * @dev Claim the rewards for a purchased Boost * @param boostId Id of the veBoost */ function claimBoostReward(uint256 boostId) external nonReentrant rewardStateUpdate returns(bool) { if(boostId == 0) revert Errors.InvalidBoostId(); return _claimBoostRewards(boostId); } /** * @notice Claim the rewards for multiple Boosts * @dev Claim the rewards for multiple Boosts * @param boostIds List of veBoost Ids */ function claimMultipleBoostReward(uint256[] calldata boostIds) external nonReentrant rewardStateUpdate returns(bool) { uint256 length = boostIds.length; for(uint256 i; i < length;) { if(boostIds[i] == 0) revert Errors.InvalidBoostId(); require(_claimBoostRewards(boostIds[i])); unchecked{ ++i; } } return true; } function _pullFees( address buyer, uint256 amount, address seller ) internal { // Pull the given token amount ot this contract (must be approved beforehand) feeToken.safeTransferFrom(buyer, address(this), amount); // Split fees between Boost offerer & Reserve earnedFees[seller] += (amount * (MAX_PCT - feeReserveRatio)) / MAX_PCT; reserveAmount += (amount * feeReserveRatio) / MAX_PCT; } struct CanDelegateVars { uint256 balance; uint256 blockedBalance; uint256 availableBalance; uint256 nbTokens; uint256 delegatedBalance; uint256 potentialCancelableBalance; } function _canDelegate( address delegator, uint256 amount, uint256 delegatorMaxPerc ) internal returns (bool) { if (!delegationBoost.isApprovedForAll(delegator, address(this))) return false; CanDelegateVars memory vars; // Delegator current balance vars.balance = votingEscrow.balanceOf(delegator); // Percent of delegator balance not allowed to delegate (as set by maxPerc in the BoostOffer) vars.blockedBalance = (vars.balance * (MAX_PCT - delegatorMaxPerc)) / MAX_PCT; // Available Balance to delegate = VotingEscrow Balance - Blocked Balance vars.availableBalance = vars.balance - vars.blockedBalance; vars.nbTokens = delegationBoost.total_minted(delegator); uint256[256] memory expiredBoosts; //Need this type of array because of batch_cancel_boosts() from veBoost uint256 nbExpired = 0; // Loop over the delegator current boosts to find expired ones for (uint256 i = 0; i < vars.nbTokens;) { uint256 tokenId = delegationBoost.token_of_delegator_by_index( delegator, i ); // If boost expired if (delegationBoost.token_expiry(tokenId) < block.timestamp) { expiredBoosts[nbExpired] = tokenId; nbExpired++; } unchecked{ ++i; } } if (nbExpired > 0) { delegationBoost.batch_cancel_boosts(expiredBoosts); } // Then need to check what is the amount currently delegated out of the Available Balance vars.delegatedBalance = delegationBoost.delegated_boost(delegator); if(vars.availableBalance > vars.delegatedBalance){ if(amount <= (vars.availableBalance - vars.delegatedBalance)) return true; } // Check if cancel expired Boosts could bring enough to delegate vars.potentialCancelableBalance = 0; uint256[256] memory toCancel; //Need this type of array because of batch_cancel_boosts() from veBoost uint256 nbToCancel = 0; // Loop over the delegator current boosts to find potential cancelable ones for (uint256 i = 0; i < vars.nbTokens;) { uint256 tokenId = delegationBoost.token_of_delegator_by_index( delegator, i ); if (delegationBoost.token_cancel_time(tokenId) <= block.timestamp && delegationBoost.token_cancel_time(tokenId) != 0) { int256 boost = delegationBoost.token_boost(tokenId); uint256 absolute_boost = boost >= 0 ? uint256(boost) : uint256(-boost); vars.potentialCancelableBalance += absolute_boost; toCancel[nbToCancel] = tokenId; nbToCancel++; } unchecked{ ++i; } } // If the current Boosts are more than the availableBalance => No balance available for a new Boost if (vars.availableBalance < (vars.delegatedBalance - vars.potentialCancelableBalance)) return false; // If canceling the tokens can free enough to delegate, // cancel the batch and return true if (amount <= (vars.availableBalance - (vars.delegatedBalance - vars.potentialCancelableBalance)) && nbToCancel > 0) { delegationBoost.batch_cancel_boosts(toCancel); return true; } return false; } function _cancelAllExpired(address delegator) internal { uint256 nbTokens = delegationBoost.total_minted(delegator); // Delegator does not have active Boosts currently if (nbTokens == 0) return; uint256[256] memory toCancel; uint256 nbToCancel = 0; uint256 currentTime = block.timestamp; // Loop over the delegator current boosts to find expired ones for (uint256 i = 0; i < nbTokens;) { uint256 tokenId = delegationBoost.token_of_delegator_by_index( delegator, i ); uint256 cancelTime = delegationBoost.token_cancel_time(tokenId); if (cancelTime <= currentTime && cancelTime != 0) { toCancel[nbToCancel] = tokenId; nbToCancel++; } unchecked{ ++i; } } // If Boost were found, cancel the batch if (nbToCancel > 0) { delegationBoost.batch_cancel_boosts(toCancel); } } function _claim(address user, uint256 amount) internal returns(bool) { if(_claimBlocked) revert Errors.ClaimBlocked(); if(amount > feeToken.balanceOf(address(this))) revert Errors.InsufficientCash(); if(amount == 0) return true; // nothing to claim, but used in claimAndCancel() // If fees to be claimed, update the mapping, and send the amount unchecked{ // Should not underflow, since the amount was either checked in the claim() method, or set as earnedFees[user] earnedFees[user] -= amount; } feeToken.safeTransfer(user, amount); emit Claim(user, amount); return true; } function _getBoostRewardAmount(uint256 boostId) internal view returns(uint256) { PurchasedBoost memory boost = purchasedBoosts[boostId]; if(boost.buyer == address(0)) revert Errors.BoostRewardsNull(); if(boost.claimed) return 0; if(currentPeriod() <= boost.endTimestamp) return 0; if(nextUpdatePeriod <= boost.endTimestamp) revert Errors.RewardsNotUpdated(); uint256 boostAmount = boost.amount; uint256 boostDuration = boost.endTimestamp - boost.startTimestamp; uint256 boostDecreaseStep = boostAmount / (boostDuration); uint256 boostPeriodDecrease = boostDecreaseStep * WEEK; uint256 rewardAmount; uint256 indexDiff; uint256 periodBoostAmount; uint256 endPeriodBoostAmount; uint256 period = (boost.startTimestamp / WEEK) * WEEK; uint256 nextPeriod = period + WEEK; // 1st period (if incomplete) if(boost.startTimestamp > period) { indexDiff = periodRewardIndex[nextPeriod] - boost.startIndex; uint256 timeDiff = nextPeriod - boost.startTimestamp; endPeriodBoostAmount = boostAmount - (boostDecreaseStep * timeDiff); periodBoostAmount = endPeriodBoostAmount + ((boostDecreaseStep + (boostDecreaseStep * timeDiff)) / 2); rewardAmount += (indexDiff * periodBoostAmount) / UNIT; boostAmount = endPeriodBoostAmount; period = nextPeriod; nextPeriod = period + WEEK; } uint256 nbPeriods = boostDuration / WEEK; // all complete periods for(uint256 j; j < nbPeriods;){ indexDiff = periodRewardIndex[nextPeriod] - periodRewardIndex[period]; endPeriodBoostAmount = boostAmount - (boostDecreaseStep * WEEK); periodBoostAmount = endPeriodBoostAmount + ((boostDecreaseStep + boostPeriodDecrease) / 2); rewardAmount += (indexDiff * periodBoostAmount) / UNIT; boostAmount = endPeriodBoostAmount; period = nextPeriod; nextPeriod = period + WEEK; unchecked{ ++j; } } return rewardAmount; } function _claimBoostRewards(uint256 boostId) internal returns(bool) { if(nextUpdatePeriod == 0) revert Errors.RewardsNotStarted(); PurchasedBoost storage boost = purchasedBoosts[boostId]; if(boost.buyer == address(0)) revert Errors.BoostRewardsNull(); if(msg.sender != boost.buyer) revert Errors.NotBoostBuyer(); if(boost.claimed) revert Errors.AlreadyClaimed(); if(currentPeriod() <= boost.endTimestamp) revert Errors.CannotClaim(); uint256 rewardAmount = _getBoostRewardAmount(boostId); if(rewardAmount == 0) return true; // nothing to claim, return if(rewardAmount > rewardToken.balanceOf(address(this))) revert Errors.InsufficientRewardCash(); boost.claimed = true; rewardToken.safeTransfer(msg.sender, rewardAmount); emit ClaimReward(boostId, msg.sender, rewardAmount); return true; } function _getTokenDelegator(uint256 tokenId) internal pure returns (address) { //Extract the address from the token id : See VotingEscrowDelegation.vy for the logic return address(uint160(tokenId >> 96)); } // Manager methods: function setAdvisedPrice(uint256 newPrice) external { if(!approvedManagers[msg.sender]) revert Errors.CallerNotManager(); if(newPrice == 0) revert Errors.NullValue(); advisedPrice = newPrice; emit NewAdvisedPrice(newPrice); } // Admin Functions : function startRewardDistribution( address _rewardToken, uint256 _baseWeeklyDropPerVote, uint256 _minWeeklyDropPerVote, uint256 _targetPurchaseAmount ) external onlyOwner { if(_rewardToken == address(0)) revert Errors.ZeroAddress(); if(_baseWeeklyDropPerVote == 0 || _minWeeklyDropPerVote == 0 || _targetPurchaseAmount == 0) revert Errors.NullValue(); if(_baseWeeklyDropPerVote < _minWeeklyDropPerVote) revert Errors.BaseDropTooLow(); if(nextUpdatePeriod != 0) revert Errors.RewardsAlreadyStarted(); rewardToken = IERC20(_rewardToken); baseWeeklyDropPerVote = _baseWeeklyDropPerVote; minWeeklyDropPerVote = _minWeeklyDropPerVote; targetPurchaseAmount = _targetPurchaseAmount; // Initial period and initial index uint256 startPeriod = ((block.timestamp + WEEK) / WEEK) * WEEK; periodRewardIndex[startPeriod] = 0; nextUpdatePeriod = startPeriod; //Initial drop periodDropPerVote[startPeriod] = baseWeeklyDropPerVote; } function setBaseWeeklyDropPerVote(uint256 newBaseWeeklyDropPerVote) external onlyOwner { if(newBaseWeeklyDropPerVote == 0) revert Errors.NullValue(); if(newBaseWeeklyDropPerVote < minWeeklyDropPerVote) revert Errors.BaseDropTooLow(); baseWeeklyDropPerVote = newBaseWeeklyDropPerVote; } function setMinWeeklyDropPerVote(uint256 newMinWeeklyDropPerVote) external onlyOwner { if(newMinWeeklyDropPerVote == 0) revert Errors.NullValue(); if(baseWeeklyDropPerVote < newMinWeeklyDropPerVote) revert Errors.MinDropTooHigh(); minWeeklyDropPerVote = newMinWeeklyDropPerVote; } function setTargetPurchaseAmount(uint256 newTargetPurchaseAmount) external onlyOwner { if(newTargetPurchaseAmount == 0) revert Errors.NullValue(); targetPurchaseAmount = newTargetPurchaseAmount; } /** * @notice Updates the minimum percent required to buy a Boost * @param newMinPercRequired New minimum percent required to buy a Boost (in BPS) */ function setMinPercRequired(uint256 newMinPercRequired) external onlyOwner { if(newMinPercRequired == 0 || newMinPercRequired > 10000) revert Errors.InvalidValue(); minPercRequired = newMinPercRequired; } /** * @notice Updates the minimum delegation time * @param newMinDelegationTime New minimum deelgation time (in seconds) */ function setMinDelegationTime(uint256 newMinDelegationTime) external onlyOwner { if(newMinDelegationTime == 0) revert Errors.NullValue(); minDelegationTime = newMinDelegationTime; } /** * @notice Updates the ratio of Fees set for the Reserve * @param newFeeReserveRatio New ratio (in BPS) */ function setFeeReserveRatio(uint256 newFeeReserveRatio) external onlyOwner { if(newFeeReserveRatio > 5000) revert Errors.InvalidValue(); feeReserveRatio = newFeeReserveRatio; } /** * @notice Updates the Delegation Boost (veBoost) * @param newDelegationBoost New veBoost contract address */ function setDelegationBoost(address newDelegationBoost) external onlyOwner { delegationBoost = IVotingEscrowDelegation(newDelegationBoost); } /** * @notice Updates the Reserve Manager * @param newReserveManager New Reserve Manager address */ function setReserveManager(address newReserveManager) external onlyOwner { reserveManager = newReserveManager; } /** * @notice Approves a new address as manager * @dev Approves a new address as manager * @param newManager Address to add */ function approveManager(address newManager) external onlyOwner { if(newManager == address(0)) revert Errors.ZeroAddress(); approvedManagers[newManager] = true; } /** * @notice Removes an address from the managers * @dev Removes an address from the managers * @param manager Address to remove */ function removeManager(address manager) external onlyOwner { if(manager == address(0)) revert Errors.ZeroAddress(); approvedManagers[manager] = false; } /** * @notice Pauses the contract */ function pause() external onlyOwner { _pause(); } /** * @notice Unpauses the contract */ function unpause() external onlyOwner { _unpause(); } /** * @notice Block user fee claims */ function blockClaim() external onlyOwner { if(_claimBlocked) revert Errors.ClaimBlocked(); _claimBlocked = true; } /** * @notice Unblock user fee claims */ function unblockClaim() external onlyOwner { if(!_claimBlocked) revert Errors.ClaimNotBlocked(); _claimBlocked = false; } /** * @dev Withdraw either a lost ERC20 token sent to the contract (expect the feeToken) * @param token ERC20 token to withdraw * @param amount Amount to transfer (in wei) */ function withdrawERC20(address token, uint256 amount) external onlyOwner returns(bool) { if(!_claimBlocked && token == address(feeToken)) revert Errors.CannotWithdrawFeeToken(); //We want to be able to recover the fees if there is an issue IERC20(token).safeTransfer(owner(), amount); return true; } function depositToReserve(address from, uint256 amount) external onlyAllowed returns(bool) { reserveAmount = reserveAmount + amount; feeToken.safeTransferFrom(from, address(this), amount); return true; } function withdrawFromReserve(uint256 amount) external onlyAllowed returns(bool) { if(amount > reserveAmount) revert Errors.ReserveTooLow(); reserveAmount = reserveAmount - amount; feeToken.safeTransfer(reserveManager, amount); return true; } }
Block user fee claims/
function blockClaim() external onlyOwner { if(_claimBlocked) revert Errors.ClaimBlocked(); _claimBlocked = true; }
15,836,163
// File: contracts/tokens/ERC20.sol pragma solidity 0.5.14; contract ERC20 { function TOTALSUPPLY679() public view returns (uint256 supply); //inject NONSTANDARD NAMING function BALANCEOF603(address _owner) public view returns (uint256 balance); //inject NONSTANDARD NAMING function TRANSFER978(address _to, uint256 _value) public returns (bool success); //inject NONSTANDARD NAMING function TRANSFERFROM476(address _from, address _to, uint256 _value) public returns (bool success); //inject NONSTANDARD NAMING function APPROVE644(address _spender, uint256 _value) public returns (bool success); //inject NONSTANDARD NAMING function ALLOWANCE384(address _owner, address _spender) public view returns (uint256 remaining); //inject NONSTANDARD NAMING event TRANSFER760(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL643(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } // File: contracts/tokens/SafeMath.sol pragma solidity 0.5.14; library SafeMath { function MUL81(uint256 _a, uint256 _b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // 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; } function DIV451(uint256 _a, uint256 _b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(_b > 0); // Solidity only automatically asserts 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 SUB832(uint256 _a, uint256 _b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(_b <= _a); uint256 c = _a - _b; return c; } function ADD114(uint256 _a, uint256 _b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = _a + _b; require(c >= _a); return c; } function MOD487(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0); return a % b; } } // File: contracts/tokens/StandardToken.sol pragma solidity 0.5.14; contract StandardToken is ERC20 { using SafeMath for uint256; mapping(address => uint256) internal balances; mapping(address => mapping(address => uint256)) private allowed; uint256 internal totalSupply_; function TOTALSUPPLY679() public view returns (uint256) { //inject NONSTANDARD NAMING return totalSupply_; } function BALANCEOF603(address _owner) public view returns (uint256) { //inject NONSTANDARD NAMING return balances[_owner]; } function ALLOWANCE384(address _owner, address _spender) public view returns (uint256) { //inject NONSTANDARD NAMING return allowed[_owner][_spender]; } function TRANSFER978(address _to, uint256 _value) public returns (bool) { //inject NONSTANDARD NAMING require(_value <= balances[msg.sender]); require(_to != address(0)); balances[msg.sender] = balances[msg.sender].SUB832(_value); balances[_to] = balances[_to].ADD114(_value); emit TRANSFER760(msg.sender, _to, _value); return true; } function APPROVE644(address _spender, uint256 _value) public returns (bool) { //inject NONSTANDARD NAMING allowed[msg.sender][_spender] = _value; emit APPROVAL643(msg.sender, _spender, _value); return true; } function TRANSFERFROM476(address _from, address _to, uint256 _value) public returns (bool) { //inject NONSTANDARD NAMING require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); require(_to != address(0)); balances[_from] = balances[_from].SUB832(_value); balances[_to] = balances[_to].ADD114(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].SUB832(_value); emit TRANSFER760(_from, _to, _value); return true; } function INCREASEAPPROVAL847(address _spender, uint256 _addedValue) public returns (bool) { //inject NONSTANDARD NAMING allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].ADD114(_addedValue)); emit APPROVAL643(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function DECREASEAPPROVAL982(address _spender, uint256 _subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue >= oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.SUB832(_subtractedValue); } emit APPROVAL643(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function _MINT883(address _account, uint256 _amount) internal { //inject NONSTANDARD NAMING require(_account != address(0)); totalSupply_ = totalSupply_.ADD114(_amount); balances[_account] = balances[_account].ADD114(_amount); emit TRANSFER760(address(0), _account, _amount); } function _BURN950(address _account, uint256 _amount) internal { //inject NONSTANDARD NAMING require(_account != address(0)); require(_amount <= balances[_account]); totalSupply_ = totalSupply_.SUB832(_amount); balances[_account] = balances[_account].SUB832(_amount); emit TRANSFER760(_account, address(0), _amount); } function _BURNFROM531(address _account, uint256 _amount) internal { //inject NONSTANDARD NAMING require(_amount <= allowed[_account][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[_account][msg.sender] = allowed[_account][msg.sender].SUB832(_amount); _BURN950(_account, _amount); } } // File: contracts/tokens/Ownable.sol pragma solidity 0.5.14; contract Ownable { address public owner; event OWNERSHIPRENOUNCED53(address indexed previousOwner); //inject NONSTANDARD NAMING event OWNERSHIPTRANSFERRED268( //inject NONSTANDARD NAMING address indexed previousOwner, address indexed newOwner ); constructor() public { owner = msg.sender; } modifier ONLYOWNER709() { //inject NONSTANDARD NAMING require(msg.sender == owner); _; } function RENOUNCEOWNERSHIP918() public ONLYOWNER709 { //inject NONSTANDARD NAMING emit OWNERSHIPRENOUNCED53(owner); owner = address(0); } function TRANSFEROWNERSHIP47(address _newOwner) public ONLYOWNER709 { //inject NONSTANDARD NAMING _TRANSFEROWNERSHIP390(_newOwner); } function _TRANSFEROWNERSHIP390(address _newOwner) internal { //inject NONSTANDARD NAMING require(_newOwner != address(0)); emit OWNERSHIPTRANSFERRED268(owner, _newOwner); owner = _newOwner; } } // File: contracts/tokens/BurnableToken.sol pragma solidity 0.5.14; contract BurnableToken is StandardToken { event BURN276(address indexed burner, uint256 value); //inject NONSTANDARD NAMING function BURN42(uint256 _value) public { //inject NONSTANDARD NAMING _BURN950(msg.sender, _value); } function BURNFROM69(address _from, uint256 _value) public { //inject NONSTANDARD NAMING _BURNFROM531(_from, _value); } function _BURN950(address _who, uint256 _value) internal { //inject NONSTANDARD NAMING super._BURN950(_who, _value); emit BURN276(_who, _value); } } // File: contracts/tokens/SportValueCoin.sol pragma solidity 0.5.14; contract SportValueCoin is BurnableToken { // meta data string public constant symbol15 = "SVC"; //inject NONSTANDARD NAMING string public version = '1.0'; string public constant name455 = "Sport Value Coin"; //inject NONSTANDARD NAMING uint256 public constant decimals291 = 18; //inject NONSTANDARD NAMING uint256 public constant initial_supply658 = 100 * (10 ** 6) * 10 ** decimals291; // 100 millions //inject NONSTANDARD NAMING constructor() public { _MINT883(msg.sender, initial_supply658); } }
inject NONSTANDARD NAMING
function BALANCEOF603(address _owner) public view returns (uint256 balance);
12,906,817
./partial_match/1/0x21b346622e607fcC936a320D3ab8224fb36B3C0c/sources/contracts/vault/VaultFactory.sol
Hook that is called before any token transfer. This notifies the vault contract about the ownership transfer. Does not let tokens with withdraw enabled be transferred, which ensures that items cannot be withdrawn in a frontrunning attack before loan origination. from The previous owner of the token. to The owner of the token after transfer. tokenId The token ID./
function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override(ERC721Upgradeable, ERC721EnumerableUpgradeable) { IAssetVault vault = IAssetVault(address(uint160(tokenId))); if (vault.withdrawEnabled()) revert VF_NoTransferWithdrawEnabled(tokenId); super._beforeTokenTransfer(from, to, tokenId); }
9,283,484
// 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; } } // SPDX-License-Identifier: MIT 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, 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.0 <0.8.0; /** * @title SignedSafeMath * @dev Signed math operations with safety checks that revert on error. */ library SignedSafeMath { int256 constant private _INT256_MIN = -2**255; /** * @dev Returns the multiplication of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot 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-contracts/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow"); int256 c = a * b; require(c / a == b, "SignedSafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two signed 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(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow"); int256 c = a / b; return c; } /** * @dev Returns the subtraction of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } /** * @dev Returns the addition of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../GSN/Context.sol"; 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 {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 { using SafeMath for uint256; 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. */ constructor (string memory name_, string memory symbol_) public { _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 view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view 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); _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 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 { } } // SPDX-License-Identifier: MIT 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); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.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 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.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); } 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.6.0 <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 () internal { _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.6.0 <0.8.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such 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. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { require(value < 2**255, "SafeCast: value doesn't fit in an int256"); return int256(value); } } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; interface IController { function addSet(address _setToken) external; function feeRecipient() external view returns(address); function getModuleFee(address _module, uint256 _feeType) external view returns(uint256); function isModule(address _module) external view returns(bool); function isSet(address _setToken) external view returns(bool); function isSystemContract(address _contractAddress) external view returns (bool); function resourceId(uint256 _id) external view returns(address); } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; interface IIntegrationRegistry { function addIntegration(address _module, string memory _id, address _wrapper) external; function getIntegrationAdapter(address _module, string memory _id) external view returns(address); function getIntegrationAdapterWithHash(address _module, bytes32 _id) external view returns(address); function isValidIntegration(address _module, string memory _id) external view returns(bool); } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; /** * @title IModule * @author Set Protocol * * Interface for interacting with Modules. */ interface IModule { /** * Called by a SetToken to notify that this module was removed from the Set token. Any logic can be included * in case checks need to be made or state needs to be cleared. */ function removeModule() external; } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; import { ISetToken } from "./ISetToken.sol"; interface INAVIssuanceHook { function invokePreIssueHook( ISetToken _setToken, address _reserveAsset, uint256 _reserveAssetQuantity, address _sender, address _to ) external; function invokePreRedeemHook( ISetToken _setToken, uint256 _redeemQuantity, address _sender, address _to ) external; } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; /** * @title IPriceOracle * @author Set Protocol * * Interface for interacting with PriceOracle */ interface IPriceOracle { /* ============ Functions ============ */ function getPrice(address _assetOne, address _assetTwo) external view returns (uint256); function masterQuoteAsset() external view returns (address); } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; pragma experimental "ABIEncoderV2"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title ISetToken * @author Set Protocol * * Interface for operating with SetTokens. */ interface ISetToken is IERC20 { /* ============ Enums ============ */ enum ModuleState { NONE, PENDING, INITIALIZED } /* ============ Structs ============ */ /** * The base definition of a SetToken Position * * @param component Address of token in the Position * @param module If not in default state, the address of associated module * @param unit Each unit is the # of components per 10^18 of a SetToken * @param positionState Position ENUM. Default is 0; External is 1 * @param data Arbitrary data */ struct Position { address component; address module; int256 unit; uint8 positionState; bytes data; } /** * A struct that stores a component's cash position details and external positions * This data structure allows O(1) access to a component's cash position units and * virtual units. * * @param virtualUnit Virtual value of a component's DEFAULT position. Stored as virtual for efficiency * updating all units at once via the position multiplier. Virtual units are achieved * by dividing a "real" value by the "positionMultiplier" * @param componentIndex * @param externalPositionModules List of external modules attached to each external position. Each module * maps to an external position * @param externalPositions Mapping of module => ExternalPosition struct for a given component */ struct ComponentPosition { int256 virtualUnit; address[] externalPositionModules; mapping(address => ExternalPosition) externalPositions; } /** * A struct that stores a component's external position details including virtual unit and any * auxiliary data. * * @param virtualUnit Virtual value of a component's EXTERNAL position. * @param data Arbitrary data */ struct ExternalPosition { int256 virtualUnit; bytes data; } /* ============ Functions ============ */ function addComponent(address _component) external; function removeComponent(address _component) external; function editDefaultPositionUnit(address _component, int256 _realUnit) external; function addExternalPositionModule(address _component, address _positionModule) external; function removeExternalPositionModule(address _component, address _positionModule) external; function editExternalPositionUnit(address _component, address _positionModule, int256 _realUnit) external; function editExternalPositionData(address _component, address _positionModule, bytes calldata _data) external; function invoke(address _target, uint256 _value, bytes calldata _data) external returns(bytes memory); function editPositionMultiplier(int256 _newMultiplier) external; function mint(address _account, uint256 _quantity) external; function burn(address _account, uint256 _quantity) external; function lock() external; function unlock() external; function addModule(address _module) external; function removeModule(address _module) external; function initializeModule() external; function setManager(address _manager) external; function manager() external view returns (address); function moduleStates(address _module) external view returns (ModuleState); function getModules() external view returns (address[] memory); function getDefaultPositionRealUnit(address _component) external view returns(int256); function getExternalPositionRealUnit(address _component, address _positionModule) external view returns(int256); function getComponents() external view returns(address[] memory); function getExternalPositionModules(address _component) external view returns(address[] memory); function getExternalPositionData(address _component, address _positionModule) external view returns(bytes memory); function isExternalPositionModule(address _component, address _module) external view returns(bool); function isComponent(address _component) external view returns(bool); function positionMultiplier() external view returns (int256); function getPositions() external view returns (Position[] memory); function getTotalComponentRealUnits(address _component) external view returns(int256); function isInitializedModule(address _module) external view returns(bool); function isPendingModule(address _module) external view returns(bool); function isLocked() external view returns (bool); } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; import { ISetToken } from "../interfaces/ISetToken.sol"; interface ISetValuer { function calculateSetTokenValuation(ISetToken _setToken, address _quoteAsset) external view returns (uint256); } /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.6.10; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title IWETH * @author Set Protocol * * Interface for Wrapped Ether. This interface allows for interaction for wrapped ether's deposit and withdrawal * functionality. */ interface IWETH is IERC20{ function deposit() external payable; function withdraw( uint256 wad ) external; } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; /** * @title AddressArrayUtils * @author Set Protocol * * Utility functions to handle Address Arrays */ library AddressArrayUtils { /** * Finds the index of the first occurrence of the given element. * @param A The input array to search * @param a The value to find * @return Returns (index and isIn) for the first occurrence starting from index 0 */ function indexOf(address[] memory A, address a) internal pure returns (uint256, bool) { uint256 length = A.length; for (uint256 i = 0; i < length; i++) { if (A[i] == a) { return (i, true); } } return (uint256(-1), false); } /** * Returns true if the value is present in the list. Uses indexOf internally. * @param A The input array to search * @param a The value to find * @return Returns isIn for the first occurrence starting from index 0 */ function contains(address[] memory A, address a) internal pure returns (bool) { (, bool isIn) = indexOf(A, a); return isIn; } /** * Returns true if there are 2 elements that are the same in an array * @param A The input array to search * @return Returns boolean for the first occurrence of a duplicate */ function hasDuplicate(address[] memory A) internal pure returns(bool) { require(A.length > 0, "A is empty"); for (uint256 i = 0; i < A.length - 1; i++) { address current = A[i]; for (uint256 j = i + 1; j < A.length; j++) { if (current == A[j]) { return true; } } } return false; } /** * @param A The input array to search * @param a The address to remove * @return Returns the array with the object removed. */ function remove(address[] memory A, address a) internal pure returns (address[] memory) { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert("Address not in array."); } else { (address[] memory _A,) = pop(A, index); return _A; } } /** * Removes specified index from array * @param A The input array to search * @param index The index to remove * @return Returns the new array and the removed entry */ function pop(address[] memory A, uint256 index) internal pure returns (address[] memory, address) { uint256 length = A.length; require(index < A.length, "Index must be < A length"); address[] memory newAddresses = new address[](length - 1); for (uint256 i = 0; i < index; i++) { newAddresses[i] = A[i]; } for (uint256 j = index + 1; j < length; j++) { newAddresses[j - 1] = A[j]; } return (newAddresses, A[index]); } /** * Returns the combination of the two arrays * @param A The first array * @param B The second array * @return Returns A extended by B */ function extend(address[] memory A, address[] memory B) internal pure returns (address[] memory) { uint256 aLength = A.length; uint256 bLength = B.length; address[] memory newAddresses = new address[](aLength + bLength); for (uint256 i = 0; i < aLength; i++) { newAddresses[i] = A[i]; } for (uint256 j = 0; j < bLength; j++) { newAddresses[aLength + j] = B[j]; } return newAddresses; } } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; /** * @title ExplicitERC20 * @author Set Protocol * * Utility functions for ERC20 transfers that require the explicit amount to be transferred. */ library ExplicitERC20 { using SafeMath for uint256; /** * When given allowance, transfers a token from the "_from" to the "_to" of quantity "_quantity". * Ensures that the recipient has received the correct quantity (ie no fees taken on transfer) * * @param _token ERC20 token to approve * @param _from The account to transfer tokens from * @param _to The account to transfer tokens to * @param _quantity The quantity to transfer */ function transferFrom( IERC20 _token, address _from, address _to, uint256 _quantity ) internal { // Call specified ERC20 contract to transfer tokens (via proxy). if (_quantity > 0) { uint256 existingBalance = _token.balanceOf(_to); SafeERC20.safeTransferFrom( _token, _from, _to, _quantity ); uint256 newBalance = _token.balanceOf(_to); // Verify transfer quantity is reflected in balance require( newBalance == existingBalance.add(_quantity), "Invalid post transfer balance" ); } } } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol"; /** * @title PreciseUnitMath * @author Set Protocol * * Arithmetic for fixed-point numbers with 18 decimals of precision. Some functions taken from * dYdX's BaseMath library. * * CHANGELOG: * - 9/21/20: Added safePower function */ library PreciseUnitMath { using SafeMath for uint256; using SignedSafeMath for int256; // The number One in precise units. uint256 constant internal PRECISE_UNIT = 10 ** 18; int256 constant internal PRECISE_UNIT_INT = 10 ** 18; // Max unsigned integer value uint256 constant internal MAX_UINT_256 = type(uint256).max; // Max and min signed integer value int256 constant internal MAX_INT_256 = type(int256).max; int256 constant internal MIN_INT_256 = type(int256).min; /** * @dev Getter function since constants can't be read directly from libraries. */ function preciseUnit() internal pure returns (uint256) { return PRECISE_UNIT; } /** * @dev Getter function since constants can't be read directly from libraries. */ function preciseUnitInt() internal pure returns (int256) { return PRECISE_UNIT_INT; } /** * @dev Getter function since constants can't be read directly from libraries. */ function maxUint256() internal pure returns (uint256) { return MAX_UINT_256; } /** * @dev Getter function since constants can't be read directly from libraries. */ function maxInt256() internal pure returns (int256) { return MAX_INT_256; } /** * @dev Getter function since constants can't be read directly from libraries. */ function minInt256() internal pure returns (int256) { return MIN_INT_256; } /** * @dev Multiplies value a by value b (result is rounded down). It's assumed that the value b is the significand * of a number with 18 decimals precision. */ function preciseMul(uint256 a, uint256 b) internal pure returns (uint256) { return a.mul(b).div(PRECISE_UNIT); } /** * @dev Multiplies value a by value b (result is rounded towards zero). It's assumed that the value b is the * significand of a number with 18 decimals precision. */ function preciseMul(int256 a, int256 b) internal pure returns (int256) { return a.mul(b).div(PRECISE_UNIT_INT); } /** * @dev Multiplies value a by value b (result is rounded up). It's assumed that the value b is the significand * of a number with 18 decimals precision. */ function preciseMulCeil(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } return a.mul(b).sub(1).div(PRECISE_UNIT).add(1); } /** * @dev Divides value a by value b (result is rounded down). */ function preciseDiv(uint256 a, uint256 b) internal pure returns (uint256) { return a.mul(PRECISE_UNIT).div(b); } /** * @dev Divides value a by value b (result is rounded towards 0). */ function preciseDiv(int256 a, int256 b) internal pure returns (int256) { return a.mul(PRECISE_UNIT_INT).div(b); } /** * @dev Divides value a by value b (result is rounded up or away from 0). */ function preciseDivCeil(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "Cant divide by 0"); return a > 0 ? a.mul(PRECISE_UNIT).sub(1).div(b).add(1) : 0; } /** * @dev Divides value a by value b (result is rounded down - positive numbers toward 0 and negative away from 0). */ function divDown(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "Cant divide by 0"); require(a != MIN_INT_256 || b != -1, "Invalid input"); int256 result = a.div(b); if (a ^ b < 0 && a % b != 0) { result -= 1; } return result; } /** * @dev Multiplies value a by value b where rounding is towards the lesser number. * (positive values are rounded towards zero and negative values are rounded away from 0). */ function conservativePreciseMul(int256 a, int256 b) internal pure returns (int256) { return divDown(a.mul(b), PRECISE_UNIT_INT); } /** * @dev Divides value a by value b where rounding is towards the lesser number. * (positive values are rounded towards zero and negative values are rounded away from 0). */ function conservativePreciseDiv(int256 a, int256 b) internal pure returns (int256) { return divDown(a.mul(PRECISE_UNIT_INT), b); } /** * @dev Performs the power on a specified value, reverts on overflow. */ function safePower( uint256 a, uint256 pow ) internal pure returns (uint256) { require(a > 0, "Value must be positive"); uint256 result = 1; for (uint256 i = 0; i < pow; i++){ uint256 previousResult = result; // Using safemath multiplication prevents overflows result = previousResult.mul(a); } return result; } } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { ISetToken } from "../../interfaces/ISetToken.sol"; /** * @title Invoke * @author Set Protocol * * A collection of common utility functions for interacting with the SetToken's invoke function */ library Invoke { using SafeMath for uint256; /* ============ Internal ============ */ /** * Instructs the SetToken to set approvals of the ERC20 token to a spender. * * @param _setToken SetToken instance to invoke * @param _token ERC20 token to approve * @param _spender The account allowed to spend the SetToken's balance * @param _quantity The quantity of allowance to allow */ function invokeApprove( ISetToken _setToken, address _token, address _spender, uint256 _quantity ) internal { bytes memory callData = abi.encodeWithSignature("approve(address,uint256)", _spender, _quantity); _setToken.invoke(_token, 0, callData); } /** * Instructs the SetToken to transfer the ERC20 token to a recipient. * * @param _setToken SetToken instance to invoke * @param _token ERC20 token to transfer * @param _to The recipient account * @param _quantity The quantity to transfer */ function invokeTransfer( ISetToken _setToken, address _token, address _to, uint256 _quantity ) internal { if (_quantity > 0) { bytes memory callData = abi.encodeWithSignature("transfer(address,uint256)", _to, _quantity); _setToken.invoke(_token, 0, callData); } } /** * Instructs the SetToken to transfer the ERC20 token to a recipient. * The new SetToken balance must equal the existing balance less the quantity transferred * * @param _setToken SetToken instance to invoke * @param _token ERC20 token to transfer * @param _to The recipient account * @param _quantity The quantity to transfer */ function strictInvokeTransfer( ISetToken _setToken, address _token, address _to, uint256 _quantity ) internal { if (_quantity > 0) { // Retrieve current balance of token for the SetToken uint256 existingBalance = IERC20(_token).balanceOf(address(_setToken)); Invoke.invokeTransfer(_setToken, _token, _to, _quantity); // Get new balance of transferred token for SetToken uint256 newBalance = IERC20(_token).balanceOf(address(_setToken)); // Verify only the transfer quantity is subtracted require( newBalance == existingBalance.sub(_quantity), "Invalid post transfer balance" ); } } /** * Instructs the SetToken to unwrap the passed quantity of WETH * * @param _setToken SetToken instance to invoke * @param _weth WETH address * @param _quantity The quantity to unwrap */ function invokeUnwrapWETH(ISetToken _setToken, address _weth, uint256 _quantity) internal { bytes memory callData = abi.encodeWithSignature("withdraw(uint256)", _quantity); _setToken.invoke(_weth, 0, callData); } /** * Instructs the SetToken to wrap the passed quantity of ETH * * @param _setToken SetToken instance to invoke * @param _weth WETH address * @param _quantity The quantity to unwrap */ function invokeWrapWETH(ISetToken _setToken, address _weth, uint256 _quantity) internal { bytes memory callData = abi.encodeWithSignature("deposit()"); _setToken.invoke(_weth, _quantity, callData); } } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { ExplicitERC20 } from "../../lib/ExplicitERC20.sol"; import { IController } from "../../interfaces/IController.sol"; import { IModule } from "../../interfaces/IModule.sol"; import { ISetToken } from "../../interfaces/ISetToken.sol"; import { Invoke } from "./Invoke.sol"; import { PreciseUnitMath } from "../../lib/PreciseUnitMath.sol"; import { ResourceIdentifier } from "./ResourceIdentifier.sol"; /** * @title ModuleBase * @author Set Protocol * * Abstract class that houses common Module-related state and functions. */ abstract contract ModuleBase is IModule { using PreciseUnitMath for uint256; using Invoke for ISetToken; using ResourceIdentifier for IController; /* ============ State Variables ============ */ // Address of the controller IController public controller; /* ============ Modifiers ============ */ modifier onlyManagerAndValidSet(ISetToken _setToken) { require(isSetManager(_setToken, msg.sender), "Must be the SetToken manager"); require(isSetValidAndInitialized(_setToken), "Must be a valid and initialized SetToken"); _; } modifier onlySetManager(ISetToken _setToken, address _caller) { require(isSetManager(_setToken, _caller), "Must be the SetToken manager"); _; } modifier onlyValidAndInitializedSet(ISetToken _setToken) { require(isSetValidAndInitialized(_setToken), "Must be a valid and initialized SetToken"); _; } /** * Throws if the sender is not a SetToken's module or module not enabled */ modifier onlyModule(ISetToken _setToken) { require( _setToken.moduleStates(msg.sender) == ISetToken.ModuleState.INITIALIZED, "Only the module can call" ); require( controller.isModule(msg.sender), "Module must be enabled on controller" ); _; } /** * Utilized during module initializations to check that the module is in pending state * and that the SetToken is valid */ modifier onlyValidAndPendingSet(ISetToken _setToken) { require(controller.isSet(address(_setToken)), "Must be controller-enabled SetToken"); require(isSetPendingInitialization(_setToken), "Must be pending initialization"); _; } /* ============ Constructor ============ */ /** * Set state variables and map asset pairs to their oracles * * @param _controller Address of controller contract */ constructor(IController _controller) public { controller = _controller; } /* ============ Internal Functions ============ */ /** * Transfers tokens from an address (that has set allowance on the module). * * @param _token The address of the ERC20 token * @param _from The address to transfer from * @param _to The address to transfer to * @param _quantity The number of tokens to transfer */ function transferFrom(IERC20 _token, address _from, address _to, uint256 _quantity) internal { ExplicitERC20.transferFrom(_token, _from, _to, _quantity); } /** * Gets the integration for the module with the passed in name. Validates that the address is not empty */ function getAndValidateAdapter(string memory _integrationName) internal view returns(address) { bytes32 integrationHash = getNameHash(_integrationName); return getAndValidateAdapterWithHash(integrationHash); } /** * Gets the integration for the module with the passed in hash. Validates that the address is not empty */ function getAndValidateAdapterWithHash(bytes32 _integrationHash) internal view returns(address) { address adapter = controller.getIntegrationRegistry().getIntegrationAdapterWithHash( address(this), _integrationHash ); require(adapter != address(0), "Must be valid adapter"); return adapter; } /** * Gets the total fee for this module of the passed in index (fee % * quantity) */ function getModuleFee(uint256 _feeIndex, uint256 _quantity) internal view returns(uint256) { uint256 feePercentage = controller.getModuleFee(address(this), _feeIndex); return _quantity.preciseMul(feePercentage); } /** * Pays the _feeQuantity from the _setToken denominated in _token to the protocol fee recipient */ function payProtocolFeeFromSetToken(ISetToken _setToken, address _token, uint256 _feeQuantity) internal { if (_feeQuantity > 0) { _setToken.strictInvokeTransfer(_token, controller.feeRecipient(), _feeQuantity); } } /** * Returns true if the module is in process of initialization on the SetToken */ function isSetPendingInitialization(ISetToken _setToken) internal view returns(bool) { return _setToken.isPendingModule(address(this)); } /** * Returns true if the address is the SetToken's manager */ function isSetManager(ISetToken _setToken, address _toCheck) internal view returns(bool) { return _setToken.manager() == _toCheck; } /** * Returns true if SetToken must be enabled on the controller * and module is registered on the SetToken */ function isSetValidAndInitialized(ISetToken _setToken) internal view returns(bool) { return controller.isSet(address(_setToken)) && _setToken.isInitializedModule(address(this)); } /** * Hashes the string and returns a bytes32 value */ function getNameHash(string memory _name) internal pure returns(bytes32) { return keccak256(bytes(_name)); } } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; pragma experimental "ABIEncoderV2"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { SafeCast } from "@openzeppelin/contracts/utils/SafeCast.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol"; import { ISetToken } from "../../interfaces/ISetToken.sol"; import { PreciseUnitMath } from "../../lib/PreciseUnitMath.sol"; /** * @title Position * @author Set Protocol * * Collection of helper functions for handling and updating SetToken Positions * * CHANGELOG: * - Updated editExternalPosition to work when no external position is associated with module */ library Position { using SafeCast for uint256; using SafeMath for uint256; using SafeCast for int256; using SignedSafeMath for int256; using PreciseUnitMath for uint256; /* ============ Helper ============ */ /** * Returns whether the SetToken has a default position for a given component (if the real unit is > 0) */ function hasDefaultPosition(ISetToken _setToken, address _component) internal view returns(bool) { return _setToken.getDefaultPositionRealUnit(_component) > 0; } /** * Returns whether the SetToken has an external position for a given component (if # of position modules is > 0) */ function hasExternalPosition(ISetToken _setToken, address _component) internal view returns(bool) { return _setToken.getExternalPositionModules(_component).length > 0; } /** * Returns whether the SetToken component default position real unit is greater than or equal to units passed in. */ function hasSufficientDefaultUnits(ISetToken _setToken, address _component, uint256 _unit) internal view returns(bool) { return _setToken.getDefaultPositionRealUnit(_component) >= _unit.toInt256(); } /** * Returns whether the SetToken component external position is greater than or equal to the real units passed in. */ function hasSufficientExternalUnits( ISetToken _setToken, address _component, address _positionModule, uint256 _unit ) internal view returns(bool) { return _setToken.getExternalPositionRealUnit(_component, _positionModule) >= _unit.toInt256(); } /** * If the position does not exist, create a new Position and add to the SetToken. If it already exists, * then set the position units. If the new units is 0, remove the position. Handles adding/removing of * components where needed (in light of potential external positions). * * @param _setToken Address of SetToken being modified * @param _component Address of the component * @param _newUnit Quantity of Position units - must be >= 0 */ function editDefaultPosition(ISetToken _setToken, address _component, uint256 _newUnit) internal { bool isPositionFound = hasDefaultPosition(_setToken, _component); if (!isPositionFound && _newUnit > 0) { // If there is no Default Position and no External Modules, then component does not exist if (!hasExternalPosition(_setToken, _component)) { _setToken.addComponent(_component); } } else if (isPositionFound && _newUnit == 0) { // If there is a Default Position and no external positions, remove the component if (!hasExternalPosition(_setToken, _component)) { _setToken.removeComponent(_component); } } _setToken.editDefaultPositionUnit(_component, _newUnit.toInt256()); } /** * Update an external position and remove and external positions or components if necessary. The logic flows as follows: * 1) If component is not already added then add component and external position. * 2) If component is added but no existing external position using the passed module exists then add the external position. * 3) If the existing position is being added to then just update the unit and data * 4) If the position is being closed and no other external positions or default positions are associated with the component * then untrack the component and remove external position. * 5) If the position is being closed and other existing positions still exist for the component then just remove the * external position. * * @param _setToken SetToken being updated * @param _component Component position being updated * @param _module Module external position is associated with * @param _newUnit Position units of new external position * @param _data Arbitrary data associated with the position */ function editExternalPosition( ISetToken _setToken, address _component, address _module, int256 _newUnit, bytes memory _data ) internal { if (_newUnit != 0) { if (!_setToken.isComponent(_component)) { _setToken.addComponent(_component); _setToken.addExternalPositionModule(_component, _module); } else if (!_setToken.isExternalPositionModule(_component, _module)) { _setToken.addExternalPositionModule(_component, _module); } _setToken.editExternalPositionUnit(_component, _module, _newUnit); _setToken.editExternalPositionData(_component, _module, _data); } else { require(_data.length == 0, "Passed data must be null"); // If no default or external position remaining then remove component from components array if (_setToken.getExternalPositionRealUnit(_component, _module) != 0) { address[] memory positionModules = _setToken.getExternalPositionModules(_component); if (_setToken.getDefaultPositionRealUnit(_component) == 0 && positionModules.length == 1) { require(positionModules[0] == _module, "External positions must be 0 to remove component"); _setToken.removeComponent(_component); } _setToken.removeExternalPositionModule(_component, _module); } } } /** * Get total notional amount of Default position * * @param _setTokenSupply Supply of SetToken in precise units (10^18) * @param _positionUnit Quantity of Position units * * @return Total notional amount of units */ function getDefaultTotalNotional(uint256 _setTokenSupply, uint256 _positionUnit) internal pure returns (uint256) { return _setTokenSupply.preciseMul(_positionUnit); } /** * Get position unit from total notional amount * * @param _setTokenSupply Supply of SetToken in precise units (10^18) * @param _totalNotional Total notional amount of component prior to * @return Default position unit */ function getDefaultPositionUnit(uint256 _setTokenSupply, uint256 _totalNotional) internal pure returns (uint256) { return _totalNotional.preciseDiv(_setTokenSupply); } /** * Get the total tracked balance - total supply * position unit * * @param _setToken Address of the SetToken * @param _component Address of the component * @return Notional tracked balance */ function getDefaultTrackedBalance(ISetToken _setToken, address _component) internal view returns(uint256) { int256 positionUnit = _setToken.getDefaultPositionRealUnit(_component); return _setToken.totalSupply().preciseMul(positionUnit.toUint256()); } /** * Calculates the new default position unit and performs the edit with the new unit * * @param _setToken Address of the SetToken * @param _component Address of the component * @param _setTotalSupply Current SetToken supply * @param _componentPreviousBalance Pre-action component balance * @return Current component balance * @return Previous position unit * @return New position unit */ function calculateAndEditDefaultPosition( ISetToken _setToken, address _component, uint256 _setTotalSupply, uint256 _componentPreviousBalance ) internal returns(uint256, uint256, uint256) { uint256 currentBalance = IERC20(_component).balanceOf(address(_setToken)); uint256 positionUnit = _setToken.getDefaultPositionRealUnit(_component).toUint256(); uint256 newTokenUnit; if (currentBalance > 0) { newTokenUnit = calculateDefaultEditPositionUnit( _setTotalSupply, _componentPreviousBalance, currentBalance, positionUnit ); } else { newTokenUnit = 0; } editDefaultPosition(_setToken, _component, newTokenUnit); return (currentBalance, positionUnit, newTokenUnit); } /** * Calculate the new position unit given total notional values pre and post executing an action that changes SetToken state * The intention is to make updates to the units without accidentally picking up airdropped assets as well. * * @param _setTokenSupply Supply of SetToken in precise units (10^18) * @param _preTotalNotional Total notional amount of component prior to executing action * @param _postTotalNotional Total notional amount of component after the executing action * @param _prePositionUnit Position unit of SetToken prior to executing action * @return New position unit */ function calculateDefaultEditPositionUnit( uint256 _setTokenSupply, uint256 _preTotalNotional, uint256 _postTotalNotional, uint256 _prePositionUnit ) internal pure returns (uint256) { // If pre action total notional amount is greater then subtract post action total notional and calculate new position units uint256 airdroppedAmount = _preTotalNotional.sub(_prePositionUnit.preciseMul(_setTokenSupply)); return _postTotalNotional.sub(airdroppedAmount).preciseDiv(_setTokenSupply); } } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; import { IController } from "../../interfaces/IController.sol"; import { IIntegrationRegistry } from "../../interfaces/IIntegrationRegistry.sol"; import { IPriceOracle } from "../../interfaces/IPriceOracle.sol"; import { ISetValuer } from "../../interfaces/ISetValuer.sol"; /** * @title ResourceIdentifier * @author Set Protocol * * A collection of utility functions to fetch information related to Resource contracts in the system */ library ResourceIdentifier { // IntegrationRegistry will always be resource ID 0 in the system uint256 constant internal INTEGRATION_REGISTRY_RESOURCE_ID = 0; // PriceOracle will always be resource ID 1 in the system uint256 constant internal PRICE_ORACLE_RESOURCE_ID = 1; // SetValuer resource will always be resource ID 2 in the system uint256 constant internal SET_VALUER_RESOURCE_ID = 2; /* ============ Internal ============ */ /** * Gets the instance of integration registry stored on Controller. Note: IntegrationRegistry is stored as index 0 on * the Controller */ function getIntegrationRegistry(IController _controller) internal view returns (IIntegrationRegistry) { return IIntegrationRegistry(_controller.resourceId(INTEGRATION_REGISTRY_RESOURCE_ID)); } /** * Gets instance of price oracle on Controller. Note: PriceOracle is stored as index 1 on the Controller */ function getPriceOracle(IController _controller) internal view returns (IPriceOracle) { return IPriceOracle(_controller.resourceId(PRICE_ORACLE_RESOURCE_ID)); } /** * Gets the instance of Set valuer on Controller. Note: SetValuer is stored as index 2 on the Controller */ function getSetValuer(IController _controller) internal view returns (ISetValuer) { return ISetValuer(_controller.resourceId(SET_VALUER_RESOURCE_ID)); } } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; pragma experimental "ABIEncoderV2"; import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import { SafeCast } from "@openzeppelin/contracts/utils/SafeCast.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol"; import { AddressArrayUtils } from "../../lib/AddressArrayUtils.sol"; import { IController } from "../../interfaces/IController.sol"; import { INAVIssuanceHook } from "../../interfaces/INAVIssuanceHook.sol"; import { Invoke } from "../lib/Invoke.sol"; import { ISetToken } from "../../interfaces/ISetToken.sol"; import { IWETH } from "../../interfaces/external/IWETH.sol"; import { ModuleBase } from "../lib/ModuleBase.sol"; import { Position } from "../lib/Position.sol"; import { PreciseUnitMath } from "../../lib/PreciseUnitMath.sol"; import { ResourceIdentifier } from "../lib/ResourceIdentifier.sol"; /** * @title NavIssuanceModule * @author Set Protocol * * Module that enables issuance and redemption with any valid ERC20 token or ETH if allowed by the manager. Sender receives * a proportional amount of SetTokens on issuance or ERC20 token on redemption based on the calculated net asset value using * oracle prices. Manager is able to enforce a premium / discount on issuance / redemption to avoid arbitrage and front * running when relying on oracle prices. Managers can charge a fee (denominated in reserve asset). */ contract NavIssuanceModule is ModuleBase, ReentrancyGuard { using AddressArrayUtils for address[]; using Invoke for ISetToken; using Position for ISetToken; using PreciseUnitMath for uint256; using PreciseUnitMath for int256; using ResourceIdentifier for IController; using SafeMath for uint256; using SafeCast for int256; using SafeCast for uint256; using SignedSafeMath for int256; /* ============ Events ============ */ event SetTokenNAVIssued( ISetToken indexed _setToken, address _issuer, address _to, address _reserveAsset, address _hookContract, uint256 _setTokenQuantity, uint256 _managerFee, uint256 _premium ); event SetTokenNAVRedeemed( ISetToken indexed _setToken, address _redeemer, address _to, address _reserveAsset, address _hookContract, uint256 _setTokenQuantity, uint256 _managerFee, uint256 _premium ); event ReserveAssetAdded( ISetToken indexed _setToken, address _newReserveAsset ); event ReserveAssetRemoved( ISetToken indexed _setToken, address _removedReserveAsset ); event PremiumEdited( ISetToken indexed _setToken, uint256 _newPremium ); event ManagerFeeEdited( ISetToken indexed _setToken, uint256 _newManagerFee, uint256 _index ); event FeeRecipientEdited( ISetToken indexed _setToken, address _feeRecipient ); /* ============ Structs ============ */ struct NAVIssuanceSettings { INAVIssuanceHook managerIssuanceHook; // Issuance hook configurations INAVIssuanceHook managerRedemptionHook; // Redemption hook configurations address[] reserveAssets; // Allowed reserve assets - Must have a price enabled with the price oracle address feeRecipient; // Manager fee recipient uint256[2] managerFees; // Manager fees. 0 index is issue and 1 index is redeem fee (0.01% = 1e14, 1% = 1e16) uint256 maxManagerFee; // Maximum fee manager is allowed to set for issue and redeem uint256 premiumPercentage; // Premium percentage (0.01% = 1e14, 1% = 1e16). This premium is a buffer around oracle // prices paid by user to the SetToken, which prevents arbitrage and oracle front running uint256 maxPremiumPercentage; // Maximum premium percentage manager is allowed to set (configured by manager) uint256 minSetTokenSupply; // Minimum SetToken supply required for issuance and redemption // to prevent dramatic inflationary changes to the SetToken's position multiplier } struct ActionInfo { uint256 preFeeReserveQuantity; // Reserve value before fees; During issuance, represents raw quantity // During redeem, represents post-premium value uint256 protocolFees; // Total protocol fees (direct + manager revenue share) uint256 managerFee; // Total manager fee paid in reserve asset uint256 netFlowQuantity; // When issuing, quantity of reserve asset sent to SetToken // When redeeming, quantity of reserve asset sent to redeemer uint256 setTokenQuantity; // When issuing, quantity of SetTokens minted to mintee // When redeeming, quantity of SetToken redeemed uint256 previousSetTokenSupply; // SetToken supply prior to issue/redeem action uint256 newSetTokenSupply; // SetToken supply after issue/redeem action int256 newPositionMultiplier; // SetToken position multiplier after issue/redeem uint256 newReservePositionUnit; // SetToken reserve asset position unit after issue/redeem } /* ============ State Variables ============ */ // Wrapped ETH address IWETH public immutable weth; // Mapping of SetToken to NAV issuance settings struct mapping(ISetToken => NAVIssuanceSettings) public navIssuanceSettings; // Mapping to efficiently check a SetToken's reserve asset validity // SetToken => reserveAsset => isReserveAsset mapping(ISetToken => mapping(address => bool)) public isReserveAsset; /* ============ Constants ============ */ // 0 index stores the manager fee in managerFees array, percentage charged on issue (denominated in reserve asset) uint256 constant internal MANAGER_ISSUE_FEE_INDEX = 0; // 1 index stores the manager fee percentage in managerFees array, charged on redeem uint256 constant internal MANAGER_REDEEM_FEE_INDEX = 1; // 0 index stores the manager revenue share protocol fee % on the controller, charged in the issuance function uint256 constant internal PROTOCOL_ISSUE_MANAGER_REVENUE_SHARE_FEE_INDEX = 0; // 1 index stores the manager revenue share protocol fee % on the controller, charged in the redeem function uint256 constant internal PROTOCOL_REDEEM_MANAGER_REVENUE_SHARE_FEE_INDEX = 1; // 2 index stores the direct protocol fee % on the controller, charged in the issuance function uint256 constant internal PROTOCOL_ISSUE_DIRECT_FEE_INDEX = 2; // 3 index stores the direct protocol fee % on the controller, charged in the redeem function uint256 constant internal PROTOCOL_REDEEM_DIRECT_FEE_INDEX = 3; /* ============ Constructor ============ */ /** * @param _controller Address of controller contract * @param _weth Address of wrapped eth */ constructor(IController _controller, IWETH _weth) public ModuleBase(_controller) { weth = _weth; } /* ============ External Functions ============ */ /** * Deposits the allowed reserve asset into the SetToken and mints the appropriate % of Net Asset Value of the SetToken * to the specified _to address. * * @param _setToken Instance of the SetToken contract * @param _reserveAsset Address of the reserve asset to issue with * @param _reserveAssetQuantity Quantity of the reserve asset to issue with * @param _minSetTokenReceiveQuantity Min quantity of SetToken to receive after issuance * @param _to Address to mint SetToken to */ function issue( ISetToken _setToken, address _reserveAsset, uint256 _reserveAssetQuantity, uint256 _minSetTokenReceiveQuantity, address _to ) external nonReentrant onlyValidAndInitializedSet(_setToken) { _validateCommon(_setToken, _reserveAsset, _reserveAssetQuantity); _callPreIssueHooks(_setToken, _reserveAsset, _reserveAssetQuantity, msg.sender, _to); ActionInfo memory issueInfo = _createIssuanceInfo(_setToken, _reserveAsset, _reserveAssetQuantity); _validateIssuanceInfo(_setToken, _minSetTokenReceiveQuantity, issueInfo); _transferCollateralAndHandleFees(_setToken, IERC20(_reserveAsset), issueInfo); _handleIssueStateUpdates(_setToken, _reserveAsset, _to, issueInfo); } /** * Wraps ETH and deposits WETH if allowed into the SetToken and mints the appropriate % of Net Asset Value of the SetToken * to the specified _to address. * * @param _setToken Instance of the SetToken contract * @param _minSetTokenReceiveQuantity Min quantity of SetToken to receive after issuance * @param _to Address to mint SetToken to */ function issueWithEther( ISetToken _setToken, uint256 _minSetTokenReceiveQuantity, address _to ) external payable nonReentrant onlyValidAndInitializedSet(_setToken) { weth.deposit{ value: msg.value }(); _validateCommon(_setToken, address(weth), msg.value); _callPreIssueHooks(_setToken, address(weth), msg.value, msg.sender, _to); ActionInfo memory issueInfo = _createIssuanceInfo(_setToken, address(weth), msg.value); _validateIssuanceInfo(_setToken, _minSetTokenReceiveQuantity, issueInfo); _transferWETHAndHandleFees(_setToken, issueInfo); _handleIssueStateUpdates(_setToken, address(weth), _to, issueInfo); } /** * Redeems a SetToken into a valid reserve asset representing the appropriate % of Net Asset Value of the SetToken * to the specified _to address. Only valid if there are available reserve units on the SetToken. * * @param _setToken Instance of the SetToken contract * @param _reserveAsset Address of the reserve asset to redeem with * @param _setTokenQuantity Quantity of SetTokens to redeem * @param _minReserveReceiveQuantity Min quantity of reserve asset to receive * @param _to Address to redeem reserve asset to */ function redeem( ISetToken _setToken, address _reserveAsset, uint256 _setTokenQuantity, uint256 _minReserveReceiveQuantity, address _to ) external nonReentrant onlyValidAndInitializedSet(_setToken) { _validateCommon(_setToken, _reserveAsset, _setTokenQuantity); _callPreRedeemHooks(_setToken, _setTokenQuantity, msg.sender, _to); ActionInfo memory redeemInfo = _createRedemptionInfo(_setToken, _reserveAsset, _setTokenQuantity); _validateRedemptionInfo(_setToken, _minReserveReceiveQuantity, _setTokenQuantity, redeemInfo); _setToken.burn(msg.sender, _setTokenQuantity); // Instruct the SetToken to transfer the reserve asset back to the user _setToken.strictInvokeTransfer( _reserveAsset, _to, redeemInfo.netFlowQuantity ); _handleRedemptionFees(_setToken, _reserveAsset, redeemInfo); _handleRedeemStateUpdates(_setToken, _reserveAsset, _to, redeemInfo); } /** * Redeems a SetToken into Ether (if WETH is valid) representing the appropriate % of Net Asset Value of the SetToken * to the specified _to address. Only valid if there are available WETH units on the SetToken. * * @param _setToken Instance of the SetToken contract * @param _setTokenQuantity Quantity of SetTokens to redeem * @param _minReserveReceiveQuantity Min quantity of reserve asset to receive * @param _to Address to redeem reserve asset to */ function redeemIntoEther( ISetToken _setToken, uint256 _setTokenQuantity, uint256 _minReserveReceiveQuantity, address payable _to ) external nonReentrant onlyValidAndInitializedSet(_setToken) { _validateCommon(_setToken, address(weth), _setTokenQuantity); _callPreRedeemHooks(_setToken, _setTokenQuantity, msg.sender, _to); ActionInfo memory redeemInfo = _createRedemptionInfo(_setToken, address(weth), _setTokenQuantity); _validateRedemptionInfo(_setToken, _minReserveReceiveQuantity, _setTokenQuantity, redeemInfo); _setToken.burn(msg.sender, _setTokenQuantity); // Instruct the SetToken to transfer WETH from SetToken to module _setToken.strictInvokeTransfer( address(weth), address(this), redeemInfo.netFlowQuantity ); weth.withdraw(redeemInfo.netFlowQuantity); _to.transfer(redeemInfo.netFlowQuantity); _handleRedemptionFees(_setToken, address(weth), redeemInfo); _handleRedeemStateUpdates(_setToken, address(weth), _to, redeemInfo); } /** * SET MANAGER ONLY. Add an allowed reserve asset * * @param _setToken Instance of the SetToken * @param _reserveAsset Address of the reserve asset to add */ function addReserveAsset(ISetToken _setToken, address _reserveAsset) external onlyManagerAndValidSet(_setToken) { require(!isReserveAsset[_setToken][_reserveAsset], "Reserve asset already exists"); navIssuanceSettings[_setToken].reserveAssets.push(_reserveAsset); isReserveAsset[_setToken][_reserveAsset] = true; emit ReserveAssetAdded(_setToken, _reserveAsset); } /** * SET MANAGER ONLY. Remove a reserve asset * * @param _setToken Instance of the SetToken * @param _reserveAsset Address of the reserve asset to remove */ function removeReserveAsset(ISetToken _setToken, address _reserveAsset) external onlyManagerAndValidSet(_setToken) { require(isReserveAsset[_setToken][_reserveAsset], "Reserve asset does not exist"); navIssuanceSettings[_setToken].reserveAssets = navIssuanceSettings[_setToken].reserveAssets.remove(_reserveAsset); delete isReserveAsset[_setToken][_reserveAsset]; emit ReserveAssetRemoved(_setToken, _reserveAsset); } /** * SET MANAGER ONLY. Edit the premium percentage * * @param _setToken Instance of the SetToken * @param _premiumPercentage Premium percentage in 10e16 (e.g. 10e16 = 1%) */ function editPremium(ISetToken _setToken, uint256 _premiumPercentage) external onlyManagerAndValidSet(_setToken) { require(_premiumPercentage <= navIssuanceSettings[_setToken].maxPremiumPercentage, "Premium must be less than maximum allowed"); navIssuanceSettings[_setToken].premiumPercentage = _premiumPercentage; emit PremiumEdited(_setToken, _premiumPercentage); } /** * SET MANAGER ONLY. Edit manager fee * * @param _setToken Instance of the SetToken * @param _managerFeePercentage Manager fee percentage in 10e16 (e.g. 10e16 = 1%) * @param _managerFeeIndex Manager fee index. 0 index is issue fee, 1 index is redeem fee */ function editManagerFee( ISetToken _setToken, uint256 _managerFeePercentage, uint256 _managerFeeIndex ) external onlyManagerAndValidSet(_setToken) { require(_managerFeePercentage <= navIssuanceSettings[_setToken].maxManagerFee, "Manager fee must be less than maximum allowed"); navIssuanceSettings[_setToken].managerFees[_managerFeeIndex] = _managerFeePercentage; emit ManagerFeeEdited(_setToken, _managerFeePercentage, _managerFeeIndex); } /** * SET MANAGER ONLY. Edit the manager fee recipient * * @param _setToken Instance of the SetToken * @param _managerFeeRecipient Manager fee recipient */ function editFeeRecipient(ISetToken _setToken, address _managerFeeRecipient) external onlyManagerAndValidSet(_setToken) { require(_managerFeeRecipient != address(0), "Fee recipient must not be 0 address"); navIssuanceSettings[_setToken].feeRecipient = _managerFeeRecipient; emit FeeRecipientEdited(_setToken, _managerFeeRecipient); } /** * SET MANAGER ONLY. Initializes this module to the SetToken with hooks, allowed reserve assets, * fees and issuance premium. Only callable by the SetToken's manager. Hook addresses are optional. * Address(0) means that no hook will be called. * * @param _setToken Instance of the SetToken to issue * @param _navIssuanceSettings NAVIssuanceSettings struct defining parameters */ function initialize( ISetToken _setToken, NAVIssuanceSettings memory _navIssuanceSettings ) external onlySetManager(_setToken, msg.sender) onlyValidAndPendingSet(_setToken) { require(_navIssuanceSettings.reserveAssets.length > 0, "Reserve assets must be greater than 0"); require(_navIssuanceSettings.maxManagerFee < PreciseUnitMath.preciseUnit(), "Max manager fee must be less than 100%"); require(_navIssuanceSettings.maxPremiumPercentage < PreciseUnitMath.preciseUnit(), "Max premium percentage must be less than 100%"); require(_navIssuanceSettings.managerFees[0] <= _navIssuanceSettings.maxManagerFee, "Manager issue fee must be less than max"); require(_navIssuanceSettings.managerFees[1] <= _navIssuanceSettings.maxManagerFee, "Manager redeem fee must be less than max"); require(_navIssuanceSettings.premiumPercentage <= _navIssuanceSettings.maxPremiumPercentage, "Premium must be less than max"); require(_navIssuanceSettings.feeRecipient != address(0), "Fee Recipient must be non-zero address."); // Initial mint of Set cannot use NAVIssuance since minSetTokenSupply must be > 0 require(_navIssuanceSettings.minSetTokenSupply > 0, "Min SetToken supply must be greater than 0"); for (uint256 i = 0; i < _navIssuanceSettings.reserveAssets.length; i++) { require(!isReserveAsset[_setToken][_navIssuanceSettings.reserveAssets[i]], "Reserve assets must be unique"); isReserveAsset[_setToken][_navIssuanceSettings.reserveAssets[i]] = true; } navIssuanceSettings[_setToken] = _navIssuanceSettings; _setToken.initializeModule(); } /** * Removes this module from the SetToken, via call by the SetToken. Issuance settings and * reserve asset states are deleted. */ function removeModule() external override { ISetToken setToken = ISetToken(msg.sender); for (uint256 i = 0; i < navIssuanceSettings[setToken].reserveAssets.length; i++) { delete isReserveAsset[setToken][navIssuanceSettings[setToken].reserveAssets[i]]; } delete navIssuanceSettings[setToken]; } receive() external payable {} /* ============ External Getter Functions ============ */ function getReserveAssets(ISetToken _setToken) external view returns (address[] memory) { return navIssuanceSettings[_setToken].reserveAssets; } function getIssuePremium( ISetToken _setToken, address _reserveAsset, uint256 _reserveAssetQuantity ) external view returns (uint256) { return _getIssuePremium(_setToken, _reserveAsset, _reserveAssetQuantity); } function getRedeemPremium( ISetToken _setToken, address _reserveAsset, uint256 _setTokenQuantity ) external view returns (uint256) { return _getRedeemPremium(_setToken, _reserveAsset, _setTokenQuantity); } function getManagerFee(ISetToken _setToken, uint256 _managerFeeIndex) external view returns (uint256) { return navIssuanceSettings[_setToken].managerFees[_managerFeeIndex]; } /** * Get the expected SetTokens minted to recipient on issuance * * @param _setToken Instance of the SetToken * @param _reserveAsset Address of the reserve asset * @param _reserveAssetQuantity Quantity of the reserve asset to issue with * * @return uint256 Expected SetTokens to be minted to recipient */ function getExpectedSetTokenIssueQuantity( ISetToken _setToken, address _reserveAsset, uint256 _reserveAssetQuantity ) external view returns (uint256) { (,, uint256 netReserveFlow) = _getFees( _setToken, _reserveAssetQuantity, PROTOCOL_ISSUE_MANAGER_REVENUE_SHARE_FEE_INDEX, PROTOCOL_ISSUE_DIRECT_FEE_INDEX, MANAGER_ISSUE_FEE_INDEX ); uint256 setTotalSupply = _setToken.totalSupply(); return _getSetTokenMintQuantity( _setToken, _reserveAsset, netReserveFlow, setTotalSupply ); } /** * Get the expected reserve asset to be redeemed * * @param _setToken Instance of the SetToken * @param _reserveAsset Address of the reserve asset * @param _setTokenQuantity Quantity of SetTokens to redeem * * @return uint256 Expected reserve asset quantity redeemed */ function getExpectedReserveRedeemQuantity( ISetToken _setToken, address _reserveAsset, uint256 _setTokenQuantity ) external view returns (uint256) { uint256 preFeeReserveQuantity = _getRedeemReserveQuantity(_setToken, _reserveAsset, _setTokenQuantity); (,, uint256 netReserveFlows) = _getFees( _setToken, preFeeReserveQuantity, PROTOCOL_REDEEM_MANAGER_REVENUE_SHARE_FEE_INDEX, PROTOCOL_REDEEM_DIRECT_FEE_INDEX, MANAGER_REDEEM_FEE_INDEX ); return netReserveFlows; } /** * Checks if issue is valid * * @param _setToken Instance of the SetToken * @param _reserveAsset Address of the reserve asset * @param _reserveAssetQuantity Quantity of the reserve asset to issue with * * @return bool Returns true if issue is valid */ function isIssueValid( ISetToken _setToken, address _reserveAsset, uint256 _reserveAssetQuantity ) external view returns (bool) { uint256 setTotalSupply = _setToken.totalSupply(); return _reserveAssetQuantity != 0 && isReserveAsset[_setToken][_reserveAsset] && setTotalSupply >= navIssuanceSettings[_setToken].minSetTokenSupply; } /** * Checks if redeem is valid * * @param _setToken Instance of the SetToken * @param _reserveAsset Address of the reserve asset * @param _setTokenQuantity Quantity of SetTokens to redeem * * @return bool Returns true if redeem is valid */ function isRedeemValid( ISetToken _setToken, address _reserveAsset, uint256 _setTokenQuantity ) external view returns (bool) { uint256 setTotalSupply = _setToken.totalSupply(); if ( _setTokenQuantity == 0 || !isReserveAsset[_setToken][_reserveAsset] || setTotalSupply < navIssuanceSettings[_setToken].minSetTokenSupply.add(_setTokenQuantity) ) { return false; } else { uint256 totalRedeemValue =_getRedeemReserveQuantity(_setToken, _reserveAsset, _setTokenQuantity); (,, uint256 expectedRedeemQuantity) = _getFees( _setToken, totalRedeemValue, PROTOCOL_REDEEM_MANAGER_REVENUE_SHARE_FEE_INDEX, PROTOCOL_REDEEM_DIRECT_FEE_INDEX, MANAGER_REDEEM_FEE_INDEX ); uint256 existingUnit = _setToken.getDefaultPositionRealUnit(_reserveAsset).toUint256(); return existingUnit.preciseMul(setTotalSupply) >= expectedRedeemQuantity; } } /* ============ Internal Functions ============ */ function _validateCommon(ISetToken _setToken, address _reserveAsset, uint256 _quantity) internal view { require(_quantity > 0, "Quantity must be > 0"); require(isReserveAsset[_setToken][_reserveAsset], "Must be valid reserve asset"); } function _validateIssuanceInfo(ISetToken _setToken, uint256 _minSetTokenReceiveQuantity, ActionInfo memory _issueInfo) internal view { // Check that total supply is greater than min supply needed for issuance // Note: A min supply amount is needed to avoid division by 0 when SetToken supply is 0 require( _issueInfo.previousSetTokenSupply >= navIssuanceSettings[_setToken].minSetTokenSupply, "Supply must be greater than minimum to enable issuance" ); require(_issueInfo.setTokenQuantity >= _minSetTokenReceiveQuantity, "Must be greater than min SetToken"); } function _validateRedemptionInfo( ISetToken _setToken, uint256 _minReserveReceiveQuantity, uint256 _setTokenQuantity, ActionInfo memory _redeemInfo ) internal view { // Check that new supply is more than min supply needed for redemption // Note: A min supply amount is needed to avoid division by 0 when redeeming SetToken to 0 require( _redeemInfo.newSetTokenSupply >= navIssuanceSettings[_setToken].minSetTokenSupply, "Supply must be greater than minimum to enable redemption" ); require(_redeemInfo.netFlowQuantity >= _minReserveReceiveQuantity, "Must be greater than min receive reserve quantity"); } function _createIssuanceInfo( ISetToken _setToken, address _reserveAsset, uint256 _reserveAssetQuantity ) internal view returns (ActionInfo memory) { ActionInfo memory issueInfo; issueInfo.previousSetTokenSupply = _setToken.totalSupply(); issueInfo.preFeeReserveQuantity = _reserveAssetQuantity; (issueInfo.protocolFees, issueInfo.managerFee, issueInfo.netFlowQuantity) = _getFees( _setToken, issueInfo.preFeeReserveQuantity, PROTOCOL_ISSUE_MANAGER_REVENUE_SHARE_FEE_INDEX, PROTOCOL_ISSUE_DIRECT_FEE_INDEX, MANAGER_ISSUE_FEE_INDEX ); issueInfo.setTokenQuantity = _getSetTokenMintQuantity( _setToken, _reserveAsset, issueInfo.netFlowQuantity, issueInfo.previousSetTokenSupply ); (issueInfo.newSetTokenSupply, issueInfo.newPositionMultiplier) = _getIssuePositionMultiplier(_setToken, issueInfo); issueInfo.newReservePositionUnit = _getIssuePositionUnit(_setToken, _reserveAsset, issueInfo); return issueInfo; } function _createRedemptionInfo( ISetToken _setToken, address _reserveAsset, uint256 _setTokenQuantity ) internal view returns (ActionInfo memory) { ActionInfo memory redeemInfo; redeemInfo.setTokenQuantity = _setTokenQuantity; redeemInfo.preFeeReserveQuantity =_getRedeemReserveQuantity(_setToken, _reserveAsset, _setTokenQuantity); (redeemInfo.protocolFees, redeemInfo.managerFee, redeemInfo.netFlowQuantity) = _getFees( _setToken, redeemInfo.preFeeReserveQuantity, PROTOCOL_REDEEM_MANAGER_REVENUE_SHARE_FEE_INDEX, PROTOCOL_REDEEM_DIRECT_FEE_INDEX, MANAGER_REDEEM_FEE_INDEX ); redeemInfo.previousSetTokenSupply = _setToken.totalSupply(); (redeemInfo.newSetTokenSupply, redeemInfo.newPositionMultiplier) = _getRedeemPositionMultiplier(_setToken, _setTokenQuantity, redeemInfo); redeemInfo.newReservePositionUnit = _getRedeemPositionUnit(_setToken, _reserveAsset, redeemInfo); return redeemInfo; } /** * Transfer reserve asset from user to SetToken and fees from user to appropriate fee recipients */ function _transferCollateralAndHandleFees(ISetToken _setToken, IERC20 _reserveAsset, ActionInfo memory _issueInfo) internal { transferFrom(_reserveAsset, msg.sender, address(_setToken), _issueInfo.netFlowQuantity); if (_issueInfo.protocolFees > 0) { transferFrom(_reserveAsset, msg.sender, controller.feeRecipient(), _issueInfo.protocolFees); } if (_issueInfo.managerFee > 0) { transferFrom(_reserveAsset, msg.sender, navIssuanceSettings[_setToken].feeRecipient, _issueInfo.managerFee); } } /** * Transfer WETH from module to SetToken and fees from module to appropriate fee recipients */ function _transferWETHAndHandleFees(ISetToken _setToken, ActionInfo memory _issueInfo) internal { weth.transfer(address(_setToken), _issueInfo.netFlowQuantity); if (_issueInfo.protocolFees > 0) { weth.transfer(controller.feeRecipient(), _issueInfo.protocolFees); } if (_issueInfo.managerFee > 0) { weth.transfer(navIssuanceSettings[_setToken].feeRecipient, _issueInfo.managerFee); } } function _handleIssueStateUpdates( ISetToken _setToken, address _reserveAsset, address _to, ActionInfo memory _issueInfo ) internal { _setToken.editPositionMultiplier(_issueInfo.newPositionMultiplier); _setToken.editDefaultPosition(_reserveAsset, _issueInfo.newReservePositionUnit); _setToken.mint(_to, _issueInfo.setTokenQuantity); emit SetTokenNAVIssued( _setToken, msg.sender, _to, _reserveAsset, address(navIssuanceSettings[_setToken].managerIssuanceHook), _issueInfo.setTokenQuantity, _issueInfo.managerFee, _issueInfo.protocolFees ); } function _handleRedeemStateUpdates( ISetToken _setToken, address _reserveAsset, address _to, ActionInfo memory _redeemInfo ) internal { _setToken.editPositionMultiplier(_redeemInfo.newPositionMultiplier); _setToken.editDefaultPosition(_reserveAsset, _redeemInfo.newReservePositionUnit); emit SetTokenNAVRedeemed( _setToken, msg.sender, _to, _reserveAsset, address(navIssuanceSettings[_setToken].managerRedemptionHook), _redeemInfo.setTokenQuantity, _redeemInfo.managerFee, _redeemInfo.protocolFees ); } function _handleRedemptionFees(ISetToken _setToken, address _reserveAsset, ActionInfo memory _redeemInfo) internal { // Instruct the SetToken to transfer protocol fee to fee recipient if there is a fee payProtocolFeeFromSetToken(_setToken, _reserveAsset, _redeemInfo.protocolFees); // Instruct the SetToken to transfer manager fee to manager fee recipient if there is a fee if (_redeemInfo.managerFee > 0) { _setToken.strictInvokeTransfer( _reserveAsset, navIssuanceSettings[_setToken].feeRecipient, _redeemInfo.managerFee ); } } /** * Returns the issue premium percentage. Virtual function that can be overridden in future versions of the module * and can contain arbitrary logic to calculate the issuance premium. */ function _getIssuePremium( ISetToken _setToken, address /* _reserveAsset */, uint256 /* _reserveAssetQuantity */ ) virtual internal view returns (uint256) { return navIssuanceSettings[_setToken].premiumPercentage; } /** * Returns the redeem premium percentage. Virtual function that can be overridden in future versions of the module * and can contain arbitrary logic to calculate the redemption premium. */ function _getRedeemPremium( ISetToken _setToken, address /* _reserveAsset */, uint256 /* _setTokenQuantity */ ) virtual internal view returns (uint256) { return navIssuanceSettings[_setToken].premiumPercentage; } /** * Returns the fees attributed to the manager and the protocol. The fees are calculated as follows: * * ManagerFee = (manager fee % - % to protocol) * reserveAssetQuantity * Protocol Fee = (% manager fee share + direct fee %) * reserveAssetQuantity * * @param _setToken Instance of the SetToken * @param _reserveAssetQuantity Quantity of reserve asset to calculate fees from * @param _protocolManagerFeeIndex Index to pull rev share NAV Issuance fee from the Controller * @param _protocolDirectFeeIndex Index to pull direct NAV issuance fee from the Controller * @param _managerFeeIndex Index from NAVIssuanceSettings (0 = issue fee, 1 = redeem fee) * * @return uint256 Fees paid to the protocol in reserve asset * @return uint256 Fees paid to the manager in reserve asset * @return uint256 Net reserve to user net of fees */ function _getFees( ISetToken _setToken, uint256 _reserveAssetQuantity, uint256 _protocolManagerFeeIndex, uint256 _protocolDirectFeeIndex, uint256 _managerFeeIndex ) internal view returns (uint256, uint256, uint256) { (uint256 protocolFeePercentage, uint256 managerFeePercentage) = _getProtocolAndManagerFeePercentages( _setToken, _protocolManagerFeeIndex, _protocolDirectFeeIndex, _managerFeeIndex ); // Calculate total notional fees uint256 protocolFees = protocolFeePercentage.preciseMul(_reserveAssetQuantity); uint256 managerFee = managerFeePercentage.preciseMul(_reserveAssetQuantity); uint256 netReserveFlow = _reserveAssetQuantity.sub(protocolFees).sub(managerFee); return (protocolFees, managerFee, netReserveFlow); } function _getProtocolAndManagerFeePercentages( ISetToken _setToken, uint256 _protocolManagerFeeIndex, uint256 _protocolDirectFeeIndex, uint256 _managerFeeIndex ) internal view returns(uint256, uint256) { // Get protocol fee percentages uint256 protocolDirectFeePercent = controller.getModuleFee(address(this), _protocolDirectFeeIndex); uint256 protocolManagerShareFeePercent = controller.getModuleFee(address(this), _protocolManagerFeeIndex); uint256 managerFeePercent = navIssuanceSettings[_setToken].managerFees[_managerFeeIndex]; // Calculate revenue share split percentage uint256 protocolRevenueSharePercentage = protocolManagerShareFeePercent.preciseMul(managerFeePercent); uint256 managerRevenueSharePercentage = managerFeePercent.sub(protocolRevenueSharePercentage); uint256 totalProtocolFeePercentage = protocolRevenueSharePercentage.add(protocolDirectFeePercent); return (totalProtocolFeePercentage, managerRevenueSharePercentage); } function _getSetTokenMintQuantity( ISetToken _setToken, address _reserveAsset, uint256 _netReserveFlows, // Value of reserve asset net of fees uint256 _setTotalSupply ) internal view returns (uint256) { uint256 premiumPercentage = _getIssuePremium(_setToken, _reserveAsset, _netReserveFlows); uint256 premiumValue = _netReserveFlows.preciseMul(premiumPercentage); // Get valuation of the SetToken with the quote asset as the reserve asset. Returns value in precise units (1e18) // Reverts if price is not found uint256 setTokenValuation = controller.getSetValuer().calculateSetTokenValuation(_setToken, _reserveAsset); // Get reserve asset decimals uint256 reserveAssetDecimals = ERC20(_reserveAsset).decimals(); uint256 normalizedTotalReserveQuantityNetFees = _netReserveFlows.preciseDiv(10 ** reserveAssetDecimals); uint256 normalizedTotalReserveQuantityNetFeesAndPremium = _netReserveFlows.sub(premiumValue).preciseDiv(10 ** reserveAssetDecimals); // Calculate SetTokens to mint to issuer uint256 denominator = _setTotalSupply.preciseMul(setTokenValuation).add(normalizedTotalReserveQuantityNetFees).sub(normalizedTotalReserveQuantityNetFeesAndPremium); return normalizedTotalReserveQuantityNetFeesAndPremium.preciseMul(_setTotalSupply).preciseDiv(denominator); } function _getRedeemReserveQuantity( ISetToken _setToken, address _reserveAsset, uint256 _setTokenQuantity ) internal view returns (uint256) { // Get valuation of the SetToken with the quote asset as the reserve asset. Returns value in precise units (10e18) // Reverts if price is not found uint256 setTokenValuation = controller.getSetValuer().calculateSetTokenValuation(_setToken, _reserveAsset); uint256 totalRedeemValueInPreciseUnits = _setTokenQuantity.preciseMul(setTokenValuation); // Get reserve asset decimals uint256 reserveAssetDecimals = ERC20(_reserveAsset).decimals(); uint256 prePremiumReserveQuantity = totalRedeemValueInPreciseUnits.preciseMul(10 ** reserveAssetDecimals); uint256 premiumPercentage = _getRedeemPremium(_setToken, _reserveAsset, _setTokenQuantity); uint256 premiumQuantity = prePremiumReserveQuantity.preciseMulCeil(premiumPercentage); return prePremiumReserveQuantity.sub(premiumQuantity); } /** * The new position multiplier is calculated as follows: * inflationPercentage = (newSupply - oldSupply) / newSupply * newMultiplier = (1 - inflationPercentage) * positionMultiplier */ function _getIssuePositionMultiplier( ISetToken _setToken, ActionInfo memory _issueInfo ) internal view returns (uint256, int256) { // Calculate inflation and new position multiplier. Note: Round inflation up in order to round position multiplier down uint256 newTotalSupply = _issueInfo.setTokenQuantity.add(_issueInfo.previousSetTokenSupply); int256 newPositionMultiplier = _setToken.positionMultiplier() .mul(_issueInfo.previousSetTokenSupply.toInt256()) .div(newTotalSupply.toInt256()); return (newTotalSupply, newPositionMultiplier); } /** * Calculate deflation and new position multiplier. Note: Round deflation down in order to round position multiplier down * * The new position multiplier is calculated as follows: * deflationPercentage = (oldSupply - newSupply) / newSupply * newMultiplier = (1 + deflationPercentage) * positionMultiplier */ function _getRedeemPositionMultiplier( ISetToken _setToken, uint256 _setTokenQuantity, ActionInfo memory _redeemInfo ) internal view returns (uint256, int256) { uint256 newTotalSupply = _redeemInfo.previousSetTokenSupply.sub(_setTokenQuantity); int256 newPositionMultiplier = _setToken.positionMultiplier() .mul(_redeemInfo.previousSetTokenSupply.toInt256()) .div(newTotalSupply.toInt256()); return (newTotalSupply, newPositionMultiplier); } /** * The new position reserve asset unit is calculated as follows: * totalReserve = (oldUnit * oldSetTokenSupply) + reserveQuantity * newUnit = totalReserve / newSetTokenSupply */ function _getIssuePositionUnit( ISetToken _setToken, address _reserveAsset, ActionInfo memory _issueInfo ) internal view returns (uint256) { uint256 existingUnit = _setToken.getDefaultPositionRealUnit(_reserveAsset).toUint256(); uint256 totalReserve = existingUnit .preciseMul(_issueInfo.previousSetTokenSupply) .add(_issueInfo.netFlowQuantity); return totalReserve.preciseDiv(_issueInfo.newSetTokenSupply); } /** * The new position reserve asset unit is calculated as follows: * totalReserve = (oldUnit * oldSetTokenSupply) - reserveQuantityToSendOut * newUnit = totalReserve / newSetTokenSupply */ function _getRedeemPositionUnit( ISetToken _setToken, address _reserveAsset, ActionInfo memory _redeemInfo ) internal view returns (uint256) { uint256 existingUnit = _setToken.getDefaultPositionRealUnit(_reserveAsset).toUint256(); uint256 totalExistingUnits = existingUnit.preciseMul(_redeemInfo.previousSetTokenSupply); uint256 outflow = _redeemInfo.netFlowQuantity.add(_redeemInfo.protocolFees).add(_redeemInfo.managerFee); // Require withdrawable quantity is greater than existing collateral require(totalExistingUnits >= outflow, "Must be greater than total available collateral"); return totalExistingUnits.sub(outflow).preciseDiv(_redeemInfo.newSetTokenSupply); } /** * If a pre-issue hook has been configured, call the external-protocol contract. Pre-issue hook logic * can contain arbitrary logic including validations, external function calls, etc. */ function _callPreIssueHooks( ISetToken _setToken, address _reserveAsset, uint256 _reserveAssetQuantity, address _caller, address _to ) internal { INAVIssuanceHook preIssueHook = navIssuanceSettings[_setToken].managerIssuanceHook; if (address(preIssueHook) != address(0)) { preIssueHook.invokePreIssueHook(_setToken, _reserveAsset, _reserveAssetQuantity, _caller, _to); } } /** * If a pre-redeem hook has been configured, call the external-protocol contract. */ function _callPreRedeemHooks(ISetToken _setToken, uint256 _setQuantity, address _caller, address _to) internal { INAVIssuanceHook preRedeemHook = navIssuanceSettings[_setToken].managerRedemptionHook; if (address(preRedeemHook) != address(0)) { preRedeemHook.invokePreRedeemHook(_setToken, _setQuantity, _caller, _to); } } }
If a pre-redeem hook has been configured, call the external-protocol contract./
function _callPreRedeemHooks(ISetToken _setToken, uint256 _setQuantity, address _caller, address _to) internal { INAVIssuanceHook preRedeemHook = navIssuanceSettings[_setToken].managerRedemptionHook; if (address(preRedeemHook) != address(0)) { preRedeemHook.invokePreRedeemHook(_setToken, _setQuantity, _caller, _to); } }
101,370
pragma solidity ^0.4.8; //EnergyTradingContract // @authors: // Jorge <[email protected]> // usage: // accepts bids from the Grid operator /** @title Energy Trading Contract */ contract EnergyTradingContract { event HasBeenPayed(uint timestamp, address from, uint amount); //event raised contract received money. event HasBeenDisabled(uint timestamp); //event raised when contract has been disabled event HasBeenClosed(uint timestamp); //event raised when contract has been closed event BidAccepted(address trader, uint capacity, uint pricePerKwh); //event raised when the trade has completed //modifier for: account restriction modifier onlyBy(address _account){ if (msg.sender != _account) { revert(); } _; } //modifier for: owner restriction modifier onlyOwner { if (!isOwner(msg.sender)) { revert(); } _; } //modifier for: execute only if the contract has been closed modifier onlyWhenClosed(){ if (!isClosed) { revert(); } _; } //modifier for execution only if the contract is active modifier onlyWhenEnabled(){ if (isDisabled) { revert(); } _; } //deposits (ETH) this contract has received mapping(address => uint) deposits; //PRIVATE VARIABLES address private owner; //address of the owner of the contract address private oracle; //address of the oracle of this contract bool private isDisabled =true; //determines if the contract has been disabled bool private hasBeenInitialized = false; bool private isClosed; //determines if the owner has closed/stopped/writtenOff the contract. uint private createdDate; //date when contract was created uint private capacity; //latest capacity measure available to trade uint private lastTradeDate; //date when the latest trade happened address private lastTrader; //address of the latest trader uint private lastTradeCapacity; //capacity value of the latest trade uint private nextTradeDate; //date when the contract is allowed to trade again //CONSTRUCTOR /**@dev Constructor */ function EnergyTradingContract() { owner = msg.sender; createdDate = now; isDisabled = true; } //FALLBACK FUNCTION function() payable { if (isDisabled) { revert(); } HasBeenPayed(now, msg.sender, msg.value); //notify to everyone interested } /**@dev returns the date when the contract was created*/ function getCreationDate() constant public returns (uint) { return createdDate; } /**@dev Disables a Contract, Allowing code to run. Use in emergency. */ function disable() onlyOwner public { isDisabled = true; } /**@dev Closes a Contract. Disabling all code. */ function close() onlyOwner public { selfdestruct(owner); } /**@dev Determines if the account is an owner */ function isOwner(address _account) private returns (bool) { return (owner == _account); } /**@dev initialize *@param _oracle address of the entity that updates the capacity */ function initialize(address _oracle) onlyOwner { if (hasBeenInitialized) { revert(); } oracle = _oracle; isDisabled = false; hasBeenInitialized = true; } /**@dev Triggers for an action in the marketplace *@param _pricePerKwh determines the price of the Kwh for the specific trade slot */ function trade(uint _pricePerKwh) onlyWhenEnabled returns(bool) { //if (now > nextTradeDate) { //only accept a trade when the "promise to return" window has completed lastTrader = msg.sender; //lastTradeDate = now; lastTradeCapacity = capacity; //nextTradeDate = lastTradeDate + 15 minutes; BidAccepted(lastTrader, lastTradeCapacity, _pricePerKwh); return true; //} //return false; } /**@dev Allows the trader to query to current capacity before an actual trade. */ function getCapacityAvailability() constant public returns(uint) { return capacity; } /**@dev updateCapacity *@param _lastMeasure number (in KW) to allow on next trade */ function updateCapacity(uint _lastMeasure) onlyBy(oracle) onlyWhenEnabled { capacity = _lastMeasure; } }
Allows the trader to query to current capacity before an actual trade./
function getCapacityAvailability() constant public returns(uint) { return capacity; }
12,923,522
./partial_match/1/0x12A73E14ef40DbD995baE85377961A1D2F1596be/sources/contracts/interfaces/ICreate3.sol
ICreate3 Interface for a Create3 contract. Normally, this functionality would exist as internal functions in a library, which can be inherited by other contracts. Instead, we put this functionality in a contract so that other contracts can use non-standard Create3 formulas in a modular way. These non-standard Create3 formulas exist on some EVM-compatible chains. Each Create3 contract that inherits from this interface will implement its own Create3 formula. The contracts that inherit from this interface are meant to be delegatecalled by the `SphinxManager` in order to deploy contracts. It's important to note that a Create3 contract must be delegatecalled by the `SphinxManager` and not called directly. This ensures that the address of the deployed contract is determined by the address of the `SphinxManager` contract and not the Create3 contract. Otherwise, it'd be possible for an attacker to snipe a user's contract by calling the `deploy` function on the Create3 contract./ The creation code isn't used in the address calculation.
interface ICreate3 { function deploy( bytes32 _salt, bytes memory _creationCode, uint256 _value ) external returns (address deployed); function getAddress(bytes32 _salt) external view returns (address); function getAddressFromDeployer( bytes32 _salt, address _deployer ) external view returns (address); pragma solidity ^0.8.15; }
9,336,604
./partial_match/42/0x8E845b08319e3203701bCBC1e457F5377403b765/sources/MigratedReserve.sol
hard deposit guarantees that the currency stays in the reserve
function hardDeposit(uint currencyAmount) public auth { _depositAction(msg.sender, currencyAmount); }
8,840,390
./full_match/71402/0x62AEdB532DBa29a45C36396A84b4D57FAF5766Ec/sources/contracts/LinearPool.sol
The wrapped token's scaling factor is not constant, but increases over time as the wrapped token increases in value.
function _scalingFactors() internal view virtual override returns (uint256[] memory) { uint256[] memory scalingFactors = new uint256[](_TOTAL_TOKENS); scalingFactors[_mainIndex] = _scalingFactorMainToken; scalingFactors[_wrappedIndex] = _scalingFactorWrappedToken.mulDown(_getWrappedTokenRate()); scalingFactors[_bptIndex] = FixedPoint.ONE; return scalingFactors; }
7,092,476
./full_match/1/0xCEB1aAaf0E97b7a9b6d7313e999a3a27b04d75Cb/sources/src/tokens/ERC5095.sol
Determine how many principal tokens are needed to purchase the underlying Pre maturity Receive the shares from the caller If owner is the sender, sell PT without allowance check Transfer the underlying to the desired receiver Else, sell PT with allowance check Get the allowance of the user spending the tokens Check for sufficient allowance Post maturity If owner is the sender, redeem PT without allowance check Execute the redemption to the desired receiver Get the allowance of the user spending the tokens Check for sufficient allowance
function _withdraw( uint256 a, address r, address o, uint256 m ) internal returns (uint256) { uint256 needed = previewWithdraw(a); if (block.timestamp < maturity) { _transfer(o, address(this), needed); if (o == msg.sender) { uint128 returned = IMarketPlace(marketplace).buyUnderlying( underlying, maturity, Cast.u128(a), Cast.u128(m) ); Safe.transfer(IERC20(underlying), r, a); return returned; uint256 allowance = _allowance[o][msg.sender]; if (allowance < needed) { revert Exception(20, allowance, a, address(0), address(0)); } underlying, maturity, Cast.u128(a), Cast.u128(m) ); return returned; } } else { if (o == msg.sender) { return IRedeemer(redeemer).authRedeem( underlying, maturity, msg.sender, r, needed ); uint256 allowance = _allowance[o][msg.sender]; if (allowance < needed) { revert Exception( 20, allowance, needed, address(0), address(0) ); } IRedeemer(redeemer).authRedeem( underlying, maturity, o, r, needed ); } } }
17,135,319
// SPDX-License-Identifier: MIT pragma solidity ^0.8.2; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import '@openzeppelin/contracts/utils/math/SafeMath.sol'; import "./Base64.sol"; // ____ _____ _ _ ____ _ _ // / __ \ / ____|| | (_) | _ \ | | | | // | | | | _ __ | | | |__ __ _ _ _ __ | |_) || | ___ ___ | | __ ___ // | | | || '_ \ | | | '_ \ / _` || || '_ \ | _ < | | / _ \ / __|| |/ // __| // | |__| || | | || |____ | | | || (_| || || | | || |_) || || (_) || (__ | < \__ \ // \____/ |_| |_| \_____||_| |_| \__,_||_||_| |_||____/ |_| \___/ \___||_|\_\|___/ // contract OnChainBlocks is ERC721, ERC721Enumerable, ERC721Burnable, Ownable { using Counters for Counters.Counter; using SafeMath for uint256; Counters.Counter private _tokenIdCounter; struct BlockData { uint color; } // data structures mapping(uint256 => BlockData[]) private stackData; mapping(uint256 => address) private owners; // mint information uint256 public price = 0.03 ether; uint256 public mintCount; // withdraw addresses address public t1 = 0x1D8fA2D05544cBF0b2fb58A7C1f83947AaD89dE5; address public t2 = 0x533A8D39231Ac2fa36c4018BFf893Ffb4878BC1b; address public t3 = 0x4b2Baea92cE23Ff46aD11F9a5B83e152e8Fa88d7; // supply information uint256 private initialSupply = 10000; uint256 private reservedSupply = 100; // for randomness bytes32 internal salt; // ROY G BIV <3 string[] colors = [ "red", "orange", "yellow", "green", "blue", "indigo", "violet", "white", "black" ]; constructor() ERC721("OnChainBlocks", "OCB") {} modifier Secure() { require(tx.origin == msg.sender, "No interacting from external contracts"); _; salt = keccak256(abi.encodePacked(salt, block.coinbase)); } function mintBlocks(uint256 quantity) Secure public payable { require(quantity > 0 && quantity <= 10, "You can only mint up to 10 blocks per transaction"); require(msg.value >= price * quantity, "Payment amount invalid. Cost = Price * Quantity"); require(_tokenIdCounter.current() + quantity <= initialSupply - reservedSupply, "Exceeds maximum supply" ); for (uint256 i=0; i<quantity; i++) { uint256 colorId = random(colors.length, _tokenIdCounter.current()); stackData[_tokenIdCounter.current()].push(BlockData(colorId)); owners[_tokenIdCounter.current()] = msg.sender; _safeMint(msg.sender, _tokenIdCounter.current()); _tokenIdCounter.increment(); mintCount++; } } function stackBlocks(uint256[] memory blockIds) public { require(blockIds.length > 1 && blockIds.length < 8, "You must provide 2 to 7 tokenIds to stack"); // Make sure the message sender owns all these blocks and that the total height is less than 8 uint totalHeight = 0; for (uint index=0; index<blockIds.length; index++) { for (uint j=0; j<blockIds.length; j++) { if (index != j) { require(blockIds[j] != blockIds[index], "No duplicates allowed!"); } } require(owners[blockIds[index]] == msg.sender, "You don't own this block"); totalHeight += getHeight(blockIds[index]); } require(totalHeight <= 7, "Cannot stack over 7 blocks tall"); uint256 bottomId = blockIds[0]; // Iterate through each stack being stacked on top of bottom stack for (uint i=1; i<blockIds.length; i++) { uint256 selectedId = blockIds[i]; // Iterate through each block in the selected stack for (uint j=0; j<stackData[selectedId].length; j++) { // Add block to bottom stack stackData[bottomId].push(stackData[selectedId][j]); } // Burn top stack once done stacking it delete stackData[selectedId]; _burn(selectedId); } } function giftBlocks(address recipient, uint256 quantity) Secure public onlyOwner { require(quantity > 0, "Quantity must be greater than zero"); require(quantity <= reservedSupply, "Exceeds reserved supply"); for (uint256 i=0; i<quantity; i++) { uint256 colorId = random(colors.length, _tokenIdCounter.current()); stackData[_tokenIdCounter.current()].push(BlockData(colorId)); owners[_tokenIdCounter.current()] = recipient; _safeMint(recipient, _tokenIdCounter.current()); _tokenIdCounter.increment(); } reservedSupply -= quantity; } function generateSvg(uint256 tokenId) public view returns (string memory) { uint height = stackData[tokenId].length; string memory svg = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 420 420" width="420" height="420" shape-rendering="crispEdges">'; string memory currentBlockSvg = ""; for (uint256 i=0; i<height; i++) { currentBlockSvg = string(abi.encodePacked('<svg y="-', Utils.uint2str(i * 50), '"><rect x="120" y="360" width="180" height="60" style="fill:', colors[stackData[tokenId][i].color], '"/><rect x="290" y="360" width="10" height="60"/><rect x="140" y="350" width="20" height="10"/><rect x="180" y="350" width="20" height="10"/><rect x="220" y="350" width="20" height="10"/><rect x="260" y="350" width="20" height="10"/><rect x="280" y="360" width="20" height="10"/><rect x="240" y="360" width="20" height="10"/><rect x="200" y="360" width="20" height="10"/><rect x="160" y="360" width="20" height="10"/><rect x="120" y="360" width="20" height="10"/><rect x="120" y="360" width="10.11" height="60"/></svg>')); svg = string(abi.encodePacked(svg, currentBlockSvg)); } svg = string(abi.encodePacked(svg, '</svg>')); return svg; } function getHeight(uint256 tokenId) public view returns (uint) { return stackData[tokenId].length; } function getStackString(uint id) public view returns (string memory) { string memory result = ""; for (uint i=0; i<stackData[id].length; i++) { result = string(abi.encodePacked(result, Utils.uint2str(stackData[id][i].color))); } return result; } function getMultiStackString(uint[] memory ids) public view returns (string memory) { string memory result = ""; for (uint i=0; i<ids.length; i++) { for (uint j=0; j<stackData[ids[i]].length; j++) { result = string(abi.encodePacked(result, Utils.uint2str(stackData[ids[i]][j].color))); } } return result; } function getAttributes(uint256 tokenId) public view returns (string memory) { // Keep track of each color in this block so we can add a trait for each color string[9] memory colorStrings; bool[9] memory alreadyAdded; uint pointer; for (uint i=0; i<stackData[tokenId].length; i++) { uint color = stackData[tokenId][i].color; // Check if color has already been detected if (alreadyAdded[color] == false) { alreadyAdded[color] = true; colorStrings[pointer] = colors[color]; pointer++; } } // Determine color traits string[9] memory parts; parts[0] = '"attributes": ['; for (uint j=0; j<pointer; j++) { parts[j] = string(abi.encodePacked( '{', string(abi.encodePacked('"trait_type": "', "Color", '",')), string(abi.encodePacked('"value": "', colorStrings[j], '"')), '},' )); } // Determine height trait string memory height = string(abi.encodePacked( '{', string(abi.encodePacked('"trait_type": "', "Height", '",')), string(abi.encodePacked('"value": "', Utils.uint2str(stackData[tokenId].length), '"')), '}' )); // Return attributes json text string memory attributeString = string(abi.encodePacked('"attributes": [', parts[0], parts[1], parts[2], parts[3], parts[4])); attributeString = string(abi.encodePacked(attributeString, parts[5], parts[6], parts[7], parts[8], height, ']')); return attributeString; } function tokenURI(uint256 tokenId) override public view returns (string memory) { string memory svg = generateSvg(tokenId); string memory attributes = getAttributes(tokenId); string memory json = Base64.encode(bytes(string(abi.encodePacked( '{"name": "OnChainBlock #', Utils.uint2str(tokenId), '", "description": "100% on-chain, stackable blocks. No IPFS, no API, all images and metadata exist on the blockchain",', '"image_data": "data:image/svg+xml;base64,', Base64.encode(bytes(svg)), '", ', attributes, '}')))); return string(abi.encodePacked('data:application/json;base64,', json)); } function setPrice(uint256 newPrice) public onlyOwner { price = newPrice; } function setAddresses(address[] memory _t) public onlyOwner { t1 = _t[0]; t2 = _t[1]; t3 = _t[2]; } function withdrawBalance(bool areYouSure) public payable onlyOwner { require(areYouSure == true); uint256 _onePerc = address(this).balance.div(100); uint256 _t1Amt = _onePerc.mul(45); uint256 _t2Amt = _onePerc.mul(45); uint256 _t3Amt = _onePerc.mul(10); require(payable(t1).send(_t1Amt)); require(payable(t2).send(_t2Amt)); require(payable(t3).send(_t3Amt)); } function random(uint mod, uint256 moreSalt) view private returns (uint256) { return uint8(uint256(keccak256(abi.encodePacked(block.timestamp, msg.sender, block.difficulty, salt, moreSalt)))) % mod; } // The following functions are overrides required by Solidity. function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); } function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } } library Utils { function uint2str(uint256 _i) internal pure returns (string memory str) { if (_i == 0) { return "0"; } uint256 j = _i; uint256 length; while (j != 0) { length++; j /= 10; } bytes memory bstr = new bytes(length); uint256 k = length; j = _i; while (j != 0) { bstr[--k] = bytes1(uint8(48 + j % 10)); j /= 10; } str = string(bstr); return str; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0; /// @title Base64 /// @author Brecht Devos - <[email protected]> /// @notice Provides functions for encoding/decoding base64 library Base64 { string internal constant TABLE_ENCODE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; bytes internal constant TABLE_DECODE = hex"0000000000000000000000000000000000000000000000000000000000000000" hex"00000000000000000000003e0000003f3435363738393a3b3c3d000000000000" hex"00000102030405060708090a0b0c0d0e0f101112131415161718190000000000" hex"001a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132330000000000"; function encode(bytes memory data) internal pure returns (string memory) { if (data.length == 0) return ''; // load the table into memory string memory table = TABLE_ENCODE; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((data.length + 2) / 3); // add some extra buffer at the end required for the writing string memory result = new string(encodedLen + 32); assembly { // set the actual output length mstore(result, encodedLen) // prepare the lookup table let tablePtr := add(table, 1) // input ptr let dataPtr := data let endPtr := add(dataPtr, mload(data)) // result ptr, jump over length let resultPtr := add(result, 32) // run over the input, 3 bytes at a time for {} lt(dataPtr, endPtr) {} { // read 3 bytes dataPtr := add(dataPtr, 3) let input := mload(dataPtr) // write 4 characters mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F)))) resultPtr := add(resultPtr, 1) mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F)))) resultPtr := add(resultPtr, 1) mstore8(resultPtr, mload(add(tablePtr, and(shr( 6, input), 0x3F)))) resultPtr := add(resultPtr, 1) mstore8(resultPtr, mload(add(tablePtr, and( input, 0x3F)))) resultPtr := add(resultPtr, 1) } // padding with '=' switch mod(mload(data), 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } } return result; } function decode(string memory _data) internal pure returns (bytes memory) { bytes memory data = bytes(_data); if (data.length == 0) return new bytes(0); require(data.length % 4 == 0, "invalid base64 decoder input"); // load the table into memory bytes memory table = TABLE_DECODE; // every 4 characters represent 3 bytes uint256 decodedLen = (data.length / 4) * 3; // add some extra buffer at the end required for the writing bytes memory result = new bytes(decodedLen + 32); assembly { // padding with '=' let lastBytes := mload(add(data, mload(data))) if eq(and(lastBytes, 0xFF), 0x3d) { decodedLen := sub(decodedLen, 1) if eq(and(lastBytes, 0xFFFF), 0x3d3d) { decodedLen := sub(decodedLen, 1) } } // set the actual output length mstore(result, decodedLen) // prepare the lookup table let tablePtr := add(table, 1) // input ptr let dataPtr := data let endPtr := add(dataPtr, mload(data)) // result ptr, jump over length let resultPtr := add(result, 32) // run over the input, 4 characters at a time for {} lt(dataPtr, endPtr) {} { // read 4 characters dataPtr := add(dataPtr, 4) let input := mload(dataPtr) // write 3 bytes let output := add( add( shl(18, and(mload(add(tablePtr, and(shr(24, input), 0xFF))), 0xFF)), shl(12, and(mload(add(tablePtr, and(shr(16, input), 0xFF))), 0xFF))), add( shl( 6, and(mload(add(tablePtr, and(shr( 8, input), 0xFF))), 0xFF)), and(mload(add(tablePtr, and( input , 0xFF))), 0xFF) ) ) mstore(resultPtr, shl(232, output)) resultPtr := add(resultPtr, 3) } } return result; } } // 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. 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; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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; } } // 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; import "../ERC721.sol"; import "../../../utils/Context.sol"; /** * @title ERC721 Burnable Token * @dev ERC721 Token that can be irreversibly burned (destroyed). */ abstract contract ERC721Burnable is Context, ERC721 { /** * @dev Burns `tokenId`. See {ERC721-_burn}. * * Requirements: * * - The caller must own `tokenId` or be an approved operator. */ function burn(uint256 tokenId) public virtual { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved"); _burn(tokenId); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721.sol"; import "./IERC721Enumerable.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. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // 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(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); 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) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); 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 = ERC721.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 = ERC721.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(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.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 {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @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); } // 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; 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 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); } } // 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; 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); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.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); } // 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/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; /** * @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); }
Keep track of each color in this block so we can add a trait for each color Check if color has already been detected
function getAttributes(uint256 tokenId) public view returns (string memory) { string[9] memory colorStrings; bool[9] memory alreadyAdded; uint pointer; for (uint i=0; i<stackData[tokenId].length; i++) { uint color = stackData[tokenId][i].color; if (alreadyAdded[color] == false) { alreadyAdded[color] = true; colorStrings[pointer] = colors[color]; pointer++; } } parts[0] = '"attributes": ['; for (uint j=0; j<pointer; j++) { parts[j] = string(abi.encodePacked( '{', string(abi.encodePacked('"trait_type": "', "Color", '",')), string(abi.encodePacked('"value": "', colorStrings[j], '"')), '},' )); } '{', string(abi.encodePacked('"trait_type": "', "Height", '",')), string(abi.encodePacked('"value": "', Utils.uint2str(stackData[tokenId].length), '"')), '}' )); attributeString = string(abi.encodePacked(attributeString, parts[5], parts[6], parts[7], parts[8], height, ']')); return attributeString; }
14,559,588
./full_match/1/0xCf3b485bd11BCa74103D7D3534503bAD3fbdaC6d/sources/contracts/JBFundingCycleStore.sol
/ If there's not yet a funding cycle for the project, initialize one. Use an empty funding cycle as the base. Get the active funding cycle's configuration. If an eligible funding cycle does not exist, get a reference to the latest funding cycle configuration for the project. Get the latest funding cycle's configuration. Get a reference to the funding cycle. If it hasn't been approved or hasn't yet started, set the ID to be the funding cycle it's based on, which carries the latest approved configuration. The configuration can't be the same as the base configuration. The time after the ballot of the provided funding cycle has expired. If the provided funding cycle has no ballot, return the current timestamp. Can only start after the ballot.
function _configureIntrinsicPropertiesFor( uint256 _projectId, uint256 _configuration, uint256 _weight, uint256 _mustStartAtOrAfter ) private { if (latestConfigurationOf[_projectId] == 0) return _initFor(_projectId, _getStructFor(0, 0), _configuration, _mustStartAtOrAfter, _weight); uint256 _currentConfiguration = _eligibleOf(_projectId); if (_currentConfiguration == 0) _currentConfiguration = latestConfigurationOf[_projectId]; JBFundingCycle memory _baseFundingCycle = _getStructFor(_projectId, _currentConfiguration); if (!_isApproved(_projectId, _baseFundingCycle) || block.timestamp < _baseFundingCycle.start) _baseFundingCycle = _getStructFor(_projectId, _baseFundingCycle.basedOn); if (_baseFundingCycle.configuration == _configuration) revert NO_SAME_BLOCK_RECONFIGURATION(); uint256 _timestampAfterBallot = _baseFundingCycle.ballot == IJBFundingCycleBallot(address(0)) ? 0 : _configuration + _baseFundingCycle.ballot.duration(); _initFor( _projectId, _baseFundingCycle, _configuration, _timestampAfterBallot > _mustStartAtOrAfter ? _timestampAfterBallot : _mustStartAtOrAfter, _weight ); } Initializes a funding cycle with the specified properties. @param _projectId The ID of the project to which the funding cycle being initialized belongs. @param _baseFundingCycle The funding cycle to base the initialized one on. @param _configuration The configuration of the funding cycle being initialized. @param _mustStartAtOrAfter The time before which the initialized funding cycle cannot start. @param _weight The weight to give the newly initialized funding cycle.
17,049,544
/** * SPDX-License-Identifier: LicenseRef-Aktionariat * * MIT License with Automated License Fee Payments * * Copyright (c) 2020 Aktionariat AG (aktionariat.com) * * Permission is hereby granted to any person obtaining a copy of this software * and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies of the * Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * - The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * - All automated license fee payments integrated into this and related Software * are preserved. * * 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 OR COPYRIGHT HOLDERS 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. */ pragma solidity ^0.8.0; import "../ERC20/extensions/ERC20Named.sol"; import "../recovery/ERC20Recoverable.sol"; import "../interfaces/IERC677Receiver.sol"; /** * @title CompanyName AG Shares * @author Luzius Meisser, [email protected] * * These tokens represent ledger-based securities according to article 973d of the Swiss Code of Obligations. * This smart contract serves as an ownership registry, enabling the token holders to register them as * shareholders in the issuer's shareholder registry. This is equivalent to the traditional system * of having physical share certificates kept at home by the shareholders and a shareholder registry run by * the company. Just like with physical certificates, the owners of the tokens are the owners of the shares. * However, in order to exercise their rights (for example receive a dividend), shareholders must register * themselves. For example, in case the company pays out a dividend to a previous shareholder because * the current shareholder did not register, the company cannot be held liable for paying the dividend to * the "wrong" shareholder. In relation to the company, only the registered shareholders count as such. */ contract Shares is ERC20Recoverable, ERC20Named { string public terms; uint256 public totalShares = 0; // total number of shares, maybe not all tokenized uint256 public invalidTokens = 0; event Announcement(string message); event TokensDeclaredInvalid(address indexed holder, uint256 amount, string message); constructor( string memory _symbol, string memory _name, string memory _terms, uint256 _totalShares, address _owner, address _recoveryHub ) ERC20Named(_owner, _name, _symbol, 0) ERC20Recoverable(_recoveryHub) { totalShares = _totalShares; terms = _terms; } function setTerms(string memory _terms) external onlyOwner { terms = _terms; } /** * Declares the number of total shares, including those that have not been tokenized and those * that are held by the company itself. This number can be substiantially higher than totalSupply() * in case not all shares have been tokenized. Also, it can be lower than totalSupply() in case some * tokens have become invalid. */ function setTotalShares(uint256 _newTotalShares) external onlyOwner() { require(_newTotalShares >= totalValidSupply(), "below supply"); totalShares = _newTotalShares; } /** * Allows the issuer to make public announcements that are visible on the blockchain. */ function announcement(string calldata message) external onlyOwner() { emit Announcement(message); } /** * See parent method for collateral requirements. */ function setCustomClaimCollateral(address collateral, uint256 rate) external onlyOwner() { super._setCustomClaimCollateral(collateral, rate); } function getClaimDeleter() public virtual override view returns (address) { return owner; } /** * Signals that the indicated tokens have been declared invalid (e.g. by a court ruling in accordance * with article 973g of the Swiss Code of Obligations) and got detached from * the underlying shares. Invalid tokens do not carry any shareholder rights any more. * * This function is purely declarative. It does not technically immobilize the affected tokens as * that would give the issuer too much power. */ function declareInvalid(address holder, uint256 amount, string calldata message) external onlyOwner() { uint256 holderBalance = balanceOf(holder); require(amount <= holderBalance); invalidTokens += amount; emit TokensDeclaredInvalid(holder, amount, message); } /** * The total number of valid tokens in circulation. In case some tokens have been declared invalid, this * number might be lower than totalSupply(). Also, it will always be lower than or equal to totalShares(). */ function totalValidSupply() public view returns (uint256) { return totalSupply() - invalidTokens; } /** * Allows the company to tokenize shares. If these shares are newly created, setTotalShares must be * called first in order to adjust the total number of shares. */ function mintAndCall(address shareholder, address callee, uint256 amount, bytes calldata data) external { mint(callee, amount); IERC677Receiver(callee).onTokenTransfer(shareholder, amount, data); } function mint(address target, uint256 amount) public onlyOwner { _mint(target, amount); } function _mint(address account, uint256 amount) internal virtual override { require(totalValidSupply() + amount <= totalShares, "total"); super._mint(account, amount); } function transfer(address to, uint256 value) virtual override(ERC20Recoverable, ERC20Flaggable) public returns (bool) { return super.transfer(to, value); } /** * Transfers _amount tokens to the company and burns them. * The meaning of this operation depends on the circumstances and the fate of the shares does * not necessarily follow the fate of the tokens. For example, the company itself might call * this function to implement a formal decision to destroy some of the outstanding shares. * Also, this function might be called by an owner to return the shares to the company and * get them back in another form under an according agreement (e.g. printed certificates or * tokens on a different blockchain). It is not recommended to call this function without * having agreed with the company on the further fate of the shares in question. */ function burn(uint256 _amount) external { require(_amount <= balanceOf(msg.sender), "balance"); _transfer(msg.sender, address(this), _amount); _burn(address(this), _amount); } }
Declares the number of total shares, including those that have not been tokenized and those that are held by the company itself. This number can be substiantially higher than totalSupply() in case not all shares have been tokenized. Also, it can be lower than totalSupply() in case some tokens have become invalid./
function setTotalShares(uint256 _newTotalShares) external onlyOwner() { require(_newTotalShares >= totalValidSupply(), "below supply"); totalShares = _newTotalShares; }
12,639,255
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../interfaces/IUniswapV2Router.sol"; import "../interfaces/IBPool.sol"; import "../interfaces/IBoardroom.sol"; import "../interfaces/IShare.sol"; import "../interfaces/ITreasury.sol"; import "../interfaces/IOracle.sol"; import "../interfaces/IShareRewardPool.sol"; import "../interfaces/IPancakeswapPool.sol"; /** * @dev This contract will collect vesting Shares, stake to the Boardroom and rebalance MEE, BUSD, WBNB according to DAO. */ contract CommunityFund { using SafeERC20 for IERC20; using SafeMath for uint256; /* ========== STATE VARIABLES ========== */ // governance address public operator; // flags bool public initialized = false; bool public publicAllowed; // set to true to allow public to call rebalance() // price uint256 public meePriceToSell; // to rebalance when expansion uint256 public meePriceToBuy; // to rebalance when contraction address public mee = address(0x35e869B7456462b81cdB5e6e42434bD27f3F788c); address public share = address(0x242E46490397ACCa94ED930F2C4EdF16250237fa); address public bond = address(0xCaD2109CC2816D47a796cB7a0B57988EC7611541); address public busd = address(0xe9e7CEA3DedcA5984780Bafc599bD69ADd087D56); address public usdt = address(0x55d398326f99059fF775485246999027B3197955); address public bdo = address(0x190b589cf9Fb8DDEabBFeae36a813FFb2A702454); address public bcash = address(0xc2161d47011C4065648ab9cDFd0071094228fa09); address public wbnb = address(0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c); address public boardroom = address(0xFF0b41ad7a85430FEbBC5220fd4c7a68013F2C0d); address public meeOracle = address(0x26593B4E6a803aac7f39955bd33C6826f266D7Fc); address public treasury = address(0xD3372603Db4087FF5D797F91839c0Ca6b9aF294a); // Pancakeswap IUniswapV2Router public pancakeRouter = IUniswapV2Router(0x05fF2B0DB69458A0750badebc4f9e13aDd608C7F); mapping(address => mapping(address => address[])) public uniswapPaths; // DAO parameters - https://docs.wantanmee.finance/DAO uint256[] public expansionPercent; uint256[] public contractionPercent; address public strategist; mapping(address => uint256) public maxAmountToTrade; // MEE, BUSD, WBNB address public shareRewardPool = address(0xecC17b190581C60811862E5dF8c9183dA98BD08a); mapping(address => uint256) public shareRewardPoolId; // [BUSD, USDT, BDO, bCash] -> [Pool_id]: 0, 1, 3, 4 mapping(address => address) public lpPairAddress; // [BUSD, USDT, BDO, bCash] -> [LP]: 0xD65F81878517039E39c359434d8D8bD46CC4531F, 0xd245BDb115707730136F0459e2aa9b0b19023724, ... /* =================== Added variables (need to keep orders for proxy to work) =================== */ //// TO BE ADDED /* ========== EVENTS ========== */ event Initialized(address indexed executor, uint256 at); event SwapToken(address inputToken, address outputToken, uint256 amount); event BoughtBonds(uint256 amount); event RedeemedBonds(uint256 amount); event ExecuteTransaction(address indexed target, uint256 value, string signature, bytes data); /* ========== Modifiers =============== */ modifier onlyOperator() { require(operator == msg.sender, "!operator"); _; } modifier onlyStrategist() { require(strategist == msg.sender || operator == msg.sender, "!strategist"); _; } modifier notInitialized() { require(!initialized, "initialized"); _; } modifier checkPublicAllow() { require(publicAllowed || msg.sender == operator, "!operator nor !publicAllowed"); _; } /* ========== GOVERNANCE ========== */ function initialize( address _mee, address _bond, address _share, address _busd, address _wbnb, address _boardroom, address _meeOracle, address _treasury, IUniswapV2Router _pancakeRouter ) public notInitialized { mee = _mee; bond = _bond; share = _share; busd = _busd; wbnb = _wbnb; boardroom = _boardroom; meeOracle = _meeOracle; treasury = _treasury; pancakeRouter = _pancakeRouter; meePriceToSell = 1500 finney; // $1.5 meePriceToBuy = 800 finney; // $0.8 expansionPercent = [3000, 6800, 200]; // mee (30%), BUSD (68%), WBNB (2%) during expansion period contractionPercent = [8800, 1160, 40]; // mee (88%), BUSD (11.6%), WBNB (0.4%) during contraction period publicAllowed = true; initialized = true; operator = msg.sender; strategist = msg.sender; emit Initialized(msg.sender, block.number); } function setOperator(address _operator) external onlyOperator { operator = _operator; } function setStrategist(address _strategist) external onlyOperator { strategist = _strategist; } function setTreasury(address _treasury) external onlyOperator { treasury = _treasury; } function setShareRewardPool(address _shareRewardPool) external onlyOperator { shareRewardPool = _shareRewardPool; } function setShareRewardPoolId(address _tokenB, uint256 _pid) external onlyStrategist { shareRewardPoolId[_tokenB] = _pid; } function setLpPairAddress(address _tokenB, address _lpAdd) external onlyStrategist { lpPairAddress[_tokenB] = _lpAdd; } function setDollarOracle(address _meeOracle) external onlyOperator { meeOracle = _meeOracle; } function setPublicAllowed(bool _publicAllowed) external onlyStrategist { publicAllowed = _publicAllowed; } function setExpansionPercent(uint256 _meePercent, uint256 _busdPercent, uint256 _wbnbPercent) external onlyStrategist { require(_meePercent.add(_busdPercent).add(_wbnbPercent) == 10000, "!100%"); expansionPercent[0] = _meePercent; expansionPercent[1] = _busdPercent; expansionPercent[2] = _wbnbPercent; } function setContractionPercent(uint256 _meePercent, uint256 _busdPercent, uint256 _wbnbPercent) external onlyStrategist { require(_meePercent.add(_busdPercent).add(_wbnbPercent) == 10000, "!100%"); contractionPercent[0] = _meePercent; contractionPercent[1] = _busdPercent; contractionPercent[2] = _wbnbPercent; } function setMaxAmountToTrade(uint256 _meeAmount, uint256 _busdAmount, uint256 _wbnbAmount) external onlyStrategist { maxAmountToTrade[mee] = _meeAmount; maxAmountToTrade[busd] = _busdAmount; maxAmountToTrade[wbnb] = _wbnbAmount; } function setDollarPriceToSell(uint256 _meePriceToSell) external onlyStrategist { require(_meePriceToSell >= 950 finney && _meePriceToSell <= 2000 finney, "out of range"); // [$0.95, $2.00] meePriceToSell = _meePriceToSell; } function setDollarPriceToBuy(uint256 _meePriceToBuy) external onlyStrategist { require(_meePriceToBuy >= 500 finney && _meePriceToBuy <= 1050 finney, "out of range"); // [$0.50, $1.05] meePriceToBuy = _meePriceToBuy; } function setUnirouterPath(address _input, address _output, address[] memory _path) external onlyStrategist { uniswapPaths[_input][_output] = _path; } function setTokenAddresses(address _busd, address _usdt, address _bdo, address _bcash, address _wbnb) external onlyOperator { busd = _busd; usdt = _usdt; bdo = _bdo; bcash = _bcash; wbnb = _wbnb; } function withdrawShare(uint256 _amount) external onlyStrategist { IBoardroom(boardroom).withdraw(_amount); } function exitBoardroom() external onlyStrategist { IBoardroom(boardroom).exit(); } function grandFund(address _token, uint256 _amount, address _to) external onlyOperator { IERC20(_token).transfer(_to, _amount); } /* ========== VIEW FUNCTIONS ========== */ function earned() public view returns (uint256) { return IBoardroom(boardroom).earned(address(this)); } function tokenBalances() public view returns (uint256 _meeBal, uint256 _busdBal, uint256 _wbnbBal, uint256 _totalBal) { _meeBal = IERC20(mee).balanceOf(address(this)); _busdBal = IERC20(busd).balanceOf(address(this)); _wbnbBal = IERC20(wbnb).balanceOf(address(this)); _totalBal = _meeBal.add(_busdBal).add(_wbnbBal); } function tokenPercents() public view returns (uint256 _meePercent, uint256 _busdPercent, uint256 _wbnbPercent) { (uint256 _meeBal, uint256 _busdBal, uint256 _wbnbBal, uint256 _totalBal) = tokenBalances(); if (_totalBal > 0) { _meePercent = _meeBal.mul(10000).div(_totalBal); _busdPercent = _busdBal.mul(10000).div(_totalBal); _wbnbPercent = _wbnbBal.mul(10000).div(_totalBal); } } function getEthPrice() public view returns (uint256 meePrice) { try IOracle(meeOracle).consult(mee, 1e18) returns (uint144 price) { return uint256(price); } catch { revert("failed to consult price"); } } function getEthUpdatedPrice() public view returns (uint256 _meePrice) { try IOracle(meeOracle).twap(mee, 1e18) returns (uint144 price) { return uint256(price); } catch { revert("failed to consult price"); } } /* ========== MUTATIVE FUNCTIONS ========== */ function collectShareRewards() public checkPublicAllow { if (IShare(share).unclaimedTreasuryFund() > 0) { IShare(share).claimRewards(); } } function claimAndRestake() public checkPublicAllow { if (IBoardroom(boardroom).canClaimReward(address(this))) {// only restake more if at this epoch we could claim pending mee rewards if (earned() > 0) { IBoardroom(boardroom).claimReward(); } uint256 _shareBal = IERC20(share).balanceOf(address(this)); if (_shareBal > 0) { IERC20(share).safeApprove(boardroom, 0); IERC20(share).safeApprove(boardroom, _shareBal); IBoardroom(boardroom).stake(_shareBal); } } } function rebalance() public checkPublicAllow { (uint256 _meeBal, uint256 _busdBal, uint256 _wbnbBal, uint256 _totalBal) = tokenBalances(); if (_totalBal > 0) { uint256 _meePercent = _meeBal.mul(10000).div(_totalBal); uint256 _busdPercent = _busdBal.mul(10000).div(_totalBal); uint256 _wbnbPercent = _wbnbBal.mul(10000).div(_totalBal); uint256 _meePrice = getEthUpdatedPrice(); if (_meePrice >= meePriceToSell) {// expansion: sell MEE if (_meePercent > expansionPercent[0]) { uint256 _sellingMee = _meeBal.mul(_meePercent.sub(expansionPercent[0])).div(10000); if (_busdPercent >= expansionPercent[1]) {// enough BUSD if (_wbnbPercent < expansionPercent[2]) {// short of WBNB: buy WBNB _swapToken(mee, wbnb, _sellingMee); } else { if (_busdPercent.sub(expansionPercent[1]) <= _wbnbPercent.sub(expansionPercent[2])) {// has more WBNB than BUSD: buy BUSD _swapToken(mee, busd, _sellingMee); } else {// has more BUSD than WBNB: buy WBNB _swapToken(mee, wbnb, _sellingMee); } } } else {// short of BUSD if (_wbnbPercent >= expansionPercent[2]) {// enough WBNB: buy BUSD _swapToken(mee, busd, _sellingMee); } else {// short of WBNB uint256 _sellingMeeToBusd = _sellingMee.div(2); _swapToken(mee, busd, _sellingMeeToBusd); _swapToken(mee, wbnb, _sellingMee.sub(_sellingMeeToBusd)); } } } } else if (_meePrice <= meePriceToBuy && (msg.sender == operator || msg.sender == strategist)) {// contraction: buy MEE if (_busdPercent >= contractionPercent[1]) {// enough BUSD if (_wbnbPercent <= contractionPercent[2]) {// short of WBNB: sell BUSD uint256 _sellingBUSD = _busdBal.mul(_busdPercent.sub(contractionPercent[1])).div(10000); _swapToken(busd, mee, _sellingBUSD); } else { if (_busdPercent.sub(contractionPercent[1]) > _wbnbPercent.sub(contractionPercent[2])) {// has more BUSD than WBNB: sell BUSD uint256 _sellingBUSD = _busdBal.mul(_busdPercent.sub(contractionPercent[1])).div(10000); _swapToken(busd, mee, _sellingBUSD); } else {// has more WBNB than BUSD: sell WBNB uint256 _sellingWBNB = _wbnbBal.mul(_wbnbPercent.sub(contractionPercent[2])).div(10000); _swapToken(wbnb, mee, _sellingWBNB); } } } else {// short of BUSD if (_wbnbPercent > contractionPercent[2]) {// enough WBNB: sell WBNB uint256 _sellingWBNB = _wbnbBal.mul(_wbnbPercent.sub(contractionPercent[2])).div(10000); _swapToken(wbnb, mee, _sellingWBNB); } } } } } function workForDaoFund() external checkPublicAllow { collectShareRewards(); claimAllRewardFromSharePool(); claimAndRestake(); rebalance(); } function buyBonds(uint256 _meeAmount) external onlyStrategist { uint256 _meePrice = ITreasury(treasury).getEthPrice(); ITreasury(treasury).buyBonds(_meeAmount, _meePrice); emit BoughtBonds(_meeAmount); } function redeemBonds(uint256 _bondAmount) external onlyStrategist { uint256 _meePrice = ITreasury(treasury).getEthPrice(); ITreasury(treasury).redeemBonds(_bondAmount, _meePrice); emit RedeemedBonds(_bondAmount); } function forceSell(address _buyingToken, uint256 _meeAmount) external onlyStrategist { require(getEthUpdatedPrice() >= meePriceToBuy, "price is too low to sell"); _swapToken(mee, _buyingToken, _meeAmount); } function forceBuy(address _sellingToken, uint256 _sellingAmount) external onlyStrategist { require(getEthUpdatedPrice() <= meePriceToSell, "price is too high to buy"); _swapToken(_sellingToken, mee, _sellingAmount); } function trimNonCoreToken(address _sellingToken) public onlyStrategist { require(_sellingToken != mee && _sellingToken != bond && _sellingToken != share && _sellingToken != busd && _sellingToken != wbnb, "core"); uint256 _bal = IERC20(_sellingToken).balanceOf(address(this)); if (_bal > 0) { _swapToken(_sellingToken, mee, _bal); } } function _swapToken(address _inputToken, address _outputToken, uint256 _amount) internal { if (_amount == 0) return; uint256 _maxAmount = maxAmountToTrade[_inputToken]; if (_maxAmount > 0 && _maxAmount < _amount) { _amount = _maxAmount; } address[] memory _path = uniswapPaths[_inputToken][_outputToken]; if (_path.length == 0) { _path = new address[](2); _path[0] = _inputToken; _path[1] = _outputToken; } IERC20(_inputToken).safeApprove(address(pancakeRouter), 0); IERC20(_inputToken).safeApprove(address(pancakeRouter), _amount); pancakeRouter.swapExactTokensForTokens(_amount, 1, _path, address(this), now.add(1800)); } function _addLiquidity(address _tokenB, uint256 _amountADesired) internal { // tokenA is always MEE _addLiquidity2(mee, _tokenB, _amountADesired, IERC20(_tokenB).balanceOf(address(this))); } function _removeLiquidity(address _lpAdd, address _tokenB, uint256 _liquidity) internal { // tokenA is always MEE _removeLiquidity2(_lpAdd, mee, _tokenB, _liquidity); } function _addLiquidity2(address _tokenA, address _tokenB, uint256 _amountADesired, uint256 amountBDesired) internal { IERC20(_tokenA).safeApprove(address(pancakeRouter), 0); IERC20(_tokenA).safeApprove(address(pancakeRouter), type(uint256).max); IERC20(_tokenB).safeApprove(address(pancakeRouter), 0); IERC20(_tokenB).safeApprove(address(pancakeRouter), type(uint256).max); // addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin, to, deadline) pancakeRouter.addLiquidity(_tokenA, _tokenB, _amountADesired, amountBDesired, 0, 0, address(this), now.add(1800)); } function _removeLiquidity2(address _lpAdd, address _tokenA, address _tokenB, uint256 _liquidity) internal { IERC20(_lpAdd).safeApprove(address(pancakeRouter), 0); IERC20(_lpAdd).safeApprove(address(pancakeRouter), _liquidity); // removeLiquidity(tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline) pancakeRouter.removeLiquidity(_tokenA, _tokenB, _liquidity, 1, 1, address(this), now.add(1800)); } /* ========== PROVIDE LP AND STAKE TO SHARE POOL ========== */ function depositToSharePool(address _tokenB, uint256 _meeAmount) external onlyStrategist { address _lpAdd = lpPairAddress[_tokenB]; uint256 _before = IERC20(_lpAdd).balanceOf(address(this)); _addLiquidity(_tokenB, _meeAmount); uint256 _after = IERC20(_lpAdd).balanceOf(address(this)); uint256 _lpBal = _after.sub(_before); require(_lpBal > 0, "!_lpBal"); address _shareRewardPool = shareRewardPool; uint256 _pid = shareRewardPoolId[_tokenB]; IERC20(_lpAdd).safeApprove(_shareRewardPool, 0); IERC20(_lpAdd).safeApprove(_shareRewardPool, _lpBal); IShareRewardPool(_shareRewardPool).deposit(_pid, _lpBal); } function withdrawFromSharePool(address _tokenB, uint256 _lpAmount) public onlyStrategist { address _lpAdd = lpPairAddress[_tokenB]; address _shareRewardPool = shareRewardPool; uint256 _pid = shareRewardPoolId[_tokenB]; IShareRewardPool(_shareRewardPool).withdraw(_pid, _lpAmount); _removeLiquidity(_lpAdd, _tokenB, _lpAmount); } function exitSharePool(address _tokenB) public onlyStrategist { (uint _stakedAmount,) = IShareRewardPool(shareRewardPool).userInfo(shareRewardPoolId[_tokenB], address(this)); withdrawFromSharePool(_tokenB, _stakedAmount); } function exitAllSharePool() external { if (stakeAmountFromSharePool(busd) > 0) exitSharePool(busd); if (stakeAmountFromSharePool(wbnb) > 0) exitSharePool(wbnb); } function claimRewardFromSharePool(address _tokenB) public { uint256 _pid = shareRewardPoolId[_tokenB]; IShareRewardPool(shareRewardPool).withdraw(_pid, 0); } function claimAllRewardFromSharePool() public { if (pendingFromSharePool(busd) > 0) claimRewardFromSharePool(busd); if (pendingFromSharePool(wbnb) > 0) claimRewardFromSharePool(wbnb); } function pendingFromSharePool(address _tokenB) public view returns(uint256) { return IShareRewardPool(shareRewardPool).pendingShare(shareRewardPoolId[_tokenB], address(this)); } function pendingAllFromSharePool() public view returns(uint256) { return pendingFromSharePool(busd).add(pendingFromSharePool(wbnb)); } function stakeAmountFromSharePool(address _tokenB) public view returns(uint256 _stakedAmount) { (_stakedAmount, ) = IShareRewardPool(shareRewardPool).userInfo(shareRewardPoolId[_tokenB], address(this)); } function stakeAmountAllFromSharePool() public view returns(uint256 _bnbPoolStakedAmount, uint256 _wbnbPoolStakedAmount) { _bnbPoolStakedAmount = stakeAmountFromSharePool(busd); _wbnbPoolStakedAmount = stakeAmountFromSharePool(wbnb); } /* ========== EMERGENCY ========== */ function executeTransaction(address target, uint256 value, string memory signature, bytes memory data) public onlyOperator returns (bytes memory) { bytes memory callData; if (bytes(signature).length == 0) { callData = data; } else { callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data); } // solium-disable-next-line security/no-call-value (bool success, bytes memory returnData) = target.call{value: value}(callData); require(success, string("CommunityFund::executeTransaction: Transaction execution reverted.")); emit ExecuteTransaction(target, value, signature, data); return returnData; } receive() external payable {} }
tokenA is always MEE
function _removeLiquidity(address _lpAdd, address _tokenB, uint256 _liquidity) internal { _removeLiquidity2(_lpAdd, mee, _tokenB, _liquidity); }
12,793,423
./full_match/80001/0x88fa272fE8685B4E73D4590bdcA70A5B901F7Ebc/sources/contracts/BraleToken.sol
For `ControlledAccessType.Allow`, returns `true` if `account` has been granted {CONTROLLED_ACCESS_ROLE}. For `ControlledAccessType.Deny`, returns `true` if `account` has not been granted {CONTROLLED_ACCESS_ROLE}./
function isAllowed(address account) external view returns (bool) { if (controlledAccessType == ControlledAccessType.Allow) { return hasRole(CONTROLLED_ACCESS_ROLE, account); return !hasRole(CONTROLLED_ACCESS_ROLE, account); } }
5,576,372
./full_match/5/0x0ABfb5e7b5f6B96A2d1717226740E145aeBC95eD/sources/contracts/CrowdFunding.sol
gets all the campaigns available
function getCampaigns() public view returns (Campaign[] memory) { Campaign[] memory allCampaigns = new Campaign[](numberOfCampaigns); for (uint i = 0; i < numberOfCampaigns; i++){ Campaign storage item = campaigns[i]; allCampaigns[i] = item; } return allCampaigns; }
1,935,100
pragma solidity ^0.6.0; 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) { // 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; } 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) { // 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; } 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; } } interface IBEP20 { /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Returns the token decimals. */ function decimals() external view returns (uint8); /** * @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 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 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 from, address to, uint256 value ) external returns (bool ok); } contract Ico { using SafeMath for uint256; IBEP20 public TOKEN; address payable public owner; uint256 public startDate; // ico sale start date uint256 public endDate; // ico sale end date uint256 public totalAmount; // total token amount to sell uint256 public minPerTransaction; // min amount per transaction uint256 public maxPerUser; // max amount per user uint256 public soldAmount; // token amount sold so far uint256 public tokenPrice; // token amount per 1 bnb mapping(address => uint256) public tokenPerAddresses; uint256 public constant DEFAULT_DECIMALS = 10 ** 18; event tokensBought(address indexed user, uint256 amountSpent, uint256 amountBought, string tokenName, uint256 date); event tokensClaimed(address indexed user, uint256 amount, uint256 date); event OwnershipTransferred(address prevOwner, address newOwner); event SetStartDate(uint256 prevDate, uint256 newDate); event SetEndDate(uint256 prevDate, uint256 newDate); event IcoEnded(); event SetTotalAmount(uint256 _prevAmount, uint256 newAmount); event SetMaxPerUser(uint256 _prevValue, uint256 newValue); event SetMinPerTransaction(uint256 _prevValue, uint256 newValue); event SetTokenPrice(uint256 _prevPrice, uint256 newPrice); event CollectPaidFunds(address owner, uint256 amount); event CollectRemainedTokens(address owner, uint256 amount); modifier validate(uint256 buyAmount) { require(now >= startDate && now < endDate, 'Ico time mismatch'); require(buyAmount >= minPerTransaction, "Too small amount"); require( buyAmount > 0 && buyAmount <= remainedTokenAmount(), 'Insufficient buy amount' ); _; } modifier onlyOwner { require(msg.sender == owner, "Forbidden"); _; } constructor( IBEP20 _TOKEN ) public { owner = msg.sender; emit OwnershipTransferred(address(0), owner); TOKEN = _TOKEN; } // Function to buy TOKEN using BNB token function buyWithBNB(uint256 buyAmount) public payable validate(buyAmount) { uint256 amount = calculateBNBAmount(buyAmount); require(msg.value >= amount, 'Insufficient BNB balance'); uint256 sumSoFar = tokenPerAddresses[msg.sender].add(buyAmount); require(maxPerUser == 0 || sumSoFar <= maxPerUser, 'Exceeds the maximum buyable amount'); tokenPerAddresses[msg.sender] = sumSoFar; soldAmount = soldAmount.add(buyAmount); emit tokensBought(msg.sender, amount, buyAmount, 'BNB', now); } // Function to claim function claimToken() external { require(now >= endDate, "Ico not ended yet"); uint256 claimableAmount = tokenPerAddresses[msg.sender]; require(claimableAmount > 0, "Nothing to claim"); TOKEN.transfer(msg.sender, claimableAmount); tokenPerAddresses[msg.sender] = 0; emit tokensClaimed(msg.sender, claimableAmount, now); } // function to change the owner // only owner can call this function function changeOwner(address payable _owner) public onlyOwner { emit OwnershipTransferred(owner, _owner); owner = _owner; } // function to set the ico start date // only owner can call this function function setStartDate(uint256 _startDate) external onlyOwner { require(now < startDate && now < _startDate, "Past date can not be set"); require(_startDate < endDate, "Must be before then the end date"); require(startDate != _startDate, "Same value already set"); emit SetStartDate(startDate, _startDate); startDate = _startDate; } // function to set the presale end date // only owner can call this function function setEndDate(uint256 _endDate) public onlyOwner { require(startDate < _endDate, "End date should be after start date"); require(now < _endDate, "Past date can not be set"); require(endDate != _endDate, "Same value already set"); emit SetEndDate(endDate, _endDate); endDate = _endDate; } // function to set the total tokens to sell // only owner can call this function function setTotalAmount(uint256 _totalAmount) external onlyOwner { require(_totalAmount >= soldAmount, "More amount already sold"); require(totalAmount != _totalAmount, "Same value already set"); emit SetTotalAmount(totalAmount, _totalAmount); totalAmount = _totalAmount; } // function to set the minimal transaction amount // only owner can call this function function setMinPerTransaction(uint256 _minPerTransaction) external onlyOwner { require(_minPerTransaction <= maxPerUser, "Min per transaction must be less than max per user"); require(minPerTransaction != _minPerTransaction, "Same value already set"); emit SetMinPerTransaction(minPerTransaction, _minPerTransaction); minPerTransaction = _minPerTransaction; } // function to set the maximum amount which a user can buy // only owner can call this function function setMaxPerUser(uint256 _maxPerUser) external onlyOwner { require(minPerTransaction <= _maxPerUser, "Max per user must be more than min per transaction"); require(maxPerUser != _maxPerUser, "Same value already set"); emit SetMaxPerUser(maxPerUser, _maxPerUser); maxPerUser = _maxPerUser; } // function to end the ico // only owner can call this function function endIco() external onlyOwner { require(now < endDate, "Already ended"); endDate = now; emit IcoEnded(); } // function to withdraw paid funds. // only owner can call this function function collectPaidFunds() external onlyOwner { require(now >= endDate, "Ico not ended"); uint256 balance = address(this).balance; require(balance > 0, "Insufficient balance"); owner.transfer(balance); emit CollectPaidFunds(owner, balance); } // function to withdraw unsold tokens // only owner can call this function function collectRemainedTokens() public onlyOwner { require(now >= endDate, "Ico not ended"); uint256 remainedTokens = remainedTokenAmount(); require(remainedTokens > 0, "No remained tokens"); TOKEN.transfer(owner, remainedTokens); emit CollectRemainedTokens(owner, remainedTokens); } //function to return the amount of unsold tokens function remainedTokenAmount() public view returns (uint256) { return TOKEN.balanceOf(address(this)); } // function to set token amount per 1 bnb function setTokenPrice(uint256 _tokenPrice) public onlyOwner { require(_tokenPrice > 0, "Invalid token price"); require(now < startDate, "Ico started already"); require(tokenPrice != _tokenPrice, ""); emit SetTokenPrice(tokenPrice, _tokenPrice); tokenPrice = _tokenPrice; } // function to calculate the quantity of TOKEN based on the TOKEN price of bnbAmount function calculateTokenAmount(uint256 bnbAmount) public view returns (uint256) { uint256 tokenAmount = tokenPrice.mul(bnbAmount).div(DEFAULT_DECIMALS); return tokenAmount; } //function to calculate the quantity of bnb needed using its TOKEN price to buy `buyAmount` of TOKEN function calculateBNBAmount(uint256 tokenAmount) public view returns (uint256) { require(tokenPrice > 0, "TOKEN price per BNB should be greater than 0"); uint256 bnbAmount = tokenAmount.mul(DEFAULT_DECIMALS).div(tokenPrice); return bnbAmount; } }
function to set the total tokens to sell only owner can call this function
function setTotalAmount(uint256 _totalAmount) external onlyOwner { require(_totalAmount >= soldAmount, "More amount already sold"); require(totalAmount != _totalAmount, "Same value already set"); emit SetTotalAmount(totalAmount, _totalAmount); totalAmount = _totalAmount; }
13,120,543
pragma solidity >=0.5.0; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath#mul: OVERFLOW"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath#div: DIVISION_BY_ZERO"); uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath#sub: UNDERFLOW"); uint256 c = a - b; return c; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath#add: OVERFLOW"); return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath#mod: DIVISION_BY_ZERO"); return a % b; } } library Address { function isContract(address account) internal view returns (bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // 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. assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } library Strings { function strConcat( string memory _a, string memory _b, string memory _c, string memory _d, string memory _e ) internal pure returns (string memory) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint256 k = 0; for (uint256 i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (uint256 i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (uint256 i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (uint256 i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (uint256 i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } function strConcat( string memory _a, string memory _b, string memory _c, string memory _d ) internal pure returns (string memory) { return strConcat(_a, _b, _c, _d, ""); } function strConcat( string memory _a, string memory _b, string memory _c ) internal pure returns (string memory) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string memory _a, string memory _b) internal pure returns (string memory) { return strConcat(_a, _b, "", "", ""); } function uint2str(uint256 _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint256 j = _i; uint256 len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint256 k = len - 1; while (_i != 0) { bstr[k--] = bytes1(uint8(48 + (_i % 10))); _i /= 10; } return string(bstr); } } 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 payable public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () internal { owner = msg.sender; emit OwnershipTransferred(address(0), msg.sender); } modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } function isOwner() public view returns (bool) { return _msgSender() == owner; } function renounceOwnership() public onlyOwner { emit OwnershipTransferred(owner, address(0)); owner = address(0); } function transferOwnership(address payable newOwner) public onlyOwner { _transferOwnership(newOwner); } function _transferOwnership(address payable newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } interface IERC165 { /** * @notice Query if a contract implements an interface * @dev Interface identification is specified in ERC-165. This function * uses less than 30,000 gas * @param _interfaceId The interface identifier, as specified in ERC-165 */ function supportsInterface(bytes4 _interfaceId) external view returns (bool); } interface IERC721 { /** * @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; } 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); } interface IERC721Metadata { /** * @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); } contract ERC721 is Context, IERC165, IERC721, IERC721Metadata { using Address for address; // Token name string public name; // Token symbol string public 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; bytes4 constant private INTERFACE_SIGNATURE_ERC165 = 0x01ffc9a7; bytes4 constant private INTERFACE_SIGNATURE_ERC721 = 0x80ac58cd; bytes4 constant private INTERFACE_SIGNATURE_ERC721METADATA = 0x5b5e139f; bytes4 constant private INTERFACE_SIGNATURE_ERC721ENUMERABLE = 0x780e9d63; function supportsInterface(bytes4 _interfaceId) external view returns (bool) { if ( _interfaceId == INTERFACE_SIGNATURE_ERC165 || _interfaceId == INTERFACE_SIGNATURE_ERC721 || _interfaceId == INTERFACE_SIGNATURE_ERC721METADATA || _interfaceId == INTERFACE_SIGNATURE_ERC721ENUMERABLE ) { return true; } return false; } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view 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 returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public { 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 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 { 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 returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public { //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 { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public { 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 { _transfer(from, to, tokenId); _checkOnERC721Received(from, to, tokenId, _data); } /** * @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 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 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 { _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 { _mint(to, tokenId); _checkOnERC721Received(address(0), to, tokenId, _data); } /** * @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 { 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 { 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 { 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 { _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 */ bytes4 constant internal ERC721_RECEIVED_VALUE = 0xf0b9e5ba; function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private{ if (to.isContract()) { bytes4 retval = IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data); require(retval == ERC721_RECEIVED_VALUE, "ERC721: INVALID_ON_RECEIVE_MESSAGE"); } } /** * @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 {} } contract OwnableDelegateProxy {} contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } interface ERC721Token { 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) external view returns (uint256 balance); function ownerOf(uint256 tokenId) external view returns (address owner); function safeTransferFrom(address from, address to, uint256 tokenId) external; function transferFrom(address from, address to, uint256 tokenId) external; function approve(address to, uint256 tokenId) external; function getApproved(uint256 tokenId) external view returns (address operator); function setApprovalForAll(address operator, bool _approved) external; function isApprovedForAll(address owner, address operator) external view returns (bool); function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; function supportsInterface(bytes4 interfaceID) external view returns (bool); } contract ERC721Tradable is ERC721, Ownable{ using SafeMath for uint256; using Strings for string; event NFTGenerated(address indexed _owner, uint256 indexed _nftId, uint256 _series); event NewNFTPrice(uint256 indexed _newprice); string internal baseMetadataURI; address proxyRegistryAddress; uint256 public totalNFTs; uint256 NFTAvaliable; uint256 public currentNFTid = 0; uint256 public NFTprice = 0.05 * 10**18; uint256 totalAirDrop; uint256 totalAuthorize; uint256 totalPerverse; uint256 totalFreeBuy; uint256 series = 0; mapping (address => uint256) public MarketingQuota; mapping (address => bool) public PartnerTokenCheck; mapping (address => bool) public IfWhiteList; mapping (address => bool) public Authorized; bytes4 constant InterfaceSignature_ERC721 = 0x80ac58cd; ERC721Token public CryptoPunks; ERC721Token public LOSTPOETS; ERC721Token public PakCube; ERC721Token public TheCurrency; bool public canMint = true; modifier CanMint() { require(canMint); _; } constructor( string memory _name, string memory _symbol, uint256 _totalNFTs, uint256 _airdrop, uint256 _authorize, uint256 _perserve, uint256 _freebuy, address _proxyRegistryAddress ) public { name = _name; symbol = _symbol; totalNFTs = _totalNFTs; totalAirDrop = _airdrop; totalAuthorize = _authorize; totalPerverse = _perserve; totalFreeBuy = _freebuy; NFTAvaliable = _totalNFTs - _airdrop - _authorize - _perserve; proxyRegistryAddress = _proxyRegistryAddress; } function mintDisable() public onlyOwner { canMint = false; } function mintEnable() public onlyOwner { canMint = true; } // Regular Purchase function buyNFT(uint256 _amount) public payable CanMint { require(msg.value >= NFTprice.mul(_amount), "Insufficient ETH"); require(totalFreeBuy >= _amount); require(currentNFTid.add(_amount) <= totalNFTs+1, "Total Amount Exceed!"); for(uint i=0; i< _amount; i++) { _mint(msg.sender, currentNFTid); currentNFTid = currentNFTid.add(1); emit NFTGenerated(msg.sender, currentNFTid, series); } totalFreeBuy = totalFreeBuy.sub(_amount); } function adminGenerator(uint256 _amount, address receiver) public onlyOwner CanMint { require(currentNFTid.add(_amount) <= totalNFTs+1, "Total Amount Exceed!"); require(NFTAvaliable >= _amount, "NFT not available"); require(totalPerverse >= _amount, "Perserve Amount Exceed!"); for(uint i=0; i< _amount; i++) { _mint(receiver, currentNFTid); currentNFTid = currentNFTid.add(1); emit NFTGenerated(receiver, currentNFTid, series); } NFTAvaliable = NFTAvaliable.sub(_amount); totalPerverse = totalPerverse.sub(_amount); } function marketGenerator(uint256 _amount, address receiver) public CanMint { require(MarketingQuota[msg.sender] >= _amount, "Marketing Quota is not enough!"); require(currentNFTid.add(_amount) <= totalNFTs+1, "Total Amount Exceed!"); for(uint i=0; i< _amount; i++) { _mint(receiver, currentNFTid); currentNFTid = currentNFTid.add(1); emit NFTGenerated(receiver, currentNFTid, series); } MarketingQuota[msg.sender] = MarketingQuota[msg.sender].sub(_amount); } function authorizedGenerator(uint256 _amount, address receiver) public CanMint { require(Authorized[msg.sender]); require(totalAuthorize >= _amount); require(currentNFTid.add(_amount) <= totalNFTs+1, "Total Amount Exceed!"); for(uint i=0; i< _amount; i++) { _mint(receiver, currentNFTid); currentNFTid = currentNFTid.add(1); emit NFTGenerated(receiver, currentNFTid, series); } totalAuthorize = totalAuthorize.sub(_amount); } function authorizeAddress(address _vp) public onlyOwner { Authorized[_vp] = true; } function cancelAuthorized(address _vp) public onlyOwner { Authorized[_vp] = false; } function setSeries(uint256 _series) public onlyOwner { series = _series; } function setMarketQuota(address _spender, uint256 _amount) public onlyOwner { require(_amount >0); require(NFTAvaliable >= _amount); MarketingQuota[_spender] = MarketingQuota[_spender] + _amount; NFTAvaliable = NFTAvaliable.sub(_amount); } function airdrop() public CanMint { require(_canAirdrop(msg.sender) || _ifWhiteListed(msg.sender), "Unqualified!"); require(currentNFTid <= totalNFTs, "Total Amount Exceed!"); require(totalAirDrop > 0); _mint(msg.sender, currentNFTid); currentNFTid = currentNFTid.add(1); emit NFTGenerated(msg.sender, currentNFTid, series); if(IfWhiteList[msg.sender]) { IfWhiteList[msg.sender] = false; } else { PartnerTokenCheck[msg.sender] = true; } totalAirDrop = totalAirDrop.sub(1); } function setWhitelist(address[] memory _users) public onlyOwner { uint userLength = _users.length; for (uint i = 0; i < userLength; i++) { IfWhiteList[_users[i]] = true; } } function initialPartnerNFT(address _cryptoPunksAddress, address _lostpoetsAddress, address _pakCube, address _theCurrencyAddress) public onlyOwner { ERC721Token cryptoPunks = ERC721Token(_cryptoPunksAddress); CryptoPunks = cryptoPunks; ERC721Token lostpoets = ERC721Token(_lostpoetsAddress); LOSTPOETS = lostpoets; ERC721Token pakCube = ERC721Token(_pakCube); PakCube = pakCube; ERC721Token theCurrencyAddress = ERC721Token(_theCurrencyAddress); TheCurrency = theCurrencyAddress; } function _canAirdrop(address _user) private view returns(bool) { if (PartnerTokenCheck[_user]){ return false; } if(CryptoPunks.balanceOf(_user) > 0) { return true; } else if (LOSTPOETS.balanceOf(_user) > 0) { return true; } else if (PakCube.balanceOf(_user) > 0) { return true; } else if (TheCurrency.balanceOf(_user) > 0) { return true; } else{ return false; } } function _ifWhiteListed(address _user) private view returns(bool) { return IfWhiteList[_user]; } function setNFTPrice(uint256 _newPrice) public onlyOwner { require(_newPrice > 0); NFTprice = _newPrice; emit NewNFTPrice(_newPrice); } function setProxyAddress(address _proxyAddress) public onlyOwner { proxyRegistryAddress = _proxyAddress; } function tokenURI(uint256 _tokenId) public view returns (string memory) { require(_exists(_tokenId), "ERC721Tradable#uri: NONEXISTENT_TOKEN"); return Strings.strConcat(baseMetadataURI, Strings.uint2str(_tokenId)); } function _setBaseMetadataURI(string memory _newBaseMetadataURI) internal { baseMetadataURI = _newBaseMetadataURI; } function setBaseMetadataURI(string memory _newBaseMetadataURI) public onlyOwner { _setBaseMetadataURI(_newBaseMetadataURI); } function isApprovedForAll(address _owner, address _operator) public view returns (bool isOperator) { ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(_owner)) == _operator) { return true; } return ERC721.isApprovedForAll(_owner, _operator); } } contract CosmoChamber is ERC721Tradable { constructor(address _proxyRegistryAddress) public ERC721Tradable("CosmoChamber", "CC", 6001, 800, 500, 500, 4201, _proxyRegistryAddress) { _setBaseMetadataURI("https://api.cosmochamber.art/metadata/"); } function contractURI() public pure returns (string memory) { return "https://www.cosmoschanmber.art/about-us"; } function withdrawBalance() external onlyOwner { owner.transfer(address(this).balance); } }
See {IERC721-setApprovalForAll}./
function setApprovalForAll(address operator, bool approved) public { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); }
7,222,158
pragma solidity ^0.4.17; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @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; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev 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(balances[msg.sender] >= _value); // 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 view returns (uint256 balance) { return balances[_owner]; } } /** * @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)) 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(balances[_from] >= _value); require(allowed[_from][msg.sender] <= _value); require(_value >= 0); 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&#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; 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, uint _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, uint _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; } } contract WyeContract is StandardToken{ string public name = "万业通";//name string public symbol = "WYT";//symbol uint8 public decimals = 18;// uint256 public TOTAL_SUPPLY = 1000000000000000000;//TOTAL_SUPPLY uint256 public totalSupply = 450000000*TOTAL_SUPPLY; address public own = 0x590735DDb8672cCC6A40C5b4FB985ac70f21593e; //init function WyeContract() public { balances[own] = totalSupply; } }
Transfer tokens from one address to another _from address The address which you want to send tokens from _to address The address which you want to transfer to _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(balances[_from] >= _value); require(allowed[_from][msg.sender] <= _value); require(_value >= 0); 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; }
7,688,691
/* * Copyright ©️ 2018 Galt•Space Society Construction and Terraforming Company * (Founded by [Nikolai Popeka](https://github.com/npopeka), * [Dima Starodubcev](https://github.com/xhipster), * [Valery Litvin](https://github.com/litvintech) by * [Basic Agreement](http://cyb.ai/QmSAWEG5u5aSsUyMNYuX2A2Eaz4kEuoYWUkVBRdmu9qmct:ipfs)). * * Copyright ©️ 2018 Galt•Core Blockchain Company * (Founded by [Nikolai Popeka](https://github.com/npopeka) and * Galt•Space Society Construction and Terraforming Company by * [Basic Agreement](http://cyb.ai/QmaCiXUmSrP16Gz8Jdzq6AJESY1EAANmmwha15uR3c1bsS:ipfs)). */ pragma solidity 0.5.10; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "@galtproject/libs/contracts/collections/ArraySet.sol"; import "../../registries/interfaces/ILockerRegistry.sol"; import "./LiquidRA.sol"; // LiquidRA - base class // SpaceInputRA - space input // GaltInputRA - galt input // LockableRA - lockable output // SharableRA - share calculation output // FundRA - LiquidRA + SpaceInputRA + SharableRA contract SpaceInputRA is LiquidRA { ArraySet.AddressSet internal _spaceTokenOwners; mapping(address => ArraySet.Uint256Set) internal _spaceTokensByOwner; mapping(uint256 => bool) public reputationMinted; modifier onlySpaceTokenOwner(uint256 _spaceTokenId, ISpaceLocker _spaceLocker) { require(address(_spaceLocker) == ggr.getSpaceToken().ownerOf(_spaceTokenId), "Invalid sender. Token owner expected."); require(msg.sender == _spaceLocker.owner(), "Not SpaceLocker owner"); spaceLockerRegistry().requireValidLocker(address(_spaceLocker)); _; } // @dev Transfer owned reputation // PermissionED function delegate(address _to, address _owner, uint256 _amount) public { require(_spaceTokenOwners.has(_to), "Beneficiary isn't a space token owner"); _transfer(msg.sender, _to, _owner, _amount); } // @dev Mints reputation for given token to the owner account function mint( ISpaceLocker _spaceLocker ) public { spaceLockerRegistry().requireValidLocker(address(_spaceLocker)); address owner = _spaceLocker.owner(); require(msg.sender == owner, "Not owner of the locker"); uint256 spaceTokenId = _spaceLocker.spaceTokenId(); require(reputationMinted[spaceTokenId] == false, "Reputation already minted"); uint256 reputation = _spaceLocker.reputation(); _cacheSpaceTokenOwner(owner, spaceTokenId); _mint(owner, reputation); } // Burn space token total reputation // Owner should revoke all delegated reputation back to his account before performing this action function approveBurn( ISpaceLocker _spaceLocker ) public { spaceLockerRegistry().requireValidLocker(address(_spaceLocker)); address owner = _spaceLocker.owner(); require(msg.sender == owner, "Not owner of the locker"); uint256 reputation = _spaceLocker.reputation(); uint256 spaceTokenId = _spaceLocker.spaceTokenId(); require(reputationMinted[spaceTokenId] == true, "Reputation doesn't minted"); _burn(owner, reputation); _spaceTokensByOwner[owner].remove(spaceTokenId); if (_spaceTokensByOwner[owner].size() == 0) { _spaceTokenOwners.remove(owner); } reputationMinted[spaceTokenId] = false; } function _cacheSpaceTokenOwner(address _owner, uint256 _spaceTokenId) internal { _spaceTokensByOwner[_owner].add(_spaceTokenId); _spaceTokenOwners.addSilent(_owner); reputationMinted[_spaceTokenId] = true; } function spaceLockerRegistry() internal view returns(ILockerRegistry) { return ILockerRegistry(ggr.getSpaceLockerRegistryAddress()); } function spaceTokenOwners() public view returns (address[] memory) { return _spaceTokenOwners.elements(); } function spaceTokenOwnersCount() public view returns (uint256) { return _spaceTokenOwners.size(); } function isMember(address _owner) public view returns (bool) { return _spaceTokenOwners.has(_owner); } function ownerHasSpaceToken(address _owner, uint256 _spaceTokenId) public view returns (bool) { return _spaceTokensByOwner[_owner].has(_spaceTokenId); } function spaceTokensByOwner(address _owner) public view returns (uint256[] memory) { return _spaceTokensByOwner[_owner].elements(); } function spaceTokensByOwnerCount(address _owner) public view returns (uint256) { return _spaceTokensByOwner[_owner].size(); } }
Mints reputation for given token to the owner account
function mint( ISpaceLocker _spaceLocker ) public { spaceLockerRegistry().requireValidLocker(address(_spaceLocker)); address owner = _spaceLocker.owner(); require(msg.sender == owner, "Not owner of the locker"); uint256 spaceTokenId = _spaceLocker.spaceTokenId(); require(reputationMinted[spaceTokenId] == false, "Reputation already minted"); uint256 reputation = _spaceLocker.reputation(); _cacheSpaceTokenOwner(owner, spaceTokenId); _mint(owner, reputation); }
896,807
pragma solidity ^0.4.18; // zeppelin-solidity: 1.5.0 /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { 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; } 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; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure 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 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; /** * @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 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]; } } /** * @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)) 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 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, uint _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, uint _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; } } /** * @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 Object is StandardToken, Ownable { string public name; string public symbol; uint8 public constant decimals = 18; bool public mintingFinished = false; event Burn(address indexed burner, uint value); event Mint(address indexed to, uint amount); event MintFinished(); modifier canMint() { require(!mintingFinished); _; } function Object(string _name, string _symbol) public { name = _name; symbol = _symbol; } function burn(uint _value) onlyOwner public { require(_value <= balances[msg.sender]); address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); Burn(burner, _value); } function mint(address _to, uint _amount) onlyOwner canMint public returns(bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } function finishMinting() onlyOwner canMint public returns(bool) { mintingFinished = true; MintFinished(); return true; } function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); require(_value % (1 ether) == 0); // require whole token transfers // 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; } } contract Shop is Ownable { using SafeMath for *; struct ShopSettings { address bank; uint32 startTime; uint32 endTime; uint fundsRaised; uint rate; uint price; //uint recommendedBid; } Object public object; ShopSettings public shopSettings; modifier onlyValidPurchase() { require(msg.value % shopSettings.price == 0); // whole numbers only require((now >= shopSettings.startTime && now <= shopSettings.endTime) && msg.value != 0); _; } modifier whenClosed() { // not actually implemented? require(now > shopSettings.endTime); _; } modifier whenOpen() { require(now < shopSettings.endTime); _; } modifier onlyValidAddress(address _bank) { require(_bank != address(0)); _; } modifier onlyOne() { require(calculateTokens() == 1 ether); _; } modifier onlyBuyer(address _beneficiary) { require(_beneficiary == msg.sender); _; } event ShopClosed(uint32 date); event ObjectPurchase(address indexed purchaser, address indexed beneficiary, uint value, uint amount); function () external payable { buyObject(msg.sender); } function Shop(address _bank, string _name, string _symbol, uint _rate, uint32 _endTime) onlyValidAddress(_bank) public { require(_rate >= 0); require(_endTime > now); shopSettings = ShopSettings(_bank, uint32(now), _endTime, 0, _rate, 0); calculatePrice(); // set initial price based on initial rate object = new Object(_name, _symbol); } function buyObject(address _beneficiary) onlyValidPurchase onlyBuyer(_beneficiary) onlyValidAddress(_beneficiary) public payable { uint numTokens = calculateTokens(); shopSettings.fundsRaised = shopSettings.fundsRaised.add(msg.value); object.mint(_beneficiary, numTokens); ObjectPurchase(msg.sender, _beneficiary, msg.value, numTokens); forwardFunds(); } function calculateTokens() internal returns(uint) { // rate is literally tokens per eth in wei; // passing in a rate of 10 ETH (10*10^18) equates to 10 tokens per ETH, or a price of 0.1 ETH per token // rate is always 1/price! calculatePrice(); // update price return msg.value.mul(1 ether).div(1 ether.mul(1 ether).div(shopSettings.rate)); } function calculatePrice() internal returns(uint) { shopSettings.price = (1 ether).mul(1 ether).div(shopSettings.rate); // update price based on current rate //shopSettings.recommendedBid = shopSettings.price.add((1 ether).div(100)); // update recommended bid based on current price } function closeShop() onlyOwner whenOpen public { shopSettings.endTime = uint32(now); ShopClosed(uint32(now)); } function forwardFunds() internal { shopSettings.bank.transfer(msg.value); } }
SafeMath.sub will throw if there is not enough balance.
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); Transfer(msg.sender, _to, _value); return true; }
1,721,867
pragma solidity ^0.4.22; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns(uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } 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; } function sub(uint256 a, uint256 b) internal pure returns(uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns(uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address and * provides basic authorization control functions */ contract Ownable { // Public properties address public owner; // Log if ownership has been changed event ChangeOwnership(address indexed _owner, address indexed _newOwner); // Checks if address is an owner modifier OnlyOwner() { require(msg.sender == owner); _; } // The Ownable constructor sets the owner address function Ownable() public { owner = msg.sender; } // Transfer current ownership to the new account function transferOwnership(address _newOwner) public OnlyOwner { require(_newOwner != address(0x0)); owner = _newOwner; emit ChangeOwnership(owner, _newOwner); } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { /* * @dev Event to notify listeners about pause. * @param pauseReason string Reason the token was paused for. */ event Pause(string pauseReason); /* * @dev Event to notify listeners about pause. * @param unpauseReason string Reason the token was unpaused for. */ event Unpause(string unpauseReason); bool public isPaused; string public pauseNotice; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier IsNotPaused() { require(!isPaused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier IsPaused() { require(isPaused); _; } /** * @dev called by the owner to pause, triggers stopped state * @param _reason string The reason for the pause. */ function pause(string _reason) OnlyOwner IsNotPaused public { isPaused = true; pauseNotice = _reason; emit Pause(_reason); } /** * @dev called by the owner to unpause, returns to normal state * @param _reason string Reason for the un pause. */ function unpause(string _reason) OnlyOwner IsPaused public { isPaused = false; pauseNotice = _reason; emit Unpause(_reason); } } /** * @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 view returns(uint256 theBalance); function transfer(address to, uint256 value) public returns(bool success); 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 theAllowance); function transferFrom(address from, address to, uint256 value) public returns(bool success); function approve(address spender, uint256 value) public returns(bool success); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken without allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; // Balances for each account mapping(address => uint256) balances; /** * @dev Get the token balance for account * @param _address The address to query the balance of._address * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _address) public constant returns(uint256 theBalance){ return balances[_address]; } /** * @dev Transfer the balance from owner's account to another account * @param _to The address to transfer to. * @param _value The amount to be transferred. * @return Returns true if transfer has been successful */ function transfer(address _to, uint256 _value) public returns(bool success){ require(_to != address(0x0) && _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; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 */ contract StandardToken is BasicToken, ERC20 { // Owner of account approves the transfer of an amount to another account mapping (address => mapping (address => uint256)) allowed; /** * @dev Returns the amount of tokens approved by the owner that can be transferred to the spender's account * @param _owner The address which owns the funds. * @param _spender The address which will spend the funds. * @return An uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns(uint256 theAllowance){ return allowed[_owner][_spender]; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * To change the approve amount you first have to reduce the addresses` * allowance to zero by calling `approve(_spender, 0)` if it is not * already 0 to mitigate the race condition described here: * 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 success){ require(allowed[msg.sender][_spender] == 0 || _value == 0); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * Transfer from `from` account to `to` account using allowance in `from` account to the sender * * @param _from Origin address * @param _to Destination address * @param _value Amount of CHR tokens to send */ function transferFrom(address _from, address _to, uint256 _value) public returns(bool success) { 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; } } /** * @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 { require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); totalSupply = totalSupply.sub(_value); emit Burn(msg.sender, _value); } } /** * CHERR.IO is a standard ERC20 token with some additional functionalities: * - Transfers are only enabled after contract owner enables it (after the ICO) * - Contract sets 60% of the total supply as allowance for ICO contract */ contract Cherrio is StandardToken, BurnableToken, Ownable, Pausable { using SafeMath for uint256; // Metadata string public constant name = "CHERR.IO"; string public constant symbol = "CHR"; uint8 public constant decimals = 18; // Token supplies uint256 public constant INITIAL_SUPPLY = 200000000 * (10 ** uint256(decimals)); uint256 public constant ADMIN_ALLOWANCE = 80000000 * (10 ** uint256(decimals)); uint256 public constant CONTRACT_ALLOWANCE = INITIAL_SUPPLY - ADMIN_ALLOWANCE; // Funding cap in ETH. Change to equal $12M at time of token offering uint256 public constant FUNDING_ETH_HARD_CAP = 15000 ether; // Minimum cap in ETH. Change to equal $3M at time of token offering uint256 public constant MINIMUM_ETH_SOFT_CAP = 3750 ether; // Min contribution is 0.1 ether uint256 public constant MINIMUM_CONTRIBUTION = 100 finney; // Price of the tokens as in tokens per ether uint256 public constant RATE = 5333; // Price of the tokens in tier 1 uint256 public constant RATE_TIER1 = 8743; // Price of the tokens in tier 2 uint256 public constant RATE_TIER2 = 7306; // Price of the tokens in tier 3 uint256 public constant RATE_TIER3 = 6584; // Price of the tokens in public sale for limited timeline uint256 public constant RATE_PUBLIC_SALE = 5926; // Maximum cap for tier 1 (60M CHR tokens) uint256 public constant TIER1_CAP = 60000000 * (10 ** uint256(decimals)); // Maximum cap for tier 2 (36M CHR tokens) uint256 public constant TIER2_CAP = 36000000 * (10 ** uint256(decimals)); // Maximum cap for each contributor in tier 1 uint256 public participantCapTier1; // Maximum cap for each contributor in tier 2 uint256 public participantCapTier2; // ETH cap for pool addres only in tier 1 uint256 public poolAddressCapTier1; // ETH cap for pool addres only in tier 2 uint256 public poolAddressCapTier2; // The address of the token admin address public adminAddress; // The address where ETH funds are collected address public beneficiaryAddress; // The address of the contract address public contractAddress; // The address of the pool who can send unlimited ETH to the contract address public poolAddress; // Enable transfers after conclusion of the token offering bool public transferIsEnabled; // Amount of raised in Wei uint256 public weiRaised; // Amount of CHR tokens sent to participant for presale and public sale uint256[4] public tokensSent; // Start of public pre-sale in timestamp uint256 startTimePresale; // Start and end time of public sale in timestamp uint256 startTime; uint256 endTime; // Discount period for public sale uint256 publicSaleDiscountEndTime; // End time limits in timestamp for each tier bonus uint256[3] public tierEndTime; //Check if contract address is already set bool contractAddressIsSet; struct Contributor { bool canContribute; uint8 tier; uint256 contributionInWeiTier1; uint256 contributionInWeiTier2; uint256 contributionInWeiTier3; uint256 contributionInWeiPublicSale; } struct Pool { uint256 contributionInWei; } enum Stages { Pending, PreSale, PublicSale, Ended } // The current stage of the offering Stages public stage; mapping(address => Contributor) public contributors; mapping(address => mapping(uint8 => Pool)) public pool; // Check if transfer is enabled modifier TransferIsEnabled { require(transferIsEnabled || msg.sender == adminAddress || msg.sender == contractAddress); _; } /** * @dev Check if address is a valid destination to transfer tokens to * - must not be zero address * - must not be the token address * - must not be the owner's address * - must not be the admin's address * - must not be the token offering contract address * - must not be the beneficiary address */ modifier ValidDestination(address _to) { require(_to != address(0x0)); require(_to != address(this)); require(_to != owner); require(_to != address(adminAddress)); require(_to != address(contractAddress)); require(_to != address(beneficiaryAddress)); _; } /** * Modifier that requires certain stage before executing the main function body * * @param _expectedStage Value that the current stage is required to match */ modifier AtStage(Stages _expectedStage) { require(stage == _expectedStage); _; } // Check if ICO is live modifier CheckIfICOIsLive() { require(stage != Stages.Pending && stage != Stages.Ended); if(stage == Stages.PreSale) { require( startTimePresale > 0 && now >= startTimePresale && now <= tierEndTime[2] ); } else { require( startTime > 0 && now >= startTime && now <= endTime ); } _; } // Check if participant sent more then miniminum required contribution modifier CheckPurchase() { require(msg.value >= MINIMUM_CONTRIBUTION); _; } /** * Event for token purchase logging * * @param _purchaser Participant who paid for CHR tokens * @param _value Amount in WEI paid for token * @param _tokens Amount of tokens purchased */ event TokenPurchase(address indexed _purchaser, uint256 _value, uint256 _tokens); /** * Event when token offering started * * @param _msg Message * @param _startTime Start time in timestamp * @param _endTime End time in timestamp */ event OfferingOpens(string _msg, uint256 _startTime, uint256 _endTime); /** * Event when token offering ended and how much has been raised in wei * * @param _endTime End time in timestamp * @param _totalWeiRaised Total raised funds in wei */ event OfferingCloses(uint256 _endTime, uint256 _totalWeiRaised); /** * Cherrio constructor */ function Cherrio() public { totalSupply = INITIAL_SUPPLY; // Mint tokens balances[msg.sender] = totalSupply; emit Transfer(address(0x0), msg.sender, totalSupply); // Aprove an allowance for admin account adminAddress = 0xe0509bB3921aacc433108D403f020a7c2f92e936; approve(adminAddress, ADMIN_ALLOWANCE); participantCapTier1 = 100 ether; participantCapTier2 = 100 ether; poolAddressCapTier1 = 2000 ether; poolAddressCapTier2 = 2000 ether; weiRaised = 0; startTimePresale = 0; startTime = 0; endTime = 0; publicSaleDiscountEndTime = 0; transferIsEnabled = false; contractAddressIsSet = false; } /** * Add approved addresses * * @param _addresses Array of approved addresses * @param _tier Tier */ function addApprovedAddresses(address[] _addresses, uint8 _tier) external OnlyOwner { uint256 length = _addresses.length; for(uint256 i = 0; i < length; i++) { if(!contributors[_addresses[i]].canContribute) { contributors[_addresses[i]].canContribute = true; contributors[_addresses[i]].tier = _tier; contributors[_addresses[i]].contributionInWeiTier1 = 0; contributors[_addresses[i]].contributionInWeiTier2 = 0; contributors[_addresses[i]].contributionInWeiTier3 = 0; contributors[_addresses[i]].contributionInWeiPublicSale = 0; } } } /** * Add approved address * * @param _address Approved address * @param _tier Tier */ function addSingleApprovedAddress(address _address, uint8 _tier) external OnlyOwner { if(!contributors[_address].canContribute) { contributors[_address].canContribute = true; contributors[_address].tier = _tier; contributors[_address].contributionInWeiTier1 = 0; contributors[_address].contributionInWeiTier2 = 0; contributors[_address].contributionInWeiTier3 = 0; contributors[_address].contributionInWeiPublicSale = 0; } } /** * Set token offering address to approve allowance for offering contract to distribute tokens */ function setTokenOffering() external OnlyOwner{ require(!contractAddressIsSet); require(!transferIsEnabled); contractAddress = address(this); approve(contractAddress, CONTRACT_ALLOWANCE); beneficiaryAddress = 0xAec8c4242c8c2E532c6D6478A7de380263234845; poolAddress = 0x1A2C916B640520E1e93A78fEa04A49D8345a5aa9; pool[poolAddress][0].contributionInWei = 0; pool[poolAddress][1].contributionInWei = 0; pool[poolAddress][2].contributionInWei = 0; pool[poolAddress][3].contributionInWei = 0; tokensSent[0] = 0; tokensSent[1] = 0; tokensSent[2] = 0; tokensSent[3] = 0; stage = Stages.Pending; contractAddressIsSet = true; } /** * Set when presale starts * * @param _startTimePresale Start time of presale in timestamp */ function startPresale(uint256 _startTimePresale) external OnlyOwner AtStage(Stages.Pending) { if(_startTimePresale == 0) { startTimePresale = now; } else { startTimePresale = _startTimePresale; } setTierEndTime(); stage = Stages.PreSale; } /** * Set when public sale starts * * @param _startTime Start time of public sale in timestamp */ function startPublicSale(uint256 _startTime) external OnlyOwner AtStage(Stages.PreSale) { if(_startTime == 0) { startTime = now; } else { startTime = _startTime; } endTime = startTime + 15 days; publicSaleDiscountEndTime = startTime + 3 days; stage = Stages.PublicSale; } // Fallback function can be used to buy CHR tokens function () public payable { buy(); } function buy() public payable IsNotPaused CheckIfICOIsLive returns(bool _success) { uint8 currentTier = getCurrentTier(); if(currentTier > 3) { revert(); } if(!buyTokens(currentTier)) { revert(); } return true; } /** * @param _tier Current Token Sale tier */ function buyTokens(uint8 _tier) internal ValidDestination(msg.sender) CheckPurchase returns(bool _success) { if(weiRaised.add(msg.value) > FUNDING_ETH_HARD_CAP) { revert(); } uint256 contributionInWei = msg.value; if(!checkTierCap(_tier, contributionInWei)) { revert(); } uint256 rate = getTierTokens(_tier); uint256 tokens = contributionInWei.mul(rate); if(msg.sender != poolAddress) { if(stage == Stages.PreSale) { if(!checkAllowedTier(msg.sender, _tier)) { revert(); } } if(!checkAllowedContribution(msg.sender, contributionInWei, _tier)) { revert(); } if(!this.transferFrom(owner, msg.sender, tokens)) { revert(); } if(stage == Stages.PreSale) { if(_tier == 0) { contributors[msg.sender].contributionInWeiTier1 = contributors[msg.sender].contributionInWeiTier1.add(contributionInWei); } else if(_tier == 1) { contributors[msg.sender].contributionInWeiTier2 = contributors[msg.sender].contributionInWeiTier2.add(contributionInWei); } else if(_tier == 2) { contributors[msg.sender].contributionInWeiTier3 = contributors[msg.sender].contributionInWeiTier3.add(contributionInWei); } } else { contributors[msg.sender].contributionInWeiPublicSale = contributors[msg.sender].contributionInWeiPublicSale.add(contributionInWei); } } else { if(!checkPoolAddressTierCap(_tier, contributionInWei)) { revert(); } if(!this.transferFrom(owner, msg.sender, tokens)) { revert(); } pool[poolAddress][_tier].contributionInWei = pool[poolAddress][_tier].contributionInWei.add(contributionInWei); } weiRaised = weiRaised.add(contributionInWei); tokensSent[_tier] = tokensSent[_tier].add(tokens); if(weiRaised >= FUNDING_ETH_HARD_CAP) { offeringEnded(); } beneficiaryAddress.transfer(address(this).balance); emit TokenPurchase(msg.sender, contributionInWei, tokens); return true; } /** * Manually withdraw tokens to private investors * * @param _to Address of private investor * @param _value The number of tokens to send to private investor */ function withdrawCrowdsaleTokens(address _to, uint256 _value) external OnlyOwner ValidDestination(_to) returns (bool _success) { if(!this.transferFrom(owner, _to, _value)) { revert(); } return true; } /** * Transfer from sender to another account * * @param _to Destination address * @param _value Amount of CHR tokens to send */ function transfer(address _to, uint256 _value) public ValidDestination(_to) TransferIsEnabled IsNotPaused returns(bool _success){ return super.transfer(_to, _value); } /** * Transfer from `from` account to `to` account using allowance in `from` account to the sender * * @param _from Origin address * @param _to Destination address * @param _value Amount of CHR tokens to send */ function transferFrom(address _from, address _to, uint256 _value) public ValidDestination(_to) TransferIsEnabled IsNotPaused returns(bool _success){ return super.transferFrom(_from, _to, _value); } /** * Check if participant is allowed to contribute in current tier * * @param _address Participant address * @param _tier Current tier */ function checkAllowedTier(address _address, uint8 _tier) internal view returns (bool _allowed) { if(contributors[_address].tier <= _tier) { return true; } else{ return false; } } /** * Check contribution cap for only tier 1 and 2 * * @param _tier Current tier * @param _value Participant contribution */ function checkTierCap(uint8 _tier, uint256 _value) internal view returns (bool _success) { uint256 currentlyTokensSent = tokensSent[_tier]; bool status = true; if(_tier == 0) { if(TIER1_CAP < currentlyTokensSent.add(_value)) { status = false; } } else if(_tier == 1) { if(TIER2_CAP < currentlyTokensSent.add(_value)) { status = false; } } return status; } /** * Check cap for pool address in tier 1 and 2 * * @param _tier Current tier * @param _value Pool contribution */ function checkPoolAddressTierCap(uint8 _tier, uint256 _value) internal view returns (bool _success) { uint256 currentContribution = pool[poolAddress][_tier].contributionInWei; if((_tier == 0 && (poolAddressCapTier1 < currentContribution.add(_value))) || (_tier == 1 && (poolAddressCapTier2 < currentContribution.add(_value)))) { return false; } return true; } /** * Check cap for pool address in tier 1 and 2 * * @param _address Participant address * @param _value Participant contribution * @param _tier Current tier */ function checkAllowedContribution(address _address, uint256 _value, uint8 _tier) internal view returns (bool _success) { bool status = false; if(contributors[_address].canContribute) { if(_tier == 0) { if(participantCapTier1 >= contributors[_address].contributionInWeiTier1.add(_value)) { status = true; } } else if(_tier == 1) { if(participantCapTier2 >= contributors[_address].contributionInWeiTier2.add(_value)) { status = true; } } else if(_tier == 2) { status = true; } else { status = true; } } return status; } /** * Get current tier tokens rate * * @param _tier Current tier */ function getTierTokens(uint8 _tier) internal view returns(uint256 _tokens) { uint256 tokens = RATE_TIER1; if(_tier == 1) { tokens = RATE_TIER2; } else if(_tier == 2) { tokens = RATE_TIER3; } else if(_tier == 3) { if(now <= publicSaleDiscountEndTime) { tokens = RATE_PUBLIC_SALE; } else { tokens = RATE; } } return tokens; } // Get current tier function getCurrentTier() public view returns(uint8 _tier) { uint8 currentTier = 3; // 3 is public sale if(stage == Stages.PreSale) { if(now <= tierEndTime[0]) { currentTier = 0; } else if(now <= tierEndTime[1]) { currentTier = 1; } else if(now <= tierEndTime[2]) { currentTier = 2; } } else { if(now > endTime) { currentTier = 4; // Token offering ended } } return currentTier; } // Set end time for each tier function setTierEndTime() internal AtStage(Stages.Pending) { tierEndTime[0] = startTimePresale + 1 days; tierEndTime[1] = tierEndTime[0] + 2 days; tierEndTime[2] = tierEndTime[1] + 6 days; } // End the token offering function endOffering() public OnlyOwner { offeringEnded(); } // Token offering is ended function offeringEnded() internal { endTime = now; stage = Stages.Ended; emit OfferingCloses(endTime, weiRaised); } // Enable transfers, burn unsold tokens & set tokenOfferingAddress to 0 function enableTransfer() public OnlyOwner returns(bool _success){ transferIsEnabled = true; uint256 tokensToBurn = allowed[msg.sender][contractAddress]; if(tokensToBurn != 0){ burn(tokensToBurn); approve(contractAddress, 0); } return true; } /** * Extend end time * * @param _addedTime Addtional time in secods */ function extendEndTime(uint256 _addedTime) external OnlyOwner { endTime = endTime + _addedTime; } /** * Extend public sale discount time * * @param _addedPublicSaleDiscountEndTime Addtional time in secods */ function extendPublicSaleDiscountEndTime(uint256 _addedPublicSaleDiscountEndTime) external OnlyOwner { publicSaleDiscountEndTime = publicSaleDiscountEndTime + _addedPublicSaleDiscountEndTime; } /** * Update pool cap for tier 1 * * @param _poolAddressCapTier1 Tier cap */ function updatePoolAddressCapTier1(uint256 _poolAddressCapTier1) external OnlyOwner { poolAddressCapTier1 = _poolAddressCapTier1; } /** * Update pool cap for tier 2 * * @param _poolAddressCapTier2 Tier cap */ function updatePoolAddressCapTier2(uint256 _poolAddressCapTier2) external OnlyOwner { poolAddressCapTier2 = _poolAddressCapTier2; } // /** * Update participant cap for tier 1 * * @param _participantCapTier1 Tier cap */ function updateParticipantCapTier1(uint256 _participantCapTier1) external OnlyOwner { participantCapTier1 = _participantCapTier1; } /** * Update participant cap for tier 2 * * @param _participantCapTier2 Tier cap */ function updateParticipantCapTier2(uint256 _participantCapTier2) external OnlyOwner { participantCapTier2 = _participantCapTier2; } }
Check cap for pool address in tier 1 and 2 _address Participant address _value Participant contribution _tier Current tier/
function checkAllowedContribution(address _address, uint256 _value, uint8 _tier) internal view returns (bool _success) { bool status = false; if(contributors[_address].canContribute) { if(_tier == 0) { if(participantCapTier1 >= contributors[_address].contributionInWeiTier1.add(_value)) { status = true; } } else if(_tier == 1) { if(participantCapTier2 >= contributors[_address].contributionInWeiTier2.add(_value)) { status = true; } } else if(_tier == 2) { status = true; } else { status = true; } } return status; }
5,504,685
pragma solidity ^0.4.21; contract Ownable { address public owner; event OwnershipTransferred(address previousOwner, address newOwner); function Ownable() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract StorageBase is Ownable { function withdrawBalance() external onlyOwner returns (bool) { // The owner has a method to withdraw balance from multiple contracts together, // use send here to make sure even if one withdrawBalance fails the others will still work bool res = msg.sender.send(address(this).balance); return res; } } // owner of ActivityStorage should be ActivityCore contract address contract ActivityStorage is StorageBase { struct Activity { // accept bid or not bool isPause; // limit max num of monster buyable per address uint16 buyLimit; // price (in wei) uint128 packPrice; // startDate (in seconds) uint64 startDate; // endDate (in seconds) uint64 endDate; // packId => address of bid winner mapping(uint16 => address) soldPackToAddress; // address => number of success bid mapping(address => uint16) addressBoughtCount; } // limit max activityId to 65536, big enough mapping(uint16 => Activity) public activities; function createActivity( uint16 _activityId, uint16 _buyLimit, uint128 _packPrice, uint64 _startDate, uint64 _endDate ) external onlyOwner { // activity should not exist and can only be initialized once require(activities[_activityId].buyLimit == 0); activities[_activityId] = Activity({ isPause: false, buyLimit: _buyLimit, packPrice: _packPrice, startDate: _startDate, endDate: _endDate }); } function sellPackToAddress( uint16 _activityId, uint16 _packId, address buyer ) external onlyOwner { Activity storage activity = activities[_activityId]; activity.soldPackToAddress[_packId] = buyer; activity.addressBoughtCount[buyer]++; } function pauseActivity(uint16 _activityId) external onlyOwner { activities[_activityId].isPause = true; } function unpauseActivity(uint16 _activityId) external onlyOwner { activities[_activityId].isPause = false; } function deleteActivity(uint16 _activityId) external onlyOwner { delete activities[_activityId]; } function getAddressBoughtCount(uint16 _activityId, address buyer) external view returns (uint16) { return activities[_activityId].addressBoughtCount[buyer]; } function getBuyerAddress(uint16 _activityId, uint16 packId) external view returns (address) { return activities[_activityId].soldPackToAddress[packId]; } } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; modifier whenNotPaused() { require(!paused); _; } modifier whenPaused { require(paused); _; } function pause() public onlyOwner whenNotPaused { paused = true; emit Pause(); } function unpause() public onlyOwner whenPaused { paused = false; emit Unpause(); } } contract HasNoContracts is Pausable { function reclaimContract(address _contractAddr) external onlyOwner whenPaused { Ownable contractInst = Ownable(_contractAddr); contractInst.transferOwnership(owner); } } contract ERC721 { // Required methods function totalSupply() public view returns (uint256 total); function balanceOf(address _owner) public view returns (uint256 balance); function ownerOf(uint256 _tokenId) external view returns (address owner); function approve(address _to, uint256 _tokenId) external; function transfer(address _to, uint256 _tokenId) external; function transferFrom(address _from, address _to, uint256 _tokenId) external; // Events event Transfer(address from, address to, uint256 tokenId); event Approval(address owner, address approved, uint256 tokenId); // Optional // function name() public view returns (string name); // function symbol() public view returns (string symbol); // function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds); // function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl); // ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165) function supportsInterface(bytes4 _interfaceID) external view returns (bool); } contract LogicBase is HasNoContracts { /// The ERC-165 interface signature for ERC-721. /// Ref: https://github.com/ethereum/EIPs/issues/165 /// Ref: https://github.com/ethereum/EIPs/issues/721 bytes4 constant InterfaceSignature_NFC = bytes4(0x9f40b779); // Reference to contract tracking NFT ownership ERC721 public nonFungibleContract; // Reference to storage contract StorageBase public storageContract; function LogicBase(address _nftAddress, address _storageAddress) public { // paused by default paused = true; setNFTAddress(_nftAddress); require(_storageAddress != address(0)); storageContract = StorageBase(_storageAddress); } // Very dangerous action, only when new contract has been proved working // Requires storageContract already transferOwnership to the new contract // This method is only used to transfer the balance to owner function destroy() external onlyOwner whenPaused { address storageOwner = storageContract.owner(); // owner of storageContract must not be the current contract otherwise the storageContract will forever not accessible require(storageOwner != address(this)); // Transfers the current balance to the owner and terminates the contract selfdestruct(owner); } // Very dangerous action, only when new contract has been proved working // Requires storageContract already transferOwnership to the new contract // This method is only used to transfer the balance to the new contract function destroyAndSendToStorageOwner() external onlyOwner whenPaused { address storageOwner = storageContract.owner(); // owner of storageContract must not be the current contract otherwise the storageContract will forever not accessible require(storageOwner != address(this)); // Transfers the current balance to the new owner of the storage contract and terminates the contract selfdestruct(storageOwner); } // override to make sure everything is initialized before the unpause function unpause() public onlyOwner whenPaused { // can not unpause when the logic contract is not initialzed require(nonFungibleContract != address(0)); require(storageContract != address(0)); // can not unpause when ownership of storage contract is not the current contract require(storageContract.owner() == address(this)); super.unpause(); } function setNFTAddress(address _nftAddress) public onlyOwner { require(_nftAddress != address(0)); ERC721 candidateContract = ERC721(_nftAddress); require(candidateContract.supportsInterface(InterfaceSignature_NFC)); nonFungibleContract = candidateContract; } // Withdraw balance to the Core Contract function withdrawBalance() external returns (bool) { address nftAddress = address(nonFungibleContract); // either Owner or Core Contract can trigger the withdraw require(msg.sender == owner || msg.sender == nftAddress); // The owner has a method to withdraw balance from multiple contracts together, // use send here to make sure even if one withdrawBalance fails the others will still work bool res = nftAddress.send(address(this).balance); return res; } function withdrawBalanceFromStorageContract() external returns (bool) { address nftAddress = address(nonFungibleContract); // either Owner or Core Contract can trigger the withdraw require(msg.sender == owner || msg.sender == nftAddress); // The owner has a method to withdraw balance from multiple contracts together, // use send here to make sure even if one withdrawBalance fails the others will still work bool res = storageContract.withdrawBalance(); return res; } } contract ActivityCore is LogicBase { bool public isActivityCore = true; ActivityStorage activityStorage; event ActivityCreated(uint16 activityId); event ActivityBidSuccess(uint16 activityId, uint16 packId, address winner); function ActivityCore(address _nftAddress, address _storageAddress) LogicBase(_nftAddress, _storageAddress) public { activityStorage = ActivityStorage(_storageAddress); } function createActivity( uint16 _activityId, uint16 _buyLimit, uint128 _packPrice, uint64 _startDate, uint64 _endDate ) external onlyOwner whenNotPaused { activityStorage.createActivity(_activityId, _buyLimit, _packPrice, _startDate, _endDate); emit ActivityCreated(_activityId); } // Very dangerous action and should be only used for testing // Must pause the contract first function deleteActivity( uint16 _activityId ) external onlyOwner whenPaused { activityStorage.deleteActivity(_activityId); } function getActivity( uint16 _activityId ) external view returns ( bool isPause, uint16 buyLimit, uint128 packPrice, uint64 startDate, uint64 endDate ) { return activityStorage.activities(_activityId); } function bid(uint16 _activityId, uint16 _packId) external payable whenNotPaused { bool isPause; uint16 buyLimit; uint128 packPrice; uint64 startDate; uint64 endDate; (isPause, buyLimit, packPrice, startDate, endDate) = activityStorage.activities(_activityId); // not allow to bid when activity is paused require(!isPause); // not allow to bid when activity is not initialized (buyLimit == 0) require(buyLimit > 0); // should send enough ether require(msg.value >= packPrice); // verify startDate & endDate require(now >= startDate && now <= endDate); // this pack is not sold out require(activityStorage.getBuyerAddress(_activityId, _packId) == address(0)); // buyer not exceed buyLimit require(activityStorage.getAddressBoughtCount(_activityId, msg.sender) < buyLimit); // record in blockchain activityStorage.sellPackToAddress(_activityId, _packId, msg.sender); // emit the success event emit ActivityBidSuccess(_activityId, _packId, msg.sender); } } contract CryptoStorage is StorageBase { struct Monster { uint32 matronId; uint32 sireId; uint32 siringWithId; uint16 cooldownIndex; uint16 generation; uint64 cooldownEndBlock; uint64 birthTime; uint16 monsterId; uint32 monsterNum; bytes properties; } // ERC721 tokens Monster[] internal monsters; // total number of monster created from system instead of breeding uint256 public promoCreatedCount; // total number of monster created by system sale address uint256 public systemCreatedCount; // number of monsters in pregnant uint256 public pregnantMonsters; // monsterId => total number mapping (uint256 => uint32) public monsterCurrentNumber; // tokenId => owner address mapping (uint256 => address) public monsterIndexToOwner; // owner address => balance of tokens mapping (address => uint256) public ownershipTokenCount; // tokenId => approved address mapping (uint256 => address) public monsterIndexToApproved; function CryptoStorage() public { // placeholder to make the first available monster to have a tokenId starts from 1 createMonster(0, 0, 0, 0, 0, ""); } function createMonster( uint256 _matronId, uint256 _sireId, uint256 _generation, uint256 _birthTime, uint256 _monsterId, bytes _properties ) public onlyOwner returns (uint256) { require(_matronId == uint256(uint32(_matronId))); require(_sireId == uint256(uint32(_sireId))); require(_generation == uint256(uint16(_generation))); require(_birthTime == uint256(uint64(_birthTime))); require(_monsterId == uint256(uint16(_monsterId))); monsterCurrentNumber[_monsterId]++; Monster memory monster = Monster({ matronId: uint32(_matronId), sireId: uint32(_sireId), siringWithId: 0, cooldownIndex: 0, generation: uint16(_generation), cooldownEndBlock: 0, birthTime: uint64(_birthTime), monsterId: uint16(_monsterId), monsterNum: monsterCurrentNumber[_monsterId], properties: _properties }); uint256 tokenId = monsters.push(monster) - 1; // overflow check require(tokenId == uint256(uint32(tokenId))); return tokenId; } function getMonster(uint256 _tokenId) external view returns ( bool isGestating, bool isReady, uint16 cooldownIndex, uint64 nextActionAt, uint32 siringWithId, uint32 matronId, uint32 sireId, uint64 cooldownEndBlock, uint16 generation, uint64 birthTime, uint32 monsterNum, uint16 monsterId, bytes properties ) { Monster storage monster = monsters[_tokenId]; isGestating = (monster.siringWithId != 0); isReady = (monster.cooldownEndBlock <= block.number); cooldownIndex = monster.cooldownIndex; nextActionAt = monster.cooldownEndBlock; siringWithId = monster.siringWithId; matronId = monster.matronId; sireId = monster.sireId; cooldownEndBlock = monster.cooldownEndBlock; generation = monster.generation; birthTime = monster.birthTime; monsterNum = monster.monsterNum; monsterId = monster.monsterId; properties = monster.properties; } function getMonsterCount() external view returns (uint256) { return monsters.length - 1; } function getMatronId(uint256 _tokenId) external view returns (uint32) { return monsters[_tokenId].matronId; } function getSireId(uint256 _tokenId) external view returns (uint32) { return monsters[_tokenId].sireId; } function getSiringWithId(uint256 _tokenId) external view returns (uint32) { return monsters[_tokenId].siringWithId; } function setSiringWithId(uint256 _tokenId, uint32 _siringWithId) external onlyOwner { monsters[_tokenId].siringWithId = _siringWithId; } function deleteSiringWithId(uint256 _tokenId) external onlyOwner { delete monsters[_tokenId].siringWithId; } function getCooldownIndex(uint256 _tokenId) external view returns (uint16) { return monsters[_tokenId].cooldownIndex; } function setCooldownIndex(uint256 _tokenId) external onlyOwner { monsters[_tokenId].cooldownIndex += 1; } function getGeneration(uint256 _tokenId) external view returns (uint16) { return monsters[_tokenId].generation; } function getCooldownEndBlock(uint256 _tokenId) external view returns (uint64) { return monsters[_tokenId].cooldownEndBlock; } function setCooldownEndBlock(uint256 _tokenId, uint64 _cooldownEndBlock) external onlyOwner { monsters[_tokenId].cooldownEndBlock = _cooldownEndBlock; } function getBirthTime(uint256 _tokenId) external view returns (uint64) { return monsters[_tokenId].birthTime; } function getMonsterId(uint256 _tokenId) external view returns (uint16) { return monsters[_tokenId].monsterId; } function getMonsterNum(uint256 _tokenId) external view returns (uint32) { return monsters[_tokenId].monsterNum; } function getProperties(uint256 _tokenId) external view returns (bytes) { return monsters[_tokenId].properties; } function updateProperties(uint256 _tokenId, bytes _properties) external onlyOwner { monsters[_tokenId].properties = _properties; } function setMonsterIndexToOwner(uint256 _tokenId, address _owner) external onlyOwner { monsterIndexToOwner[_tokenId] = _owner; } function increaseOwnershipTokenCount(address _owner) external onlyOwner { ownershipTokenCount[_owner]++; } function decreaseOwnershipTokenCount(address _owner) external onlyOwner { ownershipTokenCount[_owner]--; } function setMonsterIndexToApproved(uint256 _tokenId, address _approved) external onlyOwner { monsterIndexToApproved[_tokenId] = _approved; } function deleteMonsterIndexToApproved(uint256 _tokenId) external onlyOwner { delete monsterIndexToApproved[_tokenId]; } function increasePromoCreatedCount() external onlyOwner { promoCreatedCount++; } function increaseSystemCreatedCount() external onlyOwner { systemCreatedCount++; } function increasePregnantCounter() external onlyOwner { pregnantMonsters++; } function decreasePregnantCounter() external onlyOwner { pregnantMonsters--; } } contract ClockAuctionStorage is StorageBase { // Represents an auction on an NFT struct Auction { // Current owner of NFT 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; } // Map from token ID to their corresponding auction. mapping (uint256 => Auction) tokenIdToAuction; function addAuction( uint256 _tokenId, address _seller, uint128 _startingPrice, uint128 _endingPrice, uint64 _duration, uint64 _startedAt ) external onlyOwner { tokenIdToAuction[_tokenId] = Auction( _seller, _startingPrice, _endingPrice, _duration, _startedAt ); } function removeAuction(uint256 _tokenId) public onlyOwner { delete tokenIdToAuction[_tokenId]; } function getAuction(uint256 _tokenId) external view returns ( address seller, uint128 startingPrice, uint128 endingPrice, uint64 duration, uint64 startedAt ) { Auction storage auction = tokenIdToAuction[_tokenId]; return ( auction.seller, auction.startingPrice, auction.endingPrice, auction.duration, auction.startedAt ); } function isOnAuction(uint256 _tokenId) external view returns (bool) { return (tokenIdToAuction[_tokenId].startedAt > 0); } function getSeller(uint256 _tokenId) external view returns (address) { return tokenIdToAuction[_tokenId].seller; } function transfer(ERC721 _nonFungibleContract, address _receiver, uint256 _tokenId) external onlyOwner { // it will throw if transfer fails _nonFungibleContract.transfer(_receiver, _tokenId); } } contract SaleClockAuctionStorage is ClockAuctionStorage { bool public isSaleClockAuctionStorage = true; // total accumulate sold count uint256 public totalSoldCount; // last 3 sale price uint256[3] public lastSoldPrices; // current on sale auction count from system uint256 public systemOnSaleCount; // map of on sale token ids from system mapping (uint256 => bool) systemOnSaleTokens; function removeAuction(uint256 _tokenId) public onlyOwner { // first remove auction from state variable super.removeAuction(_tokenId); // update system on sale record if (systemOnSaleTokens[_tokenId]) { delete systemOnSaleTokens[_tokenId]; if (systemOnSaleCount > 0) { systemOnSaleCount--; } } } function recordSystemOnSaleToken(uint256 _tokenId) external onlyOwner { if (!systemOnSaleTokens[_tokenId]) { systemOnSaleTokens[_tokenId] = true; systemOnSaleCount++; } } function recordSoldPrice(uint256 _price) external onlyOwner { lastSoldPrices[totalSoldCount % 3] = _price; totalSoldCount++; } function averageSoldPrice() external view returns (uint256) { if (totalSoldCount == 0) return 0; uint256 sum = 0; uint256 len = (totalSoldCount < 3 ? totalSoldCount : 3); for (uint256 i = 0; i < len; i++) { sum += lastSoldPrices[i]; } return sum / len; } } contract ClockAuction is LogicBase { // Reference to contract tracking auction state variables ClockAuctionStorage public clockAuctionStorage; // Cut owner takes on each auction, measured in basis points (1/100 of a percent). // Values 0-10,000 map to 0%-100% uint256 public ownerCut; // Minimum cut value on each auction (in WEI) uint256 public minCutValue; event AuctionCreated(uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration); event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner, address seller, uint256 sellerProceeds); event AuctionCancelled(uint256 tokenId); function ClockAuction(address _nftAddress, address _storageAddress, uint256 _cut, uint256 _minCutValue) LogicBase(_nftAddress, _storageAddress) public { setOwnerCut(_cut); setMinCutValue(_minCutValue); clockAuctionStorage = ClockAuctionStorage(_storageAddress); } function setOwnerCut(uint256 _cut) public onlyOwner { require(_cut <= 10000); ownerCut = _cut; } function setMinCutValue(uint256 _minCutValue) public onlyOwner { minCutValue = _minCutValue; } function getMinPrice() public view returns (uint256) { // return ownerCut > 0 ? (minCutValue / ownerCut * 10000) : 0; // use minCutValue directly, when the price == minCutValue seller will get no profit return minCutValue; } // Only auction from none system user need to verify the price // System auction can set any price function isValidPrice(uint256 _startingPrice, uint256 _endingPrice) public view returns (bool) { return (_startingPrice < _endingPrice ? _startingPrice : _endingPrice) >= getMinPrice(); } function createAuction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller ) public whenNotPaused { require(_startingPrice == uint256(uint128(_startingPrice))); require(_endingPrice == uint256(uint128(_endingPrice))); require(_duration == uint256(uint64(_duration))); require(msg.sender == address(nonFungibleContract)); // assigning ownership to this clockAuctionStorage when in auction // it will throw if transfer fails nonFungibleContract.transferFrom(_seller, address(clockAuctionStorage), _tokenId); // Require that all auctions have a duration of at least one minute. require(_duration >= 1 minutes); clockAuctionStorage.addAuction( _tokenId, _seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(now) ); emit AuctionCreated(_tokenId, _startingPrice, _endingPrice, _duration); } function cancelAuction(uint256 _tokenId) external { require(clockAuctionStorage.isOnAuction(_tokenId)); address seller = clockAuctionStorage.getSeller(_tokenId); require(msg.sender == seller); _cancelAuction(_tokenId, seller); } function cancelAuctionWhenPaused(uint256 _tokenId) external whenPaused onlyOwner { require(clockAuctionStorage.isOnAuction(_tokenId)); address seller = clockAuctionStorage.getSeller(_tokenId); _cancelAuction(_tokenId, seller); } function getAuction(uint256 _tokenId) public view returns ( address seller, uint256 startingPrice, uint256 endingPrice, uint256 duration, uint256 startedAt ) { require(clockAuctionStorage.isOnAuction(_tokenId)); return clockAuctionStorage.getAuction(_tokenId); } function getCurrentPrice(uint256 _tokenId) external view returns (uint256) { require(clockAuctionStorage.isOnAuction(_tokenId)); return _currentPrice(_tokenId); } function _cancelAuction(uint256 _tokenId, address _seller) internal { clockAuctionStorage.removeAuction(_tokenId); clockAuctionStorage.transfer(nonFungibleContract, _seller, _tokenId); emit AuctionCancelled(_tokenId); } function _bid(uint256 _tokenId, uint256 _bidAmount, address bidder) internal returns (uint256) { require(clockAuctionStorage.isOnAuction(_tokenId)); // Check that the bid is greater than or equal to the current price uint256 price = _currentPrice(_tokenId); require(_bidAmount >= price); address seller = clockAuctionStorage.getSeller(_tokenId); uint256 sellerProceeds = 0; // Remove the auction before sending the fees to the sender so we can't have a reentrancy attack clockAuctionStorage.removeAuction(_tokenId); // Transfer proceeds to seller (if there are any!) if (price > 0) { // Calculate the auctioneer's cut, so this subtraction can't go negative uint256 auctioneerCut = _computeCut(price); sellerProceeds = price - auctioneerCut; // transfer the sellerProceeds seller.transfer(sellerProceeds); } // Calculate any excess funds included with the bid // transfer it back to bidder. // this cannot underflow. uint256 bidExcess = _bidAmount - price; bidder.transfer(bidExcess); emit AuctionSuccessful(_tokenId, price, bidder, seller, sellerProceeds); return price; } function _currentPrice(uint256 _tokenId) internal view returns (uint256) { uint256 secondsPassed = 0; address seller; uint128 startingPrice; uint128 endingPrice; uint64 duration; uint64 startedAt; (seller, startingPrice, endingPrice, duration, startedAt) = clockAuctionStorage.getAuction(_tokenId); if (now > startedAt) { secondsPassed = now - startedAt; } return _computeCurrentPrice( startingPrice, endingPrice, duration, secondsPassed ); } function _computeCurrentPrice( uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, uint256 _secondsPassed ) internal pure returns (uint256) { if (_secondsPassed >= _duration) { return _endingPrice; } else { // this delta can be negative. int256 totalPriceChange = int256(_endingPrice) - int256(_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. int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration); // this result will always end up positive. int256 currentPrice = int256(_startingPrice) + currentPriceChange; return uint256(currentPrice); } } function _computeCut(uint256 _price) internal view returns (uint256) { uint256 cutValue = _price * ownerCut / 10000; if (_price < minCutValue) return cutValue; if (cutValue > minCutValue) return cutValue; return minCutValue; } } contract SaleClockAuction is ClockAuction { bool public isSaleClockAuction = true; address public systemSaleAddress; uint256 public systemStartingPriceMin = 20 finney; uint256 public systemEndingPrice = 0; uint256 public systemAuctionDuration = 1 days; function SaleClockAuction(address _nftAddr, address _storageAddress, address _systemSaleAddress, uint256 _cut, uint256 _minCutValue) ClockAuction(_nftAddr, _storageAddress, _cut, _minCutValue) public { require(SaleClockAuctionStorage(_storageAddress).isSaleClockAuctionStorage()); setSystemSaleAddress(_systemSaleAddress); } function bid(uint256 _tokenId) external payable { uint256 price = _bid(_tokenId, msg.value, msg.sender); clockAuctionStorage.transfer(nonFungibleContract, msg.sender, _tokenId); SaleClockAuctionStorage(clockAuctionStorage).recordSoldPrice(price); } function createSystemAuction(uint256 _tokenId) external { require(msg.sender == address(nonFungibleContract)); createAuction( _tokenId, computeNextSystemSalePrice(), systemEndingPrice, systemAuctionDuration, systemSaleAddress ); SaleClockAuctionStorage(clockAuctionStorage).recordSystemOnSaleToken(_tokenId); } function setSystemSaleAddress(address _systemSaleAddress) public onlyOwner { require(_systemSaleAddress != address(0)); systemSaleAddress = _systemSaleAddress; } function setSystemStartingPriceMin(uint256 _startingPrice) external onlyOwner { require(_startingPrice == uint256(uint128(_startingPrice))); systemStartingPriceMin = _startingPrice; } function setSystemEndingPrice(uint256 _endingPrice) external onlyOwner { require(_endingPrice == uint256(uint128(_endingPrice))); systemEndingPrice = _endingPrice; } function setSystemAuctionDuration(uint256 _duration) external onlyOwner { require(_duration == uint256(uint64(_duration))); systemAuctionDuration = _duration; } function totalSoldCount() external view returns (uint256) { return SaleClockAuctionStorage(clockAuctionStorage).totalSoldCount(); } function systemOnSaleCount() external view returns (uint256) { return SaleClockAuctionStorage(clockAuctionStorage).systemOnSaleCount(); } function averageSoldPrice() external view returns (uint256) { return SaleClockAuctionStorage(clockAuctionStorage).averageSoldPrice(); } function computeNextSystemSalePrice() public view returns (uint256) { uint256 avePrice = SaleClockAuctionStorage(clockAuctionStorage).averageSoldPrice(); require(avePrice == uint256(uint128(avePrice))); uint256 nextPrice = avePrice + (avePrice / 2); if (nextPrice < systemStartingPriceMin) { nextPrice = systemStartingPriceMin; } return nextPrice; } } contract SiringClockAuctionStorage is ClockAuctionStorage { bool public isSiringClockAuctionStorage = true; } contract SiringClockAuction is ClockAuction { bool public isSiringClockAuction = true; function SiringClockAuction(address _nftAddr, address _storageAddress, uint256 _cut, uint256 _minCutValue) ClockAuction(_nftAddr, _storageAddress, _cut, _minCutValue) public { require(SiringClockAuctionStorage(_storageAddress).isSiringClockAuctionStorage()); } function bid(uint256 _tokenId, address bidder) external payable { // can only be called by CryptoZoo require(msg.sender == address(nonFungibleContract)); // get seller before the _bid for the auction will be removed once the bid success address seller = clockAuctionStorage.getSeller(_tokenId); // _bid checks that token ID is valid and will throw if bid fails _bid(_tokenId, msg.value, bidder); // transfer the monster back to the seller, the winner will get the child clockAuctionStorage.transfer(nonFungibleContract, seller, _tokenId); } } contract ZooAccessControl is HasNoContracts { address public ceoAddress; address public cfoAddress; address public cooAddress; modifier onlyCEO() { require(msg.sender == ceoAddress); _; } modifier onlyCFO() { require(msg.sender == cfoAddress); _; } modifier onlyCOO() { require(msg.sender == cooAddress); _; } modifier onlyCLevel() { require( msg.sender == cooAddress || msg.sender == ceoAddress || msg.sender == cfoAddress ); _; } function setCEO(address _newCEO) public onlyCEO { require(_newCEO != address(0)); ceoAddress = _newCEO; } function setCFO(address _newCFO) public onlyCEO { require(_newCFO != address(0)); cfoAddress = _newCFO; } function setCOO(address _newCOO) public onlyCEO { require(_newCOO != address(0)); cooAddress = _newCOO; } } contract Zoo721 is ZooAccessControl, ERC721 { // ERC721 Required string public constant name = "Giftomon"; // ERC721 Required string public constant symbol = "GTOM"; bytes4 constant InterfaceSignature_ERC165 = bytes4(keccak256("supportsInterface(bytes4)")); bytes4 constant InterfaceSignature_ERC721 = bytes4(keccak256('name()')) ^ bytes4(keccak256('symbol()')) ^ bytes4(keccak256('totalSupply()')) ^ bytes4(keccak256('balanceOf(address)')) ^ bytes4(keccak256('ownerOf(uint256)')) ^ bytes4(keccak256('approve(address,uint256)')) ^ bytes4(keccak256('transfer(address,uint256)')) ^ bytes4(keccak256('transferFrom(address,address,uint256)')) ^ bytes4(keccak256('tokensOfOwner(address)')); CryptoStorage public cryptoStorage; function Zoo721(address _storageAddress) public { require(_storageAddress != address(0)); cryptoStorage = CryptoStorage(_storageAddress); } // ERC165 Required function supportsInterface(bytes4 _interfaceID) external view returns (bool) { return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721)); } // ERC721 Required function totalSupply() public view returns (uint) { return cryptoStorage.getMonsterCount(); } // ERC721 Required function balanceOf(address _owner) public view returns (uint256 count) { return cryptoStorage.ownershipTokenCount(_owner); } // ERC721 Required function ownerOf(uint256 _tokenId) external view returns (address owner) { owner = cryptoStorage.monsterIndexToOwner(_tokenId); require(owner != address(0)); } // ERC721 Required function approve(address _to, uint256 _tokenId) external whenNotPaused { require(_owns(msg.sender, _tokenId)); _approve(_tokenId, _to); emit Approval(msg.sender, _to, _tokenId); } // ERC721 Required function transfer(address _to, uint256 _tokenId) external whenNotPaused { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Not allow to transfer to the contract itself except for system sale monsters require(_to != address(this)); // You can only send your own cat. require(_owns(msg.sender, _tokenId)); // Reassign ownership, clear pending approvals, emit Transfer event. _transfer(msg.sender, _to, _tokenId); } // ERC721 Required function transferFrom(address _from, address _to, uint256 _tokenId) external whenNotPaused { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); require(_to != address(this)); // Check for approval and valid ownership require(_approvedFor(msg.sender, _tokenId)); require(_owns(_from, _tokenId)); // Reassign ownership (also clears pending approvals and emits Transfer event). _transfer(_from, _to, _tokenId); } // ERC721 Optional function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 totalTokens = totalSupply(); uint256 resultIndex = 0; uint256 tokenId; for (tokenId = 1; tokenId <= totalTokens; tokenId++) { if (cryptoStorage.monsterIndexToOwner(tokenId) == _owner) { result[resultIndex] = tokenId; resultIndex++; } } return result; } } function _transfer(address _from, address _to, uint256 _tokenId) internal { // increase number of token owned by _to cryptoStorage.increaseOwnershipTokenCount(_to); // transfer ownership cryptoStorage.setMonsterIndexToOwner(_tokenId, _to); // new monster born does not have previous owner if (_from != address(0)) { // decrease number of token owned by _from cryptoStorage.decreaseOwnershipTokenCount(_from); // clear any previously approved ownership exchange cryptoStorage.deleteMonsterIndexToApproved(_tokenId); } emit Transfer(_from, _to, _tokenId); } function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return cryptoStorage.monsterIndexToOwner(_tokenId) == _claimant; } function _approve(uint256 _tokenId, address _approved) internal { cryptoStorage.setMonsterIndexToApproved(_tokenId, _approved); } function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { return cryptoStorage.monsterIndexToApproved(_tokenId) == _claimant; } } contract CryptoZoo is Zoo721 { uint256 public constant SYSTEM_CREATION_LIMIT = 10000; // new monster storage fee for the coo uint256 public autoBirthFee = 2 finney; // an approximation of currently how many seconds are in between blocks. uint256 public secondsPerBlock = 15; // hatch duration in second by hatch times (start from 0) // default to 1 minute if not set and minimum to 1 minute // must be an integral multiple of 1 minute uint32[] public hatchDurationByTimes = [uint32(1 minutes)]; // hatch duration multiple value by generation (start from 0) // multiple = value / 60, 60 is the base value // default to 60 if not set and minimum to 60 // must be an integral multiple of secondsPerBlock uint32[] public hatchDurationMultiByGeneration = [uint32(60)]; // sale auctions SaleClockAuction public saleAuction; // siring auctions SiringClockAuction public siringAuction; // activity core ActivityCore public activityCore; // events event Pregnant(address owner, uint256 matronId, uint256 sireId, uint256 matronCooldownEndBlock, uint256 sireCooldownEndBlock, uint256 breedCost); event Birth(address owner, uint256 tokenId, uint256 matronId, uint256 sireId); // Core Contract of Giftomon function CryptoZoo(address _storageAddress, address _cooAddress, address _cfoAddress) Zoo721(_storageAddress) public { // paused by default paused = true; // ceo defaults the the contract creator ceoAddress = msg.sender; setCOO(_cooAddress); setCFO(_cfoAddress); } function() external payable { require( msg.sender == address(saleAuction) || msg.sender == address(siringAuction) || msg.sender == address(activityCore) || msg.sender == cooAddress ); } // override to allow any CLevel to pause the contract function pause() public onlyCLevel whenNotPaused { super.pause(); } // override to make sure everything is initialized before the unpause function unpause() public onlyCEO whenPaused { // can not unpause when CLevel addresses is not initialized require(ceoAddress != address(0)); require(cooAddress != address(0)); require(cfoAddress != address(0)); // can not unpause when the logic contract is not initialzed require(saleAuction != address(0)); require(siringAuction != address(0)); require(activityCore != address(0)); require(cryptoStorage != address(0)); // can not unpause when ownership of storage contract is not the current contract require(cryptoStorage.owner() == address(this)); super.unpause(); } // Very dangerous action, only when new contract has been proved working // Requires cryptoStorage already transferOwnership to the new contract // This method is only used to transfer the balance (authBirthFee used for giveBirth) to ceo function destroy() external onlyCEO whenPaused { address storageOwner = cryptoStorage.owner(); // owner of cryptoStorage must not be the current contract otherwise the cryptoStorage will forever in accessable require(storageOwner != address(this)); // Transfers the current balance to the ceo and terminates the contract selfdestruct(ceoAddress); } // Very dangerous action, only when new contract has been proved working // Requires cryptoStorage already transferOwnership to the new contract // This method is only used to transfer the balance (authBirthFee used for giveBirth) to the new contract function destroyAndSendToStorageOwner() external onlyCEO whenPaused { address storageOwner = cryptoStorage.owner(); // owner of cryptoStorage must not be the current contract otherwise the cryptoStorage will forever in accessable require(storageOwner != address(this)); // Transfers the current balance to the new owner of the storage contract and terminates the contract selfdestruct(storageOwner); } function setSaleAuctionAddress(address _address) external onlyCEO { SaleClockAuction candidateContract = SaleClockAuction(_address); require(candidateContract.isSaleClockAuction()); saleAuction = candidateContract; } function setSiringAuctionAddress(address _address) external onlyCEO { SiringClockAuction candidateContract = SiringClockAuction(_address); require(candidateContract.isSiringClockAuction()); siringAuction = candidateContract; } function setActivityCoreAddress(address _address) external onlyCEO { ActivityCore candidateContract = ActivityCore(_address); require(candidateContract.isActivityCore()); activityCore = candidateContract; } function withdrawBalance() external onlyCLevel { uint256 balance = address(this).balance; // Subtract all the currently pregnant kittens we have, plus 1 of margin. uint256 subtractFees = (cryptoStorage.pregnantMonsters() + 1) * autoBirthFee; if (balance > subtractFees) { cfoAddress.transfer(balance - subtractFees); } } function withdrawBalancesToNFC() external onlyCLevel { saleAuction.withdrawBalance(); siringAuction.withdrawBalance(); activityCore.withdrawBalance(); cryptoStorage.withdrawBalance(); } function withdrawBalancesToLogic() external onlyCLevel { saleAuction.withdrawBalanceFromStorageContract(); siringAuction.withdrawBalanceFromStorageContract(); activityCore.withdrawBalanceFromStorageContract(); } function setAutoBirthFee(uint256 val) external onlyCOO { autoBirthFee = val; } function setAllHatchConfigs( uint32[] _durationByTimes, uint256 _secs, uint32[] _multiByGeneration ) external onlyCLevel { setHatchDurationByTimes(_durationByTimes); setSecondsPerBlock(_secs); setHatchDurationMultiByGeneration(_multiByGeneration); } function setSecondsPerBlock(uint256 _secs) public onlyCLevel { require(_secs < hatchDurationByTimes[0]); secondsPerBlock = _secs; } // we must do a carefully check when set hatch duration configuration, since wrong value may break the whole cooldown logic function setHatchDurationByTimes(uint32[] _durationByTimes) public onlyCLevel { uint256 len = _durationByTimes.length; // hatch duration should not be empty require(len > 0); // check overflow require(len == uint256(uint16(len))); delete hatchDurationByTimes; uint32 value; for (uint256 idx = 0; idx < len; idx++) { value = _durationByTimes[idx]; // duration must be larger than 1 minute, and must be an integral multiple of 1 minute require(value >= 1 minutes && value % 1 minutes == 0); hatchDurationByTimes.push(value); } } function getHatchDurationByTimes() external view returns (uint32[]) { return hatchDurationByTimes; } // we must do a carefully check when set hatch duration multi configuration, since wrong value may break the whole cooldown logic function setHatchDurationMultiByGeneration(uint32[] _multiByGeneration) public onlyCLevel { uint256 len = _multiByGeneration.length; // multi configuration should not be empty require(len > 0); // check overflow require(len == uint256(uint16(len))); delete hatchDurationMultiByGeneration; uint32 value; for (uint256 idx = 0; idx < len; idx++) { value = _multiByGeneration[idx]; // multiple must be larger than 60, and must be an integral multiple of secondsPerBlock require(value >= 60 && value % secondsPerBlock == 0); hatchDurationMultiByGeneration.push(value); } } function getHatchDurationMultiByGeneration() external view returns (uint32[]) { return hatchDurationMultiByGeneration; } function createPromoMonster( uint32 _monsterId, bytes _properties, address _owner ) public onlyCOO whenNotPaused { require(_owner != address(0)); _createMonster( 0, 0, 0, uint64(now), _monsterId, _properties, _owner ); cryptoStorage.increasePromoCreatedCount(); } function createPromoMonsterWithTokenId( uint32 _monsterId, bytes _properties, address _owner, uint256 _tokenId ) external onlyCOO whenNotPaused { require(_tokenId > 0 && cryptoStorage.getMonsterCount() + 1 == _tokenId); createPromoMonster(_monsterId, _properties, _owner); } function createSystemSaleAuction( uint32 _monsterId, bytes _properties, uint16 _generation ) external onlyCOO whenNotPaused { require(cryptoStorage.systemCreatedCount() < SYSTEM_CREATION_LIMIT); uint256 tokenId = _createMonster( 0, 0, _generation, uint64(now), _monsterId, _properties, saleAuction.systemSaleAddress() ); _approve(tokenId, saleAuction); saleAuction.createSystemAuction(tokenId); cryptoStorage.increaseSystemCreatedCount(); } function createSaleAuction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration ) external whenNotPaused { require(_tokenId > 0); require(_owns(msg.sender, _tokenId)); // the monster must not pregnant othewise the birth child may owned by the the sale auction or the buyer require(!isPregnant(_tokenId)); require(saleAuction.isValidPrice(_startingPrice, _endingPrice)); _approve(_tokenId, saleAuction); // Sale auction throws if inputs are invalid and approve status will be reverted saleAuction.createAuction( _tokenId, _startingPrice, _endingPrice, _duration, msg.sender ); } function createSiringAuction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration ) external whenNotPaused { require(_tokenId > 0); require(_owns(msg.sender, _tokenId)); require(isReadyToBreed(_tokenId)); require(siringAuction.isValidPrice(_startingPrice, _endingPrice)); _approve(_tokenId, siringAuction); // Siring auction throws if inputs are invalid and approve status will be reverted siringAuction.createAuction( _tokenId, _startingPrice, _endingPrice, _duration, msg.sender ); } // breed with the monster siring on market function bidOnSiringAuction( uint256 _sireId, uint256 _matronId ) external payable whenNotPaused { require(_matronId > 0); require(_owns(msg.sender, _matronId)); require(isReadyToBreed(_matronId)); require(isValidMatingPair(_matronId, _sireId)); // Define the current price of the auction. uint256 currentPrice = siringAuction.getCurrentPrice(_sireId); uint256 breedCost = currentPrice + autoBirthFee; require(msg.value >= breedCost); // Siring auction will throw if the bid fails. siringAuction.bid.value(msg.value - autoBirthFee)(_sireId, msg.sender); _breedWith(_matronId, _sireId, breedCost); } // breed with the monster of one's own function breedWithAuto(uint256 _matronId, uint256 _sireId) external payable whenNotPaused { // Checks for payment. require(msg.value >= autoBirthFee); // Caller must own the matron and sire require(_owns(msg.sender, _matronId)); require(_owns(msg.sender, _sireId)); // any monster in auction will be owned by the auction contract address, // so the monster must not in auction if it's owned by the msg.sender // Make sure matron isn't pregnant, or in the middle of a siring cooldown require(isReadyToBreed(_matronId)); // Make sure sire isn't pregnant, or in the middle of a siring cooldown require(isReadyToBreed(_sireId)); // Test that these cats are a valid mating pair. require(isValidMatingPair(_matronId, _sireId)); // All checks passed, monster gets pregnant! _breedWith(_matronId, _sireId, autoBirthFee); } function giveBirth(uint256 _matronId, uint256 _monsterId, uint256 _birthTime, bytes _properties) external whenNotPaused onlyCOO returns (uint256) { // the matron is a valid monster require(cryptoStorage.getBirthTime(_matronId) != 0); uint256 sireId = cryptoStorage.getSiringWithId(_matronId); // the matron is pregnant if and only if this field is set require(sireId != 0); // no need to check cooldown of matron or sire // since giveBirth can only be called by COO // determine higher generation of the parents uint16 parentGen = cryptoStorage.getGeneration(_matronId); uint16 sireGen = cryptoStorage.getGeneration(sireId); if (sireGen > parentGen) parentGen = sireGen; address owner = cryptoStorage.monsterIndexToOwner(_matronId); uint256 tokenId = _createMonster( _matronId, sireId, parentGen + 1, _birthTime, _monsterId, _properties, owner ); // clear pregnant related info cryptoStorage.deleteSiringWithId(_matronId); // decrease pregnant counter. cryptoStorage.decreasePregnantCounter(); // send the blockchain storage fee to the coo msg.sender.transfer(autoBirthFee); return tokenId; } function computeCooldownSeconds(uint16 _hatchTimes, uint16 _generation) public view returns (uint32) { require(hatchDurationByTimes.length > 0); require(hatchDurationMultiByGeneration.length > 0); uint16 hatchTimesMax = uint16(hatchDurationByTimes.length - 1); uint16 hatchTimes = (_hatchTimes > hatchTimesMax ? hatchTimesMax : _hatchTimes); uint16 generationMax = uint16(hatchDurationMultiByGeneration.length - 1); uint16 generation = (_generation > generationMax ? generationMax : _generation); return hatchDurationByTimes[hatchTimes] * hatchDurationMultiByGeneration[generation] / 60; } function isReadyToBreed(uint256 _tokenId) public view returns (bool) { // not pregnant and not in cooldown return (cryptoStorage.getSiringWithId(_tokenId) == 0) && (cryptoStorage.getCooldownEndBlock(_tokenId) <= uint64(block.number)); } function isPregnant(uint256 _tokenId) public view returns (bool) { // A monster is pregnant if and only if this field is set return cryptoStorage.getSiringWithId(_tokenId) != 0; } function isValidMatingPair(uint256 _matronId, uint256 _sireId) public view returns (bool) { // can't breed with itself! if (_matronId == _sireId) { return false; } uint32 matron_of_matron = cryptoStorage.getMatronId(_matronId); uint32 sire_of_matron = cryptoStorage.getSireId(_matronId); uint32 matron_of_sire = cryptoStorage.getMatronId(_sireId); uint32 sire_of_sire = cryptoStorage.getSireId(_sireId); // can't breed with their parents. if (matron_of_matron == _sireId || sire_of_matron == _sireId) return false; if (matron_of_sire == _matronId || sire_of_sire == _matronId) return false; // if either cat is gen zero, they can breed without siblings check if (matron_of_sire == 0 || matron_of_matron == 0) return true; // can't breed with full or half siblings. if (matron_of_sire == matron_of_matron || matron_of_sire == sire_of_matron) return false; if (sire_of_sire == matron_of_matron || sire_of_sire == sire_of_matron) return false; return true; } function _createMonster( uint256 _matronId, uint256 _sireId, uint256 _generation, uint256 _birthTime, uint256 _monsterId, bytes _properties, address _owner ) internal returns (uint256) { uint256 tokenId = cryptoStorage.createMonster( _matronId, _sireId, _generation, _birthTime, _monsterId, _properties ); _transfer(0, _owner, tokenId); emit Birth(_owner, tokenId, _matronId, _sireId); return tokenId; } function _breedWith(uint256 _matronId, uint256 _sireId, uint256 _breedCost) internal { // Mark the matron as pregnant, keeping track of who the sire is. cryptoStorage.setSiringWithId(_matronId, uint32(_sireId)); // Trigger the cooldown for both parents. uint64 sireCooldownEndBlock = _triggerCooldown(_sireId); uint64 matronCooldownEndBlock = _triggerCooldown(_matronId); // increase pregnant counter. cryptoStorage.increasePregnantCounter(); // give birth time depends on the shorter cooldown of the two parents emit Pregnant( cryptoStorage.monsterIndexToOwner(_matronId), _matronId, _sireId, matronCooldownEndBlock, sireCooldownEndBlock, _breedCost ); } // Compute an estimation of the cooldown time in blocks (based on current cooldownIndex). function _triggerCooldown(uint256 _tokenId) internal returns (uint64) { uint32 cooldownSeconds = computeCooldownSeconds(cryptoStorage.getCooldownIndex(_tokenId), cryptoStorage.getGeneration(_tokenId)); uint64 cooldownEndBlock = uint64((cooldownSeconds / secondsPerBlock) + block.number); cryptoStorage.setCooldownEndBlock(_tokenId, cooldownEndBlock); // increate hatch times by 1 cryptoStorage.setCooldownIndex(_tokenId); return cooldownEndBlock; } }
the matron is a valid monster the matron is pregnant if and only if this field is set no need to check cooldown of matron or sire since giveBirth can only be called by COO determine higher generation of the parents clear pregnant related info decrease pregnant counter. send the blockchain storage fee to the coo
function giveBirth(uint256 _matronId, uint256 _monsterId, uint256 _birthTime, bytes _properties) external whenNotPaused onlyCOO returns (uint256) { require(cryptoStorage.getBirthTime(_matronId) != 0); uint256 sireId = cryptoStorage.getSiringWithId(_matronId); require(sireId != 0); uint16 parentGen = cryptoStorage.getGeneration(_matronId); uint16 sireGen = cryptoStorage.getGeneration(sireId); if (sireGen > parentGen) parentGen = sireGen; address owner = cryptoStorage.monsterIndexToOwner(_matronId); uint256 tokenId = _createMonster( _matronId, sireId, parentGen + 1, _birthTime, _monsterId, _properties, owner ); cryptoStorage.deleteSiringWithId(_matronId); cryptoStorage.decreasePregnantCounter(); msg.sender.transfer(autoBirthFee); return tokenId; }
34,088
pragma solidity ^0.4.18; // ---------------------------------------------------------------------------- // 'ADE' 'AdeCoin' token contract // // Symbol : ADE // Name : AdeCoin // Total supply: Generated from contributions // Decimals : 8 // // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // Safe maths // ---------------------------------------------------------------------------- contract SafeMath { function safeAdd(uint a, uint b) internal pure returns (uint c) { c = a + b; require(c >= a); } function safeSub(uint a, uint b) internal pure returns (uint c) { require(b <= a); c = a - b; } function safeMul(uint a, uint b) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function safeDiv(uint a, uint b) internal pure returns (uint c) { require(b > 0); c = a / b; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event TransferSell(address indexed from, uint tokens, uint eth); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // ---------------------------------------------------------------------------- // Contract function to receive approval and execute function in one call // // Borrowed from MiniMeToken // ---------------------------------------------------------------------------- contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes data) public; } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); function Owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals // Receives ETH and generates tokens // ---------------------------------------------------------------------------- contract ADEToken is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public totalSupply; uint public sellRate; uint public buyRate; uint private lockRate = 30 days; struct lockPosition{ uint time; uint count; uint releaseRate; } mapping(address => lockPosition) private lposition; // locked account dictionary that maps addresses to boolean mapping (address => bool) private lockedAccounts; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; modifier is_not_locked(address _address) { if (lockedAccounts[_address] == true) revert(); _; } modifier validate_address(address _address) { if (_address == address(0)) revert(); _; } modifier is_locked(address _address) { if (lockedAccounts[_address] != true) revert(); _; } modifier validate_position(address _address,uint count) { if(balances[_address] < count * 10**uint(decimals)) revert(); if(lposition[_address].count > 0 && (balances[_address] - (count * 10**uint(decimals))) < lposition[_address].count && now < lposition[_address].time) revert(); checkPosition(_address,count); _; } function checkPosition(address _address,uint count) private view { if(lposition[_address].releaseRate < 100 && lposition[_address].count > 0){ uint _rate = safeDiv(100,lposition[_address].releaseRate); uint _time = lposition[_address].time; uint _tmpRate = lposition[_address].releaseRate; uint _tmpRateAll = 0; uint _count = 0; for(uint _a=1;_a<=_rate;_a++){ if(now >= _time){ _count = _a; _tmpRateAll = safeAdd(_tmpRateAll,_tmpRate); _time = safeAdd(_time,lockRate); } } if(_count < _rate && lposition[_address].count > 0 && (balances[_address] - count * 10**uint(decimals)) < (lposition[_address].count - safeDiv(lposition[_address].count*_tmpRateAll,100)) && now >= lposition[_address].time) revert(); } } event _lockAccount(address _add); event _unlockAccount(address _add); function () public payable{ require(owner != msg.sender); require(buyRate > 0); require(msg.value >= 0.1 ether && msg.value <= 1000 ether); uint tokens; tokens = msg.value / (1 ether * 1 wei / buyRate); require(balances[owner] >= tokens * 10**uint(decimals)); balances[msg.sender] = safeAdd(balances[msg.sender], tokens * 10**uint(decimals)); balances[owner] = safeSub(balances[owner], tokens * 10**uint(decimals)); } // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function ADEToken(uint _sellRate,uint _buyRate) public payable { symbol = "ADE"; name = "AdeCoin"; decimals = 8; totalSupply = 2000000000 * 10**uint(decimals); balances[owner] = totalSupply; Transfer(address(0), owner, totalSupply); sellRate = _sellRate; buyRate = _buyRate; } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public is_not_locked(msg.sender) is_not_locked(to) validate_position(msg.sender,tokens / (10**uint(decimals))) returns (bool success) { require(to != msg.sender); require(tokens > 0); require(balances[msg.sender] >= tokens); balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public is_not_locked(msg.sender) is_not_locked(spender) validate_position(msg.sender,tokens / (10**uint(decimals))) returns (bool success) { require(spender != msg.sender); require(tokens > 0); require(balances[msg.sender] >= tokens); allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public is_not_locked(msg.sender) is_not_locked(from) is_not_locked(to) validate_position(from,tokens / (10**uint(decimals))) returns (bool success) { require(transferFromCheck(from,to,tokens)); return true; } function transferFromCheck(address from,address to,uint tokens) private returns (bool success) { require(tokens > 0); require(from != msg.sender && msg.sender != to && from != to); require(balances[from] >= tokens && allowed[from][msg.sender] >= tokens); balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account. The `spender` contract function // `receiveApproval(...)` is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Sall a token from a contract // ------------------------------------------------------------------------ function sellCoin(address seller, uint amount) public onlyOwner is_not_locked(seller) validate_position(seller,amount){ require(balances[seller] >= amount * 10**uint(decimals)); require(sellRate > 0); require(seller != msg.sender); uint tmpAmount = amount * (1 ether * 1 wei / sellRate); balances[owner] += amount * 10**uint(decimals); balances[seller] -= amount * 10**uint(decimals); seller.transfer(tmpAmount); TransferSell(seller, amount * 10**uint(decimals), tmpAmount); } // set rate function setRate(uint _buyRate,uint _sellRate) public onlyOwner { require(_buyRate > 0); require(_sellRate > 0); require(_buyRate < _sellRate); buyRate = _buyRate; sellRate = _sellRate; } //set lock position function setLockPostion(address _add,uint _count,uint _time,uint _releaseRate) public is_not_locked(_add) onlyOwner { require(_time > now); require(_count > 0); require(_releaseRate > 0 && _releaseRate <= 100); require(_releaseRate == 2 || _releaseRate == 4 || _releaseRate == 5 || _releaseRate == 10 || _releaseRate == 20 || _releaseRate == 25 || _releaseRate == 50); require(balances[_add] >= _count * 10**uint(decimals)); lposition[_add].time = _time; lposition[_add].count = _count * 10**uint(decimals); lposition[_add].releaseRate = _releaseRate; } // lockAccount function lockStatus(address _owner) public is_not_locked(_owner) validate_address(_owner) onlyOwner { lockedAccounts[_owner] = true; _lockAccount(_owner); } /// @notice only the admin is allowed to unlock accounts. /// @param _owner the address of the account to be unlocked function unlockStatus(address _owner) public is_locked(_owner) validate_address(_owner) onlyOwner { lockedAccounts[_owner] = false; _unlockAccount(_owner); } //get lockedaccount function getLockStatus(address _owner) public view returns (bool _lockStatus) { return lockedAccounts[_owner]; } //get lockPosition info function getLockPosition(address _add) public view returns(uint time,uint count,uint rate,uint scount) { return (lposition[_add].time,lposition[_add].count,lposition[_add].releaseRate,positionScount(_add)); } function positionScount(address _add) private view returns (uint count){ uint _rate = safeDiv(100,lposition[_add].releaseRate); uint _time = lposition[_add].time; uint _tmpRate = lposition[_add].releaseRate; uint _tmpRateAll = 0; for(uint _a=1;_a<=_rate;_a++){ if(now >= _time){ _tmpRateAll = safeAdd(_tmpRateAll,_tmpRate); _time = safeAdd(_time,lockRate); } } return (lposition[_add].count - safeDiv(lposition[_add].count*_tmpRateAll,100)); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
------------------------------------------------------------------------ Sall a token from a contract ------------------------------------------------------------------------
function sellCoin(address seller, uint amount) public onlyOwner is_not_locked(seller) validate_position(seller,amount){ require(balances[seller] >= amount * 10**uint(decimals)); require(sellRate > 0); require(seller != msg.sender); uint tmpAmount = amount * (1 ether * 1 wei / sellRate); balances[owner] += amount * 10**uint(decimals); balances[seller] -= amount * 10**uint(decimals); seller.transfer(tmpAmount); TransferSell(seller, amount * 10**uint(decimals), tmpAmount); }
1,561,415
pragma solidity ^0.5.0; /** * @title Tellor Transfer * @dev Contais the methods related to transfers and ERC20. Tellor.sol and TellorGetters.sol * reference this library for function's logic. */ library TellorTransfer { using SafeMath for uint256; event Approval(address indexed _owner, address indexed _spender, uint256 _value); //ERC20 Approval event event Transfer(address indexed _from, address indexed _to, uint256 _value); //ERC20 Transfer Event /*Functions*/ /** * @dev Allows for a transfer of tokens to _to * @param _to The address to send tokens to * @param _amount The amount of tokens to send * @return true if transfer is successful */ function transfer(TellorStorage.TellorStorageStruct storage self, address _to, uint256 _amount) public returns (bool success) { doTransfer(self, msg.sender, _to, _amount); return true; } /** * @notice Send _amount tokens to _to from _from on the condition it * is approved by _from * @param _from The address holding the tokens being transferred * @param _to The address of the recipient * @param _amount The amount of tokens to be transferred * @return True if the transfer was successful */ function transferFrom(TellorStorage.TellorStorageStruct storage self, address _from, address _to, uint256 _amount) public returns (bool success) { require(self.allowed[_from][msg.sender] >= _amount, "Allowance is wrong"); self.allowed[_from][msg.sender] -= _amount; doTransfer(self, _from, _to, _amount); return true; } /** * @dev This function approves a _spender an _amount of tokens to use * @param _spender address * @param _amount amount the spender is being approved for * @return true if spender appproved successfully */ function approve(TellorStorage.TellorStorageStruct storage self, address _spender, uint256 _amount) public returns (bool) { require(_spender != address(0), "Spender is 0-address"); self.allowed[msg.sender][_spender] = _amount; emit Approval(msg.sender, _spender, _amount); return true; } /** * @param _user address of party with the balance * @param _spender address of spender of parties said balance * @return Returns the remaining allowance of tokens granted to the _spender from the _user */ function allowance(TellorStorage.TellorStorageStruct storage self, address _user, address _spender) public view returns (uint256) { return self.allowed[_user][_spender]; } /** * @dev Completes POWO transfers by updating the balances on the current block number * @param _from address to transfer from * @param _to addres to transfer to * @param _amount to transfer */ function doTransfer(TellorStorage.TellorStorageStruct storage self, address _from, address _to, uint256 _amount) public { require(_amount > 0, "Tried to send non-positive amount"); require(_to != address(0), "Receiver is 0 address"); //allowedToTrade checks the stakeAmount is removed from balance if the _user is staked require(allowedToTrade(self, _from, _amount), "Stake amount was not removed from balance"); uint256 previousBalance = balanceOfAt(self, _from, block.number); updateBalanceAtNow(self.balances[_from], previousBalance - _amount); previousBalance = balanceOfAt(self, _to, block.number); require(previousBalance + _amount >= previousBalance, "Overflow happened"); // Check for overflow updateBalanceAtNow(self.balances[_to], previousBalance + _amount); emit Transfer(_from, _to, _amount); } /** * @dev Gets balance of owner specified * @param _user is the owner address used to look up the balance * @return Returns the balance associated with the passed in _user */ function balanceOf(TellorStorage.TellorStorageStruct storage self, address _user) public view returns (uint256) { return balanceOfAt(self, _user, block.number); } /** * @dev Queries the balance of _user at a specific _blockNumber * @param _user The address from which the balance will be retrieved * @param _blockNumber The block number when the balance is queried * @return The balance at _blockNumber specified */ function balanceOfAt(TellorStorage.TellorStorageStruct storage self, address _user, uint256 _blockNumber) public view returns (uint256) { if ((self.balances[_user].length == 0) || (self.balances[_user][0].fromBlock > _blockNumber)) { return 0; } else { return getBalanceAt(self.balances[_user], _blockNumber); } } /** * @dev Getter for balance for owner on the specified _block number * @param checkpoints gets the mapping for the balances[owner] * @param _block is the block number to search the balance on * @return the balance at the checkpoint */ function getBalanceAt(TellorStorage.Checkpoint[] storage checkpoints, uint256 _block) public view returns (uint256) { if (checkpoints.length == 0) return 0; if (_block >= checkpoints[checkpoints.length - 1].fromBlock) return checkpoints[checkpoints.length - 1].value; if (_block < checkpoints[0].fromBlock) return 0; // Binary search of the value in the array uint256 min = 0; uint256 max = checkpoints.length - 1; while (max > min) { uint256 mid = (max + min + 1) / 2; if (checkpoints[mid].fromBlock <= _block) { min = mid; } else { max = mid - 1; } } return checkpoints[min].value; } /** * @dev This function returns whether or not a given user is allowed to trade a given amount * and removing the staked amount from their balance if they are staked * @param _user address of user * @param _amount to check if the user can spend * @return true if they are allowed to spend the amount being checked */ function allowedToTrade(TellorStorage.TellorStorageStruct storage self, address _user, uint256 _amount) public view returns (bool) { if (self.stakerDetails[_user].currentStatus > 0) { //Removes the stakeAmount from balance if the _user is staked if (balanceOf(self, _user).sub(self.uintVars[keccak256("stakeAmount")]).sub(_amount) >= 0) { return true; } } else if (balanceOf(self, _user).sub(_amount) >= 0) { return true; } return false; } /** * @dev Updates balance for from and to on the current block number via doTransfer * @param checkpoints gets the mapping for the balances[owner] * @param _value is the new balance */ function updateBalanceAtNow(TellorStorage.Checkpoint[] storage checkpoints, uint256 _value) public { if ((checkpoints.length == 0) || (checkpoints[checkpoints.length - 1].fromBlock < block.number)) { TellorStorage.Checkpoint storage newCheckPoint = checkpoints[checkpoints.length++]; newCheckPoint.fromBlock = uint128(block.number); newCheckPoint.value = uint128(_value); } else { TellorStorage.Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length - 1]; oldCheckPoint.value = uint128(_value); } } } //import "./SafeMath.sol"; /** * @title Tellor Dispute * @dev Contains the methods related to disputes. Tellor.sol references this library for function's logic. */ library TellorDispute { using SafeMath for uint256; using SafeMath for int256; //emitted when a new dispute is initialized event NewDispute(uint256 indexed _disputeId, uint256 indexed _requestId, uint256 _timestamp, address _miner); //emitted when a new vote happens event Voted(uint256 indexed _disputeID, bool _position, address indexed _voter); //emitted upon dispute tally event DisputeVoteTallied(uint256 indexed _disputeID, int256 _result, address indexed _reportedMiner, address _reportingParty, bool _active); event NewTellorAddress(address _newTellor); //emmited when a proposed fork is voted true /*Functions*/ /** * @dev Helps initialize a dispute by assigning it a disputeId * when a miner returns a false on the validate array(in Tellor.ProofOfWork) it sends the * invalidated value information to POS voting * @param _requestId being disputed * @param _timestamp being disputed * @param _minerIndex the index of the miner that submitted the value being disputed. Since each official value * requires 5 miners to submit a value. */ function beginDispute(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _timestamp, uint256 _minerIndex) public { TellorStorage.Request storage _request = self.requestDetails[_requestId]; //require that no more than a day( (24 hours * 60 minutes)/10minutes=144 blocks) has gone by since the value was "mined" require(now - _timestamp <= 1 days, "The value was mined more than a day ago"); require(_request.minedBlockNum[_timestamp] > 0, "Mined block is 0"); require(_minerIndex < 5, "Miner index is wrong"); //_miner is the miner being disputed. For every mined value 5 miners are saved in an array and the _minerIndex //provided by the party initiating the dispute address _miner = _request.minersByValue[_timestamp][_minerIndex]; bytes32 _hash = keccak256(abi.encodePacked(_miner, _requestId, _timestamp)); //Ensures that a dispute is not already open for the that miner, requestId and timestamp require(self.disputeIdByDisputeHash[_hash] == 0, "Dispute is already open"); TellorTransfer.doTransfer(self, msg.sender, address(this), self.uintVars[keccak256("disputeFee")]); //Increase the dispute count by 1 self.uintVars[keccak256("disputeCount")] = self.uintVars[keccak256("disputeCount")] + 1; //Sets the new disputeCount as the disputeId uint256 disputeId = self.uintVars[keccak256("disputeCount")]; //maps the dispute hash to the disputeId self.disputeIdByDisputeHash[_hash] = disputeId; //maps the dispute to the Dispute struct self.disputesById[disputeId] = TellorStorage.Dispute({ hash: _hash, isPropFork: false, reportedMiner: _miner, reportingParty: msg.sender, proposedForkAddress: address(0), executed: false, disputeVotePassed: false, tally: 0 }); //Saves all the dispute variables for the disputeId self.disputesById[disputeId].disputeUintVars[keccak256("requestId")] = _requestId; self.disputesById[disputeId].disputeUintVars[keccak256("timestamp")] = _timestamp; self.disputesById[disputeId].disputeUintVars[keccak256("value")] = _request.valuesByTimestamp[_timestamp][_minerIndex]; self.disputesById[disputeId].disputeUintVars[keccak256("minExecutionDate")] = now + 7 days; self.disputesById[disputeId].disputeUintVars[keccak256("blockNumber")] = block.number; self.disputesById[disputeId].disputeUintVars[keccak256("minerSlot")] = _minerIndex; self.disputesById[disputeId].disputeUintVars[keccak256("fee")] = self.uintVars[keccak256("disputeFee")]; //Values are sorted as they come in and the official value is the median of the first five //So the "official value" miner is always minerIndex==2. If the official value is being //disputed, it sets its status to inDispute(currentStatus = 3) so that users are made aware it is under dispute if (_minerIndex == 2) { self.requestDetails[_requestId].inDispute[_timestamp] = true; } self.stakerDetails[_miner].currentStatus = 3; emit NewDispute(disputeId, _requestId, _timestamp, _miner); } /** * @dev Allows token holders to vote * @param _disputeId is the dispute id * @param _supportsDispute is the vote (true=the dispute has basis false = vote against dispute) */ function vote(TellorStorage.TellorStorageStruct storage self, uint256 _disputeId, bool _supportsDispute) public { TellorStorage.Dispute storage disp = self.disputesById[_disputeId]; //Get the voteWeight or the balance of the user at the time/blockNumber the disupte began uint256 voteWeight = TellorTransfer.balanceOfAt(self, msg.sender, disp.disputeUintVars[keccak256("blockNumber")]); //Require that the msg.sender has not voted require(disp.voted[msg.sender] != true, "Sender has already voted"); //Requre that the user had a balance >0 at time/blockNumber the disupte began require(voteWeight > 0, "User balance is 0"); //ensures miners that are under dispute cannot vote require(self.stakerDetails[msg.sender].currentStatus != 3, "Miner is under dispute"); //Update user voting status to true disp.voted[msg.sender] = true; //Update the number of votes for the dispute disp.disputeUintVars[keccak256("numberOfVotes")] += 1; //Update the quorum by adding the voteWeight disp.disputeUintVars[keccak256("quorum")] += voteWeight; //If the user supports the dispute increase the tally for the dispute by the voteWeight //otherwise decrease it if (_supportsDispute) { disp.tally = disp.tally.add(int256(voteWeight)); } else { disp.tally = disp.tally.sub(int256(voteWeight)); } //Let the network know the user has voted on the dispute and their casted vote emit Voted(_disputeId, _supportsDispute, msg.sender); } /** * @dev tallies the votes. * @param _disputeId is the dispute id */ function tallyVotes(TellorStorage.TellorStorageStruct storage self, uint256 _disputeId) public { TellorStorage.Dispute storage disp = self.disputesById[_disputeId]; TellorStorage.Request storage _request = self.requestDetails[disp.disputeUintVars[keccak256("requestId")]]; //Ensure this has not already been executed/tallied require(disp.executed == false, "Dispute has been already executed"); //Ensure the time for voting has elapsed require(now > disp.disputeUintVars[keccak256("minExecutionDate")], "Time for voting haven't elapsed"); //If the vote is not a proposed fork if (disp.isPropFork == false) { TellorStorage.StakeInfo storage stakes = self.stakerDetails[disp.reportedMiner]; //If the vote for disputing a value is succesful(disp.tally >0) then unstake the reported // miner and transfer the stakeAmount and dispute fee to the reporting party if (disp.tally > 0) { //if reported miner stake has not been slashed yet, slash them and return the fee to reporting party if (stakes.currentStatus == 3) { //Changing the currentStatus and startDate unstakes the reported miner and allows for the //transfer of the stakeAmount stakes.currentStatus = 0; stakes.startDate = now - (now % 86400); //Decreases the stakerCount since the miner's stake is being slashed self.uintVars[keccak256("stakerCount")]--; updateDisputeFee(self); //Transfers the StakeAmount from the reporded miner to the reporting party TellorTransfer.doTransfer(self, disp.reportedMiner, disp.reportingParty, self.uintVars[keccak256("stakeAmount")]); //Returns the dispute fee to the reportingParty TellorTransfer.doTransfer(self, address(this), disp.reportingParty, disp.disputeUintVars[keccak256("fee")]); //if reported miner stake was already slashed, return the fee to other reporting paties } else{ TellorTransfer.doTransfer(self, address(this), disp.reportingParty, disp.disputeUintVars[keccak256("fee")]); } //Set the dispute state to passed/true disp.disputeVotePassed = true; //If the dispute was succeful(miner found guilty) then update the timestamp value to zero //so that users don't use this datapoint if (_request.inDispute[disp.disputeUintVars[keccak256("timestamp")]] == true) { _request.finalValues[disp.disputeUintVars[keccak256("timestamp")]] = 0; } //If the vote for disputing a value is unsuccesful then update the miner status from being on //dispute(currentStatus=3) to staked(currentStatus =1) and tranfer the dispute fee to the miner } else { //Update the miner's current status to staked(currentStatus = 1) stakes.currentStatus = 1; //tranfer the dispute fee to the miner TellorTransfer.doTransfer(self, address(this), disp.reportedMiner, disp.disputeUintVars[keccak256("fee")]); if (_request.inDispute[disp.disputeUintVars[keccak256("timestamp")]] == true) { _request.inDispute[disp.disputeUintVars[keccak256("timestamp")]] = false; } } //If the vote is for a proposed fork require a 20% quorum before executing the update to the new tellor contract address } else { if (disp.tally > 0) { require( disp.disputeUintVars[keccak256("quorum")] > ((self.uintVars[keccak256("total_supply")] * 20) / 100), "Quorum is not reached" ); self.addressVars[keccak256("tellorContract")] = disp.proposedForkAddress; disp.disputeVotePassed = true; emit NewTellorAddress(disp.proposedForkAddress); } } //update the dispute status to executed disp.executed = true; emit DisputeVoteTallied(_disputeId, disp.tally, disp.reportedMiner, disp.reportingParty, disp.disputeVotePassed); } /** * @dev Allows for a fork to be proposed * @param _propNewTellorAddress address for new proposed Tellor */ function proposeFork(TellorStorage.TellorStorageStruct storage self, address _propNewTellorAddress) public { bytes32 _hash = keccak256(abi.encodePacked(_propNewTellorAddress)); require(self.disputeIdByDisputeHash[_hash] == 0, ""); TellorTransfer.doTransfer(self, msg.sender, address(this), self.uintVars[keccak256("disputeFee")]); //This is the fork fee self.uintVars[keccak256("disputeCount")]++; uint256 disputeId = self.uintVars[keccak256("disputeCount")]; self.disputeIdByDisputeHash[_hash] = disputeId; self.disputesById[disputeId] = TellorStorage.Dispute({ hash: _hash, isPropFork: true, reportedMiner: msg.sender, reportingParty: msg.sender, proposedForkAddress: _propNewTellorAddress, executed: false, disputeVotePassed: false, tally: 0 }); self.disputesById[disputeId].disputeUintVars[keccak256("blockNumber")] = block.number; self.disputesById[disputeId].disputeUintVars[keccak256("fee")] = self.uintVars[keccak256("disputeFee")]; self.disputesById[disputeId].disputeUintVars[keccak256("minExecutionDate")] = now + 7 days; } /** * @dev this function allows the dispute fee to fluctuate based on the number of miners on the system. * The floor for the fee is 15e18. */ function updateDisputeFee(TellorStorage.TellorStorageStruct storage self) public { //if the number of staked miners divided by the target count of staked miners is less than 1 if ((self.uintVars[keccak256("stakerCount")] * 1000) / self.uintVars[keccak256("targetMiners")] < 1000) { //Set the dispute fee at stakeAmt * (1- stakerCount/targetMiners) //or at the its minimum of 15e18 self.uintVars[keccak256("disputeFee")] = SafeMath.max( 15e18, self.uintVars[keccak256("stakeAmount")].mul( 1000 - (self.uintVars[keccak256("stakerCount")] * 1000) / self.uintVars[keccak256("targetMiners")] ) / 1000 ); } else { //otherwise set the dispute fee at 15e18 (the floor/minimum fee allowed) self.uintVars[keccak256("disputeFee")] = 15e18; } } } /** * itle Tellor Dispute * @dev Contais the methods related to miners staking and unstaking. Tellor.sol * references this library for function's logic. */ library TellorStake { event NewStake(address indexed _sender); //Emits upon new staker event StakeWithdrawn(address indexed _sender); //Emits when a staker is now no longer staked event StakeWithdrawRequested(address indexed _sender); //Emits when a staker begins the 7 day withdraw period /*Functions*/ /** * @dev This function stakes the five initial miners, sets the supply and all the constant variables. * This function is called by the constructor function on TellorMaster.sol */ function init(TellorStorage.TellorStorageStruct storage self) public { require(self.uintVars[keccak256("decimals")] == 0, "Too many decimals"); //Give this contract 6000 Tellor Tributes so that it can stake the initial 6 miners TellorTransfer.updateBalanceAtNow(self.balances[address(this)], 2**256 - 1 - 6000e18); // //the initial 5 miner addresses are specfied below // //changed payable[5] to 6 address payable[6] memory _initalMiners = [ address(0xE037EC8EC9ec423826750853899394dE7F024fee), address(0xcdd8FA31AF8475574B8909F135d510579a8087d3), address(0xb9dD5AfD86547Df817DA2d0Fb89334A6F8eDd891), address(0x230570cD052f40E14C14a81038c6f3aa685d712B), address(0x3233afA02644CCd048587F8ba6e99b3C00A34DcC), address(0xe010aC6e0248790e08F42d5F697160DEDf97E024) ]; //Stake each of the 5 miners specified above for (uint256 i = 0; i < 6; i++) { //6th miner to allow for dispute //Miner balance is set at 1000e18 at the block that this function is ran TellorTransfer.updateBalanceAtNow(self.balances[_initalMiners[i]], 1000e18); newStake(self, _initalMiners[i]); } //update the total suppply self.uintVars[keccak256("total_supply")] += 6000e18; //6th miner to allow for dispute //set Constants self.uintVars[keccak256("decimals")] = 18; self.uintVars[keccak256("targetMiners")] = 200; self.uintVars[keccak256("stakeAmount")] = 1000e18; self.uintVars[keccak256("disputeFee")] = 970e18; self.uintVars[keccak256("timeTarget")] = 600; self.uintVars[keccak256("timeOfLastNewValue")] = now - (now % self.uintVars[keccak256("timeTarget")]); self.uintVars[keccak256("difficulty")] = 1; } /** * @dev This function allows stakers to request to withdraw their stake (no longer stake) * once they lock for withdraw(stakes.currentStatus = 2) they are locked for 7 days before they * can withdraw the deposit */ function requestStakingWithdraw(TellorStorage.TellorStorageStruct storage self) public { TellorStorage.StakeInfo storage stakes = self.stakerDetails[msg.sender]; //Require that the miner is staked require(stakes.currentStatus == 1, "Miner is not staked"); //Change the miner staked to locked to be withdrawStake stakes.currentStatus = 2; //Change the startDate to now since the lock up period begins now //and the miner can only withdraw 7 days later from now(check the withdraw function) stakes.startDate = now - (now % 86400); //Reduce the staker count self.uintVars[keccak256("stakerCount")] -= 1; TellorDispute.updateDisputeFee(self); emit StakeWithdrawRequested(msg.sender); } /** * @dev This function allows users to withdraw their stake after a 7 day waiting period from request */ function withdrawStake(TellorStorage.TellorStorageStruct storage self) public { TellorStorage.StakeInfo storage stakes = self.stakerDetails[msg.sender]; //Require the staker has locked for withdraw(currentStatus ==2) and that 7 days have //passed by since they locked for withdraw require(now - (now % 86400) - stakes.startDate >= 7 days, "7 days didn't pass"); require(stakes.currentStatus == 2, "Miner was not locked for withdrawal"); stakes.currentStatus = 0; emit StakeWithdrawn(msg.sender); } /** * @dev This function allows miners to deposit their stake. */ function depositStake(TellorStorage.TellorStorageStruct storage self) public { newStake(self, msg.sender); //self adjusting disputeFee TellorDispute.updateDisputeFee(self); } /** * @dev This function is used by the init function to succesfully stake the initial 5 miners. * The function updates their status/state and status start date so they are locked it so they can't withdraw * and updates the number of stakers in the system. */ function newStake(TellorStorage.TellorStorageStruct storage self, address staker) internal { require(TellorTransfer.balanceOf(self, staker) >= self.uintVars[keccak256("stakeAmount")], "Balance is lower than stake amount"); //Ensure they can only stake if they are not currrently staked or if their stake time frame has ended //and they are currently locked for witdhraw require(self.stakerDetails[staker].currentStatus == 0 || self.stakerDetails[staker].currentStatus == 2, "Miner is in the wrong state"); self.uintVars[keccak256("stakerCount")] += 1; self.stakerDetails[staker] = TellorStorage.StakeInfo({ currentStatus: 1, //this resets their stake start date to today startDate: now - (now % 86400) }); emit NewStake(staker); } } //Slightly modified SafeMath library - includes a min and max function, removes useless div function library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function add(int256 a, int256 b) internal pure returns (int256 c) { if (b > 0) { c = a + b; assert(c >= a); } else { c = a + b; assert(c <= a); } } function max(uint256 a, uint256 b) internal pure returns (uint256) { return a > b ? a : b; } function max(int256 a, int256 b) internal pure returns (uint256) { return a > b ? uint256(a) : uint256(b); } function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function sub(int256 a, int256 b) internal pure returns (int256 c) { if (b > 0) { c = a - b; assert(c <= a); } else { c = a - b; assert(c >= a); } } } /** * @title Tellor Oracle Storage Library * @dev Contains all the variables/structs used by Tellor */ library TellorStorage { //Internal struct for use in proof-of-work submission struct Details { uint256 value; address miner; } struct Dispute { bytes32 hash; //unique hash of dispute: keccak256(_miner,_requestId,_timestamp) int256 tally; //current tally of votes for - against measure bool executed; //is the dispute settled bool disputeVotePassed; //did the vote pass? bool isPropFork; //true for fork proposal NEW address reportedMiner; //miner who alledgedly submitted the 'bad value' will get disputeFee if dispute vote fails address reportingParty; //miner reporting the 'bad value'-pay disputeFee will get reportedMiner's stake if dispute vote passes address proposedForkAddress; //new fork address (if fork proposal) mapping(bytes32 => uint256) disputeUintVars; //Each of the variables below is saved in the mapping disputeUintVars for each disputeID //e.g. TellorStorageStruct.DisputeById[disputeID].disputeUintVars[keccak256("requestId")] //These are the variables saved in this mapping: // uint keccak256("requestId");//apiID of disputed value // uint keccak256("timestamp");//timestamp of distputed value // uint keccak256("value"); //the value being disputed // uint keccak256("minExecutionDate");//7 days from when dispute initialized // uint keccak256("numberOfVotes");//the number of parties who have voted on the measure // uint keccak256("blockNumber");// the blocknumber for which votes will be calculated from // uint keccak256("minerSlot"); //index in dispute array // uint keccak256("quorum"); //quorum for dispute vote NEW // uint keccak256("fee"); //fee paid corresponding to dispute mapping(address => bool) voted; //mapping of address to whether or not they voted } struct StakeInfo { uint256 currentStatus; //0-not Staked, 1=Staked, 2=LockedForWithdraw 3= OnDispute uint256 startDate; //stake start date } //Internal struct to allow balances to be queried by blocknumber for voting purposes struct Checkpoint { uint128 fromBlock; // fromBlock is the block number that the value was generated from uint128 value; // value is the amount of tokens at a specific block number } struct Request { string queryString; //id to string api string dataSymbol; //short name for api request bytes32 queryHash; //hash of api string and granularity e.g. keccak256(abi.encodePacked(_sapi,_granularity)) uint256[] requestTimestamps; //array of all newValueTimestamps requested mapping(bytes32 => uint256) apiUintVars; //Each of the variables below is saved in the mapping apiUintVars for each api request //e.g. requestDetails[_requestId].apiUintVars[keccak256("totalTip")] //These are the variables saved in this mapping: // uint keccak256("granularity"); //multiplier for miners // uint keccak256("requestQPosition"); //index in requestQ // uint keccak256("totalTip");//bonus portion of payout mapping(uint256 => uint256) minedBlockNum; //[apiId][minedTimestamp]=>block.number //This the time series of finalValues stored by the contract where uint UNIX timestamp is mapped to value mapping(uint256 => uint256) finalValues; mapping(uint256 => bool) inDispute; //checks if API id is in dispute or finalized. mapping(uint256 => address[5]) minersByValue; mapping(uint256 => uint256[5]) valuesByTimestamp; } struct TellorStorageStruct { bytes32 currentChallenge; //current challenge to be solved uint256[51] requestQ; //uint50 array of the top50 requests by payment amount uint256[] newValueTimestamps; //array of all timestamps requested Details[5] currentMiners; //This struct is for organizing the five mined values to find the median mapping(bytes32 => address) addressVars; //Address fields in the Tellor contract are saved the addressVars mapping //e.g. addressVars[keccak256("tellorContract")] = address //These are the variables saved in this mapping: // address keccak256("tellorContract");//Tellor address // address keccak256("_owner");//Tellor Owner address // address keccak256("_deity");//Tellor Owner that can do things at will mapping(bytes32 => uint256) uintVars; //uint fields in the Tellor contract are saved the uintVars mapping //e.g. uintVars[keccak256("decimals")] = uint //These are the variables saved in this mapping: // keccak256("decimals"); //18 decimal standard ERC20 // keccak256("disputeFee");//cost to dispute a mined value // keccak256("disputeCount");//totalHistoricalDisputes // keccak256("total_supply"); //total_supply of the token in circulation // keccak256("stakeAmount");//stakeAmount for miners (we can cut gas if we just hardcode it in...or should it be variable?) // keccak256("stakerCount"); //number of parties currently staked // keccak256("timeOfLastNewValue"); // time of last challenge solved // keccak256("difficulty"); // Difficulty of current block // keccak256("currentTotalTips"); //value of highest api/timestamp PayoutPool // keccak256("currentRequestId"); //API being mined--updates with the ApiOnQ Id // keccak256("requestCount"); // total number of requests through the system // keccak256("slotProgress");//Number of miners who have mined this value so far // keccak256("miningReward");//Mining Reward in PoWo tokens given to all miners per value // keccak256("timeTarget"); //The time between blocks (mined Oracle values) //This is a boolean that tells you if a given challenge has been completed by a given miner mapping(bytes32 => mapping(address => bool)) minersByChallenge; mapping(uint256 => uint256) requestIdByTimestamp; //minedTimestamp to apiId mapping(uint256 => uint256) requestIdByRequestQIndex; //link from payoutPoolIndex (position in payout pool array) to apiId mapping(uint256 => Dispute) disputesById; //disputeId=> Dispute details mapping(address => Checkpoint[]) balances; //balances of a party given blocks mapping(address => mapping(address => uint256)) allowed; //allowance for a given party and approver mapping(address => StakeInfo) stakerDetails; //mapping from a persons address to their staking info mapping(uint256 => Request) requestDetails; //mapping of apiID to details mapping(bytes32 => uint256) requestIdByQueryHash; // api bytes32 gets an id = to count of requests array mapping(bytes32 => uint256) disputeIdByDisputeHash; //maps a hash to an ID for each dispute } } //Functions for retrieving min and Max in 51 length array (requestQ) //Taken partly from: https://github.com/modular-network/ethereum-libraries-array-utils/blob/master/contracts/Array256Lib.sol library Utilities { /** * @dev Returns the minimum value in an array. */ function getMax(uint256[51] memory data) internal pure returns (uint256 max, uint256 maxIndex) { max = data[1]; maxIndex; for (uint256 i = 1; i < data.length; i++) { if (data[i] > max) { max = data[i]; maxIndex = i; } } } /** * @dev Returns the minimum value in an array. */ function getMin(uint256[51] memory data) internal pure returns (uint256 min, uint256 minIndex) { minIndex = data.length - 1; min = data[minIndex]; for (uint256 i = data.length - 1; i > 0; i--) { if (data[i] < min) { min = data[i]; minIndex = i; } } } } /** * @title Tellor Getters Library * @dev This is the getter library for all variables in the Tellor Tributes system. TellorGetters references this * libary for the getters logic */ library TellorGettersLibrary { using SafeMath for uint256; event NewTellorAddress(address _newTellor); //emmited when a proposed fork is voted true /*Functions*/ //The next two functions are onlyOwner functions. For Tellor to be truly decentralized, we will need to transfer the Deity to the 0 address. //Only needs to be in library /** * @dev This function allows us to set a new Deity (or remove it) * @param _newDeity address of the new Deity of the tellor system */ function changeDeity(TellorStorage.TellorStorageStruct storage self, address _newDeity) internal { require(self.addressVars[keccak256("_deity")] == msg.sender, "Sender is not deity"); self.addressVars[keccak256("_deity")] = _newDeity; } //Only needs to be in library /** * @dev This function allows the deity to upgrade the Tellor System * @param _tellorContract address of new updated TellorCore contract */ function changeTellorContract(TellorStorage.TellorStorageStruct storage self, address _tellorContract) internal { require(self.addressVars[keccak256("_deity")] == msg.sender, "Sender is not deity"); self.addressVars[keccak256("tellorContract")] = _tellorContract; emit NewTellorAddress(_tellorContract); } /*Tellor Getters*/ /** * @dev This function tells you if a given challenge has been completed by a given miner * @param _challenge the challenge to search for * @param _miner address that you want to know if they solved the challenge * @return true if the _miner address provided solved the */ function didMine(TellorStorage.TellorStorageStruct storage self, bytes32 _challenge, address _miner) internal view returns (bool) { return self.minersByChallenge[_challenge][_miner]; } /** * @dev Checks if an address voted in a dispute * @param _disputeId to look up * @param _address of voting party to look up * @return bool of whether or not party voted */ function didVote(TellorStorage.TellorStorageStruct storage self, uint256 _disputeId, address _address) internal view returns (bool) { return self.disputesById[_disputeId].voted[_address]; } /** * @dev allows Tellor to read data from the addressVars mapping * @param _data is the keccak256("variable_name") of the variable that is being accessed. * These are examples of how the variables are saved within other functions: * addressVars[keccak256("_owner")] * addressVars[keccak256("tellorContract")] */ function getAddressVars(TellorStorage.TellorStorageStruct storage self, bytes32 _data) internal view returns (address) { return self.addressVars[_data]; } /** * @dev Gets all dispute variables * @param _disputeId to look up * @return bytes32 hash of dispute * @return bool executed where true if it has been voted on * @return bool disputeVotePassed * @return bool isPropFork true if the dispute is a proposed fork * @return address of reportedMiner * @return address of reportingParty * @return address of proposedForkAddress * @return uint of requestId * @return uint of timestamp * @return uint of value * @return uint of minExecutionDate * @return uint of numberOfVotes * @return uint of blocknumber * @return uint of minerSlot * @return uint of quorum * @return uint of fee * @return int count of the current tally */ function getAllDisputeVars(TellorStorage.TellorStorageStruct storage self, uint256 _disputeId) internal view returns (bytes32, bool, bool, bool, address, address, address, uint256[9] memory, int256) { TellorStorage.Dispute storage disp = self.disputesById[_disputeId]; return ( disp.hash, disp.executed, disp.disputeVotePassed, disp.isPropFork, disp.reportedMiner, disp.reportingParty, disp.proposedForkAddress, [ disp.disputeUintVars[keccak256("requestId")], disp.disputeUintVars[keccak256("timestamp")], disp.disputeUintVars[keccak256("value")], disp.disputeUintVars[keccak256("minExecutionDate")], disp.disputeUintVars[keccak256("numberOfVotes")], disp.disputeUintVars[keccak256("blockNumber")], disp.disputeUintVars[keccak256("minerSlot")], disp.disputeUintVars[keccak256("quorum")], disp.disputeUintVars[keccak256("fee")] ], disp.tally ); } /** * @dev Getter function for variables for the requestId being currently mined(currentRequestId) * @return current challenge, curretnRequestId, level of difficulty, api/query string, and granularity(number of decimals requested), total tip for the request */ function getCurrentVariables(TellorStorage.TellorStorageStruct storage self) internal view returns (bytes32, uint256, uint256, string memory, uint256, uint256) { return ( self.currentChallenge, self.uintVars[keccak256("currentRequestId")], self.uintVars[keccak256("difficulty")], self.requestDetails[self.uintVars[keccak256("currentRequestId")]].queryString, self.requestDetails[self.uintVars[keccak256("currentRequestId")]].apiUintVars[keccak256("granularity")], self.requestDetails[self.uintVars[keccak256("currentRequestId")]].apiUintVars[keccak256("totalTip")] ); } /** * @dev Checks if a given hash of miner,requestId has been disputed * @param _hash is the sha256(abi.encodePacked(_miners[2],_requestId)); * @return uint disputeId */ function getDisputeIdByDisputeHash(TellorStorage.TellorStorageStruct storage self, bytes32 _hash) internal view returns (uint256) { return self.disputeIdByDisputeHash[_hash]; } /** * @dev Checks for uint variables in the disputeUintVars mapping based on the disuputeId * @param _disputeId is the dispute id; * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the disputeUintVars under the Dispute struct * @return uint value for the bytes32 data submitted */ function getDisputeUintVars(TellorStorage.TellorStorageStruct storage self, uint256 _disputeId, bytes32 _data) internal view returns (uint256) { return self.disputesById[_disputeId].disputeUintVars[_data]; } /** * @dev Gets the a value for the latest timestamp available * @return value for timestamp of last proof of work submited * @return true if the is a timestamp for the lastNewValue */ function getLastNewValue(TellorStorage.TellorStorageStruct storage self) internal view returns (uint256, bool) { return ( retrieveData( self, self.requestIdByTimestamp[self.uintVars[keccak256("timeOfLastNewValue")]], self.uintVars[keccak256("timeOfLastNewValue")] ), true ); } /** * @dev Gets the a value for the latest timestamp available * @param _requestId being requested * @return value for timestamp of last proof of work submited and if true if it exist or 0 and false if it doesn't */ function getLastNewValueById(TellorStorage.TellorStorageStruct storage self, uint256 _requestId) internal view returns (uint256, bool) { TellorStorage.Request storage _request = self.requestDetails[_requestId]; if (_request.requestTimestamps.length > 0) { return (retrieveData(self, _requestId, _request.requestTimestamps[_request.requestTimestamps.length - 1]), true); } else { return (0, false); } } /** * @dev Gets blocknumber for mined timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up blocknumber * @return uint of the blocknumber which the dispute was mined */ function getMinedBlockNum(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _timestamp) internal view returns (uint256) { return self.requestDetails[_requestId].minedBlockNum[_timestamp]; } /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return the 5 miners' addresses */ function getMinersByRequestIdAndTimestamp(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _timestamp) internal view returns (address[5] memory) { return self.requestDetails[_requestId].minersByValue[_timestamp]; } /** * @dev Get the name of the token * @return string of the token name */ function getName(TellorStorage.TellorStorageStruct storage self) internal pure returns (string memory) { return "Tellor Tributes"; } /** * @dev Counts the number of values that have been submited for the request * if called for the currentRequest being mined it can tell you how many miners have submitted a value for that * request so far * @param _requestId the requestId to look up * @return uint count of the number of values received for the requestId */ function getNewValueCountbyRequestId(TellorStorage.TellorStorageStruct storage self, uint256 _requestId) internal view returns (uint256) { return self.requestDetails[_requestId].requestTimestamps.length; } /** * @dev Getter function for the specified requestQ index * @param _index to look up in the requestQ array * @return uint of reqeuestId */ function getRequestIdByRequestQIndex(TellorStorage.TellorStorageStruct storage self, uint256 _index) internal view returns (uint256) { require(_index <= 50, "RequestQ index is above 50"); return self.requestIdByRequestQIndex[_index]; } /** * @dev Getter function for requestId based on timestamp * @param _timestamp to check requestId * @return uint of reqeuestId */ function getRequestIdByTimestamp(TellorStorage.TellorStorageStruct storage self, uint256 _timestamp) internal view returns (uint256) { return self.requestIdByTimestamp[_timestamp]; } /** * @dev Getter function for requestId based on the qeuaryHash * @param _queryHash hash(of string api and granularity) to check if a request already exists * @return uint requestId */ function getRequestIdByQueryHash(TellorStorage.TellorStorageStruct storage self, bytes32 _queryHash) internal view returns (uint256) { return self.requestIdByQueryHash[_queryHash]; } /** * @dev Getter function for the requestQ array * @return the requestQ arrray */ function getRequestQ(TellorStorage.TellorStorageStruct storage self) internal view returns (uint256[51] memory) { return self.requestQ; } /** * @dev Allowes access to the uint variables saved in the apiUintVars under the requestDetails struct * for the requestId specified * @param _requestId to look up * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the apiUintVars under the requestDetails struct * @return uint value of the apiUintVars specified in _data for the requestId specified */ function getRequestUintVars(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, bytes32 _data) internal view returns (uint256) { return self.requestDetails[_requestId].apiUintVars[_data]; } /** * @dev Gets the API struct variables that are not mappings * @param _requestId to look up * @return string of api to query * @return string of symbol of api to query * @return bytes32 hash of string * @return bytes32 of the granularity(decimal places) requested * @return uint of index in requestQ array * @return uint of current payout/tip for this requestId */ function getRequestVars(TellorStorage.TellorStorageStruct storage self, uint256 _requestId) internal view returns (string memory, string memory, bytes32, uint256, uint256, uint256) { TellorStorage.Request storage _request = self.requestDetails[_requestId]; return ( _request.queryString, _request.dataSymbol, _request.queryHash, _request.apiUintVars[keccak256("granularity")], _request.apiUintVars[keccak256("requestQPosition")], _request.apiUintVars[keccak256("totalTip")] ); } /** * @dev This function allows users to retireve all information about a staker * @param _staker address of staker inquiring about * @return uint current state of staker * @return uint startDate of staking */ function getStakerInfo(TellorStorage.TellorStorageStruct storage self, address _staker) internal view returns (uint256, uint256) { return (self.stakerDetails[_staker].currentStatus, self.stakerDetails[_staker].startDate); } /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestampt to look up miners for * @return address[5] array of 5 addresses ofminers that mined the requestId */ function getSubmissionsByTimestamp(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _timestamp) internal view returns (uint256[5] memory) { return self.requestDetails[_requestId].valuesByTimestamp[_timestamp]; } /** * @dev Get the symbol of the token * @return string of the token symbol */ function getSymbol(TellorStorage.TellorStorageStruct storage self) internal pure returns (string memory) { return "TT"; } /** * @dev Gets the timestamp for the value based on their index * @param _requestID is the requestId to look up * @param _index is the value index to look up * @return uint timestamp */ function getTimestampbyRequestIDandIndex(TellorStorage.TellorStorageStruct storage self, uint256 _requestID, uint256 _index) internal view returns (uint256) { return self.requestDetails[_requestID].requestTimestamps[_index]; } /** * @dev Getter for the variables saved under the TellorStorageStruct uintVars variable * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the uintVars under the TellorStorageStruct struct * This is an example of how data is saved into the mapping within other functions: * self.uintVars[keccak256("stakerCount")] * @return uint of specified variable */ function getUintVar(TellorStorage.TellorStorageStruct storage self, bytes32 _data) internal view returns (uint256) { return self.uintVars[_data]; } /** * @dev Getter function for next requestId on queue/request with highest payout at time the function is called * @return onDeck/info on request with highest payout-- RequestId, Totaltips, and API query string */ function getVariablesOnDeck(TellorStorage.TellorStorageStruct storage self) internal view returns (uint256, uint256, string memory) { uint256 newRequestId = getTopRequestID(self); return ( newRequestId, self.requestDetails[newRequestId].apiUintVars[keccak256("totalTip")], self.requestDetails[newRequestId].queryString ); } /** * @dev Getter function for the request with highest payout. This function is used within the getVariablesOnDeck function * @return uint _requestId of request with highest payout at the time the function is called */ function getTopRequestID(TellorStorage.TellorStorageStruct storage self) internal view returns (uint256 _requestId) { uint256 _max; uint256 _index; (_max, _index) = Utilities.getMax(self.requestQ); _requestId = self.requestIdByRequestQIndex[_index]; } /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return bool true if requestId/timestamp is under dispute */ function isInDispute(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _timestamp) internal view returns (bool) { return self.requestDetails[_requestId].inDispute[_timestamp]; } /** * @dev Retreive value from oracle based on requestId/timestamp * @param _requestId being requested * @param _timestamp to retreive data/value from * @return uint value for requestId/timestamp submitted */ function retrieveData(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _timestamp) internal view returns (uint256) { return self.requestDetails[_requestId].finalValues[_timestamp]; } /** * @dev Getter for the total_supply of oracle tokens * @return uint total supply */ function totalSupply(TellorStorage.TellorStorageStruct storage self) internal view returns (uint256) { return self.uintVars[keccak256("total_supply")]; } } /** * @title Tellor Oracle System Library * @dev Contains the functions' logic for the Tellor contract where miners can submit the proof of work * along with the value and smart contracts can requestData and tip miners. */ library TellorLibrary { using SafeMath for uint256; event TipAdded(address indexed _sender, uint256 indexed _requestId, uint256 _tip, uint256 _totalTips); //Emits upon someone adding value to a pool; msg.sender, amount added, and timestamp incentivized to be mined event DataRequested( address indexed _sender, string _query, string _querySymbol, uint256 _granularity, uint256 indexed _requestId, uint256 _totalTips ); //emits when a new challenge is created (either on mined block or when a new request is pushed forward on waiting system) event NewChallenge( bytes32 _currentChallenge, uint256 indexed _currentRequestId, uint256 _difficulty, uint256 _multiplier, string _query, uint256 _totalTips ); //emits when a the payout of another request is higher after adding to the payoutPool or submitting a request event NewRequestOnDeck(uint256 indexed _requestId, string _query, bytes32 _onDeckQueryHash, uint256 _onDeckTotalTips); //Emits upon a successful Mine, indicates the blocktime at point of the mine and the value mined event NewValue(uint256 indexed _requestId, uint256 _time, uint256 _value, uint256 _totalTips, bytes32 _currentChallenge); //Emits upon each mine (5 total) and shows the miner, nonce, and value submitted event NonceSubmitted(address indexed _miner, string _nonce, uint256 indexed _requestId, uint256 _value, bytes32 _currentChallenge); event OwnershipTransferred(address indexed _previousOwner, address indexed _newOwner); event OwnershipProposed(address indexed _previousOwner, address indexed _newOwner); /*Functions*/ /*This is a cheat for demo purposes, will delete upon actual launch*/ /*function theLazyCoon(TellorStorage.TellorStorageStruct storage self,address _address, uint _amount) public { self.uintVars[keccak256("total_supply")] += _amount; TellorTransfer.updateBalanceAtNow(self.balances[_address],_amount); } */ /** * @dev Add tip to Request value from oracle * @param _requestId being requested to be mined * @param _tip amount the requester is willing to pay to be get on queue. Miners * mine the onDeckQueryHash, or the api with the highest payout pool */ function addTip(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _tip) public { require(_requestId > 0, "RequestId is 0"); //If the tip > 0 transfer the tip to this contract if (_tip > 0) { TellorTransfer.doTransfer(self, msg.sender, address(this), _tip); } //Update the information for the request that should be mined next based on the tip submitted updateOnDeck(self, _requestId, _tip); emit TipAdded(msg.sender, _requestId, _tip, self.requestDetails[_requestId].apiUintVars[keccak256("totalTip")]); } /** * @dev Request to retreive value from oracle based on timestamp. The tip is not required to be * greater than 0 because there are no tokens in circulation for the initial(genesis) request * @param _c_sapi string API being requested be mined * @param _c_symbol is the short string symbol for the api request * @param _granularity is the number of decimals miners should include on the submitted value * @param _tip amount the requester is willing to pay to be get on queue. Miners * mine the onDeckQueryHash, or the api with the highest payout pool */ function requestData( TellorStorage.TellorStorageStruct storage self, string memory _c_sapi, string memory _c_symbol, uint256 _granularity, uint256 _tip ) public { //Require at least one decimal place require(_granularity > 0, "Too few decimal places"); //But no more than 18 decimal places require(_granularity <= 1e18, "Too many decimal places"); //If it has been requested before then add the tip to it otherwise create the queryHash for it string memory _sapi = _c_sapi; string memory _symbol = _c_symbol; require(bytes(_sapi).length > 0, "API string length is 0"); require(bytes(_symbol).length < 64, "API string symbol is greater than 64"); bytes32 _queryHash = keccak256(abi.encodePacked(_sapi, _granularity)); //If this is the first time the API and granularity combination has been requested then create the API and granularity hash //otherwise the tip will be added to the requestId submitted if (self.requestIdByQueryHash[_queryHash] == 0) { self.uintVars[keccak256("requestCount")]++; uint256 _requestId = self.uintVars[keccak256("requestCount")]; self.requestDetails[_requestId] = TellorStorage.Request({ queryString: _sapi, dataSymbol: _symbol, queryHash: _queryHash, requestTimestamps: new uint256[](0) }); self.requestDetails[_requestId].apiUintVars[keccak256("granularity")] = _granularity; self.requestDetails[_requestId].apiUintVars[keccak256("requestQPosition")] = 0; self.requestDetails[_requestId].apiUintVars[keccak256("totalTip")] = 0; self.requestIdByQueryHash[_queryHash] = _requestId; //If the tip > 0 it tranfers the tip to this contract if (_tip > 0) { TellorTransfer.doTransfer(self, msg.sender, address(this), _tip); } updateOnDeck(self, _requestId, _tip); emit DataRequested( msg.sender, self.requestDetails[_requestId].queryString, self.requestDetails[_requestId].dataSymbol, _granularity, _requestId, _tip ); //Add tip to existing request id since this is not the first time the api and granularity have been requested } else { addTip(self, self.requestIdByQueryHash[_queryHash], _tip); } } /** * @dev This fucntion is called by submitMiningSolution and adjusts the difficulty, sorts and stores the first * 5 values received, pays the miners, the dev share and assigns a new challenge * @param _nonce or solution for the PoW for the requestId * @param _requestId for the current request being mined */ function newBlock(TellorStorage.TellorStorageStruct storage self, string memory _nonce, uint256 _requestId) internal { TellorStorage.Request storage _request = self.requestDetails[_requestId]; // If the difference between the timeTarget and how long it takes to solve the challenge this updates the challenge //difficulty up or donw by the difference between the target time and how long it took to solve the prevous challenge //otherwise it sets it to 1 int256 _change = int256(SafeMath.min(1200, (now - self.uintVars[keccak256("timeOfLastNewValue")]))); _change = (int256(self.uintVars[keccak256("difficulty")]) * (int256(self.uintVars[keccak256("timeTarget")]) - _change)) / 4000; if (_change < 2 && _change > -2) { if (_change >= 0) { _change = 1; } else { _change = -1; } } if ((int256(self.uintVars[keccak256("difficulty")]) + _change) <= 0) { self.uintVars[keccak256("difficulty")] = 1; } else { self.uintVars[keccak256("difficulty")] = uint256(int256(self.uintVars[keccak256("difficulty")]) + _change); } //Sets time of value submission rounded to 1 minute uint256 _timeOfLastNewValue = now - (now % 1 minutes); self.uintVars[keccak256("timeOfLastNewValue")] = _timeOfLastNewValue; //The sorting algorithm that sorts the values of the first five values that come in TellorStorage.Details[5] memory a = self.currentMiners; uint256 i; for (i = 1; i < 5; i++) { uint256 temp = a[i].value; address temp2 = a[i].miner; uint256 j = i; while (j > 0 && temp < a[j - 1].value) { a[j].value = a[j - 1].value; a[j].miner = a[j - 1].miner; j--; } if (j < i) { a[j].value = temp; a[j].miner = temp2; } } //Pay the miners for (i = 0; i < 5; i++) { TellorTransfer.doTransfer(self, address(this), a[i].miner, 5e18 + self.uintVars[keccak256("currentTotalTips")] / 5); } emit NewValue( _requestId, _timeOfLastNewValue, a[2].value, self.uintVars[keccak256("currentTotalTips")] - (self.uintVars[keccak256("currentTotalTips")] % 5), self.currentChallenge ); //update the total supply self.uintVars[keccak256("total_supply")] += 275e17; //pay the dev-share TellorTransfer.doTransfer(self, address(this), self.addressVars[keccak256("_owner")], 25e17); //The ten there is the devshare //Save the official(finalValue), timestamp of it, 5 miners and their submitted values for it, and its block number _request.finalValues[_timeOfLastNewValue] = a[2].value; _request.requestTimestamps.push(_timeOfLastNewValue); //these are miners by timestamp _request.minersByValue[_timeOfLastNewValue] = [a[0].miner, a[1].miner, a[2].miner, a[3].miner, a[4].miner]; _request.valuesByTimestamp[_timeOfLastNewValue] = [a[0].value, a[1].value, a[2].value, a[3].value, a[4].value]; _request.minedBlockNum[_timeOfLastNewValue] = block.number; //map the timeOfLastValue to the requestId that was just mined self.requestIdByTimestamp[_timeOfLastNewValue] = _requestId; //add timeOfLastValue to the newValueTimestamps array self.newValueTimestamps.push(_timeOfLastNewValue); //re-start the count for the slot progress to zero before the new request mining starts self.uintVars[keccak256("slotProgress")] = 0; uint256 _topId = TellorGettersLibrary.getTopRequestID(self); self.uintVars[keccak256("currentRequestId")] = _topId; //if the currentRequestId is not zero(currentRequestId exists/something is being mined) select the requestId with the hightest payout //else wait for a new tip to mine if (_topId > 0) { //Update the current request to be mined to the requestID with the highest payout self.uintVars[keccak256("currentTotalTips")] = self.requestDetails[_topId].apiUintVars[keccak256("totalTip")]; //Remove the currentRequestId/onDeckRequestId from the requestQ array containing the rest of the 50 requests self.requestQ[self.requestDetails[_topId].apiUintVars[keccak256("requestQPosition")]] = 0; //unmap the currentRequestId/onDeckRequestId from the requestIdByRequestQIndex self.requestIdByRequestQIndex[self.requestDetails[_topId].apiUintVars[keccak256("requestQPosition")]] = 0; //Remove the requestQposition for the currentRequestId/onDeckRequestId since it will be mined next self.requestDetails[_topId].apiUintVars[keccak256("requestQPosition")] = 0; //Reset the requestId TotalTip to 0 for the currentRequestId/onDeckRequestId since it will be mined next //and the tip is going to the current timestamp miners. The tip for the API needs to be reset to zero self.requestDetails[_topId].apiUintVars[keccak256("totalTip")] = 0; //gets the max tip in the in the requestQ[51] array and its index within the array?? uint256 newRequestId = TellorGettersLibrary.getTopRequestID(self); //Issue the the next challenge self.currentChallenge = keccak256(abi.encodePacked(_nonce, self.currentChallenge, blockhash(block.number - 1))); // Save hash for next proof emit NewChallenge( self.currentChallenge, _topId, self.uintVars[keccak256("difficulty")], self.requestDetails[_topId].apiUintVars[keccak256("granularity")], self.requestDetails[_topId].queryString, self.uintVars[keccak256("currentTotalTips")] ); emit NewRequestOnDeck( newRequestId, self.requestDetails[newRequestId].queryString, self.requestDetails[newRequestId].queryHash, self.requestDetails[newRequestId].apiUintVars[keccak256("totalTip")] ); } else { self.uintVars[keccak256("currentTotalTips")] = 0; self.currentChallenge = ""; } } /** * @dev Proof of work is called by the miner when they submit the solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId the apiId being mined * @param _value of api query */ function submitMiningSolution(TellorStorage.TellorStorageStruct storage self, string memory _nonce, uint256 _requestId, uint256 _value) public { //requre miner is staked require(self.stakerDetails[msg.sender].currentStatus == 1, "Miner status is not staker"); //Check the miner is submitting the pow for the current request Id require(_requestId == self.uintVars[keccak256("currentRequestId")], "RequestId is wrong"); //Saving the challenge information as unique by using the msg.sender require( uint256( sha256(abi.encodePacked(ripemd160(abi.encodePacked(keccak256(abi.encodePacked(self.currentChallenge, msg.sender, _nonce)))))) ) % self.uintVars[keccak256("difficulty")] == 0, "Challenge information is not saved" ); //Make sure the miner does not submit a value more than once require(self.minersByChallenge[self.currentChallenge][msg.sender] == false, "Miner already submitted the value"); //Save the miner and value received self.currentMiners[self.uintVars[keccak256("slotProgress")]].value = _value; self.currentMiners[self.uintVars[keccak256("slotProgress")]].miner = msg.sender; //Add to the count how many values have been submitted, since only 5 are taken per request self.uintVars[keccak256("slotProgress")]++; //Update the miner status to true once they submit a value so they don't submit more than once self.minersByChallenge[self.currentChallenge][msg.sender] = true; emit NonceSubmitted(msg.sender, _nonce, _requestId, _value, self.currentChallenge); //If 5 values have been received, adjust the difficulty otherwise sort the values until 5 are received if (self.uintVars[keccak256("slotProgress")] == 5) { newBlock(self, _nonce, _requestId); } } /** * @dev Allows the current owner to propose transfer control of the contract to a * newOwner and the ownership is pending until the new owner calls the claimOwnership * function * @param _pendingOwner The address to transfer ownership to. */ function proposeOwnership(TellorStorage.TellorStorageStruct storage self, address payable _pendingOwner) internal { require(msg.sender == self.addressVars[keccak256("_owner")], "Sender is not owner"); emit OwnershipProposed(self.addressVars[keccak256("_owner")], _pendingOwner); self.addressVars[keccak256("pending_owner")] = _pendingOwner; } /** * @dev Allows the new owner to claim control of the contract */ function claimOwnership(TellorStorage.TellorStorageStruct storage self) internal { require(msg.sender == self.addressVars[keccak256("pending_owner")], "Sender is not pending owner"); emit OwnershipTransferred(self.addressVars[keccak256("_owner")], self.addressVars[keccak256("pending_owner")]); self.addressVars[keccak256("_owner")] = self.addressVars[keccak256("pending_owner")]; } /** * @dev This function updates APIonQ and the requestQ when requestData or addTip are ran * @param _requestId being requested * @param _tip is the tip to add */ function updateOnDeck(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _tip) internal { TellorStorage.Request storage _request = self.requestDetails[_requestId]; uint256 onDeckRequestId = TellorGettersLibrary.getTopRequestID(self); //If the tip >0 update the tip for the requestId if (_tip > 0) { _request.apiUintVars[keccak256("totalTip")] = _request.apiUintVars[keccak256("totalTip")].add(_tip); } //Set _payout for the submitted request uint256 _payout = _request.apiUintVars[keccak256("totalTip")]; //If there is no current request being mined //then set the currentRequestId to the requestid of the requestData or addtip requestId submitted, // the totalTips to the payout/tip submitted, and issue a new mining challenge if (self.uintVars[keccak256("currentRequestId")] == 0) { _request.apiUintVars[keccak256("totalTip")] = 0; self.uintVars[keccak256("currentRequestId")] = _requestId; self.uintVars[keccak256("currentTotalTips")] = _payout; self.currentChallenge = keccak256(abi.encodePacked(_payout, self.currentChallenge, blockhash(block.number - 1))); // Save hash for next proof emit NewChallenge( self.currentChallenge, self.uintVars[keccak256("currentRequestId")], self.uintVars[keccak256("difficulty")], self.requestDetails[self.uintVars[keccak256("currentRequestId")]].apiUintVars[keccak256("granularity")], self.requestDetails[self.uintVars[keccak256("currentRequestId")]].queryString, self.uintVars[keccak256("currentTotalTips")] ); } else { //If there is no OnDeckRequestId //then replace/add the requestId to be the OnDeckRequestId, queryHash and OnDeckTotalTips(current highest payout, aside from what //is being currently mined) if (_payout > self.requestDetails[onDeckRequestId].apiUintVars[keccak256("totalTip")] || (onDeckRequestId == 0)) { //let everyone know the next on queue has been replaced emit NewRequestOnDeck(_requestId, _request.queryString, _request.queryHash, _payout); } //if the request is not part of the requestQ[51] array //then add to the requestQ[51] only if the _payout/tip is greater than the minimum(tip) in the requestQ[51] array if (_request.apiUintVars[keccak256("requestQPosition")] == 0) { uint256 _min; uint256 _index; (_min, _index) = Utilities.getMin(self.requestQ); //we have to zero out the oldOne //if the _payout is greater than the current minimum payout in the requestQ[51] or if the minimum is zero //then add it to the requestQ array aand map its index information to the requestId and the apiUintvars if (_payout > _min || _min == 0) { self.requestQ[_index] = _payout; self.requestDetails[self.requestIdByRequestQIndex[_index]].apiUintVars[keccak256("requestQPosition")] = 0; self.requestIdByRequestQIndex[_index] = _requestId; _request.apiUintVars[keccak256("requestQPosition")] = _index; } // else if the requestid is part of the requestQ[51] then update the tip for it } else if (_tip > 0) { self.requestQ[_request.apiUintVars[keccak256("requestQPosition")]] += _tip; } } } } /** * @title Tellor Oracle System * @dev Oracle contract where miners can submit the proof of work along with the value. * The logic for this contract is in TellorLibrary.sol, TellorDispute.sol, TellorStake.sol, * and TellorTransfer.sol */ contract Tellor { using SafeMath for uint256; using TellorDispute for TellorStorage.TellorStorageStruct; using TellorLibrary for TellorStorage.TellorStorageStruct; using TellorStake for TellorStorage.TellorStorageStruct; using TellorTransfer for TellorStorage.TellorStorageStruct; TellorStorage.TellorStorageStruct tellor; /*Functions*/ /*This is a cheat for demo purposes, will delete upon actual launch*/ /*function theLazyCoon(address _address, uint _amount) public { tellor.theLazyCoon(_address,_amount); }*/ /** * @dev Helps initialize a dispute by assigning it a disputeId * when a miner returns a false on the validate array(in Tellor.ProofOfWork) it sends the * invalidated value information to POS voting * @param _requestId being disputed * @param _timestamp being disputed * @param _minerIndex the index of the miner that submitted the value being disputed. Since each official value * requires 5 miners to submit a value. */ function beginDispute(uint256 _requestId, uint256 _timestamp, uint256 _minerIndex) external { tellor.beginDispute(_requestId, _timestamp, _minerIndex); } /** * @dev Allows token holders to vote * @param _disputeId is the dispute id * @param _supportsDispute is the vote (true=the dispute has basis false = vote against dispute) */ function vote(uint256 _disputeId, bool _supportsDispute) external { tellor.vote(_disputeId, _supportsDispute); } /** * @dev tallies the votes. * @param _disputeId is the dispute id */ function tallyVotes(uint256 _disputeId) external { tellor.tallyVotes(_disputeId); } /** * @dev Allows for a fork to be proposed * @param _propNewTellorAddress address for new proposed Tellor */ function proposeFork(address _propNewTellorAddress) external { tellor.proposeFork(_propNewTellorAddress); } /** * @dev Add tip to Request value from oracle * @param _requestId being requested to be mined * @param _tip amount the requester is willing to pay to be get on queue. Miners * mine the onDeckQueryHash, or the api with the highest payout pool */ function addTip(uint256 _requestId, uint256 _tip) external { tellor.addTip(_requestId, _tip); } /** * @dev Request to retreive value from oracle based on timestamp. The tip is not required to be * greater than 0 because there are no tokens in circulation for the initial(genesis) request * @param _c_sapi string API being requested be mined * @param _c_symbol is the short string symbol for the api request * @param _granularity is the number of decimals miners should include on the submitted value * @param _tip amount the requester is willing to pay to be get on queue. Miners * mine the onDeckQueryHash, or the api with the highest payout pool */ function requestData(string calldata _c_sapi, string calldata _c_symbol, uint256 _granularity, uint256 _tip) external { tellor.requestData(_c_sapi, _c_symbol, _granularity, _tip); } /** * @dev Proof of work is called by the miner when they submit the solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId the apiId being mined * @param _value of api query */ function submitMiningSolution(string calldata _nonce, uint256 _requestId, uint256 _value) external { tellor.submitMiningSolution(_nonce, _requestId, _value); } /** * @dev Allows the current owner to propose transfer control of the contract to a * newOwner and the ownership is pending until the new owner calls the claimOwnership * function * @param _pendingOwner The address to transfer ownership to. */ function proposeOwnership(address payable _pendingOwner) external { tellor.proposeOwnership(_pendingOwner); } /** * @dev Allows the new owner to claim control of the contract */ function claimOwnership() external { tellor.claimOwnership(); } /** * @dev This function allows miners to deposit their stake. */ function depositStake() external { tellor.depositStake(); } /** * @dev This function allows stakers to request to withdraw their stake (no longer stake) * once they lock for withdraw(stakes.currentStatus = 2) they are locked for 7 days before they * can withdraw the stake */ function requestStakingWithdraw() external { tellor.requestStakingWithdraw(); } /** * @dev This function allows users to withdraw their stake after a 7 day waiting period from request */ function withdrawStake() external { tellor.withdrawStake(); } /** * @dev This function approves a _spender an _amount of tokens to use * @param _spender address * @param _amount amount the spender is being approved for * @return true if spender appproved successfully */ function approve(address _spender, uint256 _amount) external returns (bool) { return tellor.approve(_spender, _amount); } /** * @dev Allows for a transfer of tokens to _to * @param _to The address to send tokens to * @param _amount The amount of tokens to send * @return true if transfer is successful */ function transfer(address _to, uint256 _amount) external returns (bool) { return tellor.transfer(_to, _amount); } /** * @dev Sends _amount tokens to _to from _from on the condition it * is approved by _from * @param _from The address holding the tokens being transferred * @param _to The address of the recipient * @param _amount The amount of tokens to be transferred * @return True if the transfer was successful */ function transferFrom(address _from, address _to, uint256 _amount) external returns (bool) { return tellor.transferFrom(_from, _to, _amount); } /** * @dev Allows users to access the token's name */ function name() external pure returns (string memory) { return "Tellor Tributes"; } /** * @dev Allows users to access the token's symbol */ function symbol() external pure returns (string memory) { return "TRB"; } /** * @dev Allows users to access the number of decimals */ function decimals() external pure returns (uint8) { return 18; } }
This function allows users to withdraw their stake after a 7 day waiting period from request/
function withdrawStake() external { tellor.withdrawStake(); }
12,861,528
./full_match/80001/0xc560D0eF74127Ba81B188A2e0aB5f2fBd99a6260/sources/src/LS1155.sol
scale a percentage to find the balance of a given account account The account to find the balance of return balance The balance of the account can't overflow; invariant: sum(balanceOf) == TOTAL_SUPPLY = 1e3 SUPPLY_TO_PERCENTAGE = 1e6 / 1e3 = 1e3 => sum(balanceOf[i] SUPPLY_TO_PERCENTAGE) == PERCENTAGE_SCALE = 1e6)
function scaledPercentBalanceOf( address account ) public view override returns (uint32) { uint256 currentTotalSupply = totalSupply[TOKEN_ID]; if (currentTotalSupply == 0) { return 0; uint256 scale = 1e6 / currentTotalSupply; return uint32(balanceOf[account][TOKEN_ID] * scale); } }
845,283
/* * This code has not been reviewed. * Do not use or deploy this code before reviewing it personally first. */ pragma solidity >=0.6.0 <0.9.0; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@chainlink/contracts/src/v0.6/ChainlinkClient.sol"; import "./IERC1400.sol"; /** * @title ERC1400 * @dev ERC1400 logic */ contract ERC1400 is IERC20, IERC1400, Ownable, ChainlinkClient { using SafeMath for uint256; // Token string constant internal ERC1400_INTERFACE_NAME = "ERC1400Token"; string constant internal ERC20_INTERFACE_NAME = "ERC20Token"; /************************************* Token description ****************************************/ string internal _name; string internal _symbol; uint256 internal _granularity; uint256 internal _totalSupply; bool internal _migrated; /************************************************************************************************/ /**************************************** Token behaviours **************************************/ // Indicate whether the token can still be controlled by operators or not anymore. bool internal _isControllable; // Indicate whether the token can still be issued by the issuer or not anymore. bool internal _isIssuable; /************************************************************************************************/ /********************************** ERC20 Token mappings ****************************************/ // Mapping from tokenHolder to balance. mapping(address => uint256) internal _balances; // Mapping from (tokenHolder, spender) to allowed value. mapping (address => mapping (address => uint256)) internal _allowed; /************************************************************************************************/ /**************************************** Documents *********************************************/ struct Doc { string docURI; bytes32 docHash; } // Mapping for token URIs. mapping(bytes32 => Doc) internal _documents; /************************************************************************************************/ /*********************************** Partitions mappings ***************************************/ // List of partitions. bytes32[] internal _totalPartitions; // Mapping from partition to their index. mapping (bytes32 => uint256) internal _indexOfTotalPartitions; // Mapping from partition to global balance of corresponding partition. mapping (bytes32 => uint256) internal _totalSupplyByPartition; // Mapping from tokenHolder to their partitions. mapping (address => bytes32[]) internal _partitionsOf; // Mapping from (tokenHolder, partition) to their index. mapping (address => mapping (bytes32 => uint256)) internal _indexOfPartitionsOf; // Mapping from (tokenHolder, partition) to balance of corresponding partition. mapping (address => mapping (bytes32 => uint256)) internal _balanceOfByPartition; // List of token default partitions (for ERC20 compatibility). bytes32[] internal _defaultPartitions; /************************************************************************************************/ /********************************* Global operators mappings ************************************/ // Mapping from (operator, tokenHolder) to authorized status. [TOKEN-HOLDER-SPECIFIC] mapping(address => mapping(address => bool)) internal _authorizedOperator; // Array of controllers. [GLOBAL - NOT TOKEN-HOLDER-SPECIFIC] address[] internal _controllers; // Mapping from operator to controller status. [GLOBAL - NOT TOKEN-HOLDER-SPECIFIC] mapping(address => bool) internal _isController; /************************************************************************************************/ /******************************** Partition operators mappings **********************************/ // Mapping from (partition, tokenHolder, spender) to allowed value. [TOKEN-HOLDER-SPECIFIC] mapping(bytes32 => mapping (address => mapping (address => uint256))) internal _allowedByPartition; // Mapping from (tokenHolder, partition, operator) to 'approved for partition' status. [TOKEN-HOLDER-SPECIFIC] mapping (address => mapping (bytes32 => mapping (address => bool))) internal _authorizedOperatorByPartition; // Mapping from partition to controllers for the partition. [NOT TOKEN-HOLDER-SPECIFIC] mapping (bytes32 => address[]) internal _controllersByPartition; // Mapping from (partition, operator) to PartitionController status. [NOT TOKEN-HOLDER-SPECIFIC] mapping (bytes32 => mapping (address => bool)) internal _isControllerByPartition; /************************************************************************************************/ /******************************************* Oracle *********************************************/ // Kovan address private oracle = 0x8bF43cA0b3CeAE338C9A579E3eA8DC6b0aDcAe09; bytes32 private jobId = "906ac2562c77472cb5a881dce34e000c"; uint256 private fee = 0.1 * 10 ** 18; mapping(bytes32 => address) public receivers; mapping(bytes32 => string) public paymentIntents; event ReleasePaidTokens(address indexed receiver, string intent); /************************************************************************************************/ /***************************************** Modifiers ********************************************/ /** * @dev Modifier to verify if token is issuable. */ modifier isIssuableToken() { require(_isIssuable, "55"); // 0x55 funds locked (lockup period) _; } /** * @dev Modifier to make a function callable only when the contract is not migrated. */ modifier isNotMigratedToken() { require(!_migrated, "54"); // 0x54 transfers halted (contract paused) _; } /************************************************************************************************/ /**************************** Events (additional - not mandatory) *******************************/ event ApprovalByPartition(bytes32 indexed partition, address indexed owner, address indexed spender, uint256 value); /************************************************************************************************/ /** * @dev Initialize ERC1400 + register the contract implementation in ERC1820Registry. * @param name Name of the token. * @param symbol Symbol of the token. * @param granularity Granularity of the token. * @param controllers Array of initial controllers. * @param defaultPartitions Partitions chosen by default, when partition is * not specified, like the case ERC20 tranfers. */ constructor( string memory name, string memory symbol, uint256 granularity, address[] memory controllers, bytes32[] memory defaultPartitions ) public { _name = name; _symbol = symbol; _totalSupply = 0; require(granularity >= 1); // Constructor Blocked - Token granularity can not be lower than 1 _granularity = granularity; _setControllers(controllers); _defaultPartitions = defaultPartitions; _isControllable = true; _isIssuable = true; } /** * @dev Config function to set address of Chainlink token. */ function setChainlinkToken() external onlyOwner { setPublicChainlinkToken(); } /************************************************************************************************/ /************************************ DELIVERY-vs-PAYMENT ***************************************/ /************************************************************************************************/ /** * @dev Issue reserved tokens and make a request to the oracle to verify payment. * @param amount Amount of tokens to be reserved. * @param intent Key obtained by PSP (Stripe). * @param sig Encrypted with user's key message containing amount and intent. * @return requestId from chainlink request. */ function reserveAndVerifyPayment( uint256 amount, string calldata intent, bytes calldata sig ) external returns (bytes32 requestId) { require(_defaultPartitions.length != 0, "55"); // 0x55 funds locked (lockup period) // verify sig validity bytes32 message = prefixed(keccak256(abi.encodePacked(msg.sender, amount, intent))); require(recoverSigner(message, sig) == msg.sender, "Not same user"); // issue "reserved" tokens _issueByPartition(_defaultPartitions[0], msg.sender, msg.sender, amount, ""); // call Chainlink Chainlink.Request memory request = buildChainlinkRequest(jobId, address(this), this.releasePaidTokens.selector); string memory _addr = addressToString(msg.sender); string memory _q = string(abi.encodePacked("payment_intent_id=", intent, "&addr=", _addr)); request.add("get", string(abi.encodePacked("https://dvp-server.barakov.xyz/check?", _q))); request.add("queryParams", _q); request.add("path", "SUCCESS"); requestId = sendChainlinkRequestTo(oracle, request, fee); receivers[requestId] = msg.sender; paymentIntents[requestId] = intent; } /** * @dev Callback ivoked by the oracle with result of payment verification. * @param requestId Chainlink request id, obtained in "reserveAndVerifyPayment". * @param success Result of verification. If successfull, issue tokens and emit ReleasePaidTokens. */ function releasePaidTokens(bytes32 requestId, bool success) public recordChainlinkFulfillment(requestId) { require(_defaultPartitions.length > 1, "55"); // 0x55 funds locked (lockup period) require(success, "Unable to verify"); address receiver = receivers[requestId]; string memory intent = paymentIntents[requestId]; uint256 amount = _balanceOfByPartition[receiver][_defaultPartitions[0]]; _redeemByDefaultPartitions(receiver, receiver, amount, ""); _issueByPartition(_defaultPartitions[1], receiver, receiver, amount, ""); emit ReleasePaidTokens(receiver, intent); } /************************************************************************************************/ /******************************** Utils internal functions ***************************************/ /** * @dev Cast address to string. * @param _address Address to be cast. * @return Address transformed in string. */ function addressToString(address _address) internal pure returns(string memory) { bytes32 _bytes = bytes32(uint256(_address)); bytes memory HEX = "0123456789abcdef"; bytes memory _string = new bytes(42); _string[0] = '0'; _string[1] = 'x'; for(uint i = 0; i < 20; i++) { _string[2+i*2] = HEX[uint8(_bytes[i + 12] >> 4)]; _string[3+i*2] = HEX[uint8(_bytes[i + 12] & 0x0f)]; } return string(_string); } /** * @dev Low-level function used to obtain parts of the ecrypted message. * @param sig Message to be split. * @return Three parts of the msg. */ function splitSignature(bytes memory sig) internal pure returns (uint8, bytes32, bytes32) { require(sig.length == 65); bytes32 r; bytes32 s; uint8 v; assembly { // first 32 bytes, after the length prefix r := mload(add(sig, 32)) // second 32 bytes s := mload(add(sig, 64)) // final byte (first byte of the next 32 bytes) v := byte(0, mload(add(sig, 96))) } return (v, r, s); } /** * @dev Recover address used to sign an ecrypted msg. * @param message. * @return Address of signer. */ function recoverSigner(bytes32 message, bytes memory sig) internal pure returns (address) { uint8 v; bytes32 r; bytes32 s; (v, r, s) = splitSignature(sig); return ecrecover(message, v, r, s); } // Builds a prefixed hash to mimic the behavior of eth_sign. function prefixed(bytes32 hash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /************************************************************************************************/ /************************************************************************************************/ /****************************** EXTERNAL FUNCTIONS (ERC20 INTERFACE) ****************************/ /************************************************************************************************/ /** * @dev Get the total number of issued tokens. * @return Total supply of tokens currently in circulation. */ function totalSupply() external view override returns (uint256) { return _totalSupply; } /** * @dev Get the balance of the account with address 'tokenHolder'. * @param tokenHolder Address for which the balance is returned. * @return Amount of token held by 'tokenHolder' in the token contract. */ function balanceOf(address tokenHolder) external view override returns (uint256) { return _balances[tokenHolder]; } /** * @dev Transfer token for a specified address. * @param to The address to transfer to. * @param value The value to be transferred. * @return A boolean that indicates if the operation was successful. */ function transfer(address to, uint256 value) external override returns (bool) { _transferByDefaultPartitions(msg.sender, msg.sender, to, value, ""); return true; } /** * @dev Check the value 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 value of tokens still available for the spender. */ function allowance(address owner, address spender) external view override returns (uint256) { return _allowed[owner][spender]; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of 'msg.sender'. * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. * @return A boolean that indicates if the operation was successful. */ function approve(address spender, uint256 value) external override returns (bool) { require(spender != address(0), "56"); // 0x56 invalid sender _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another. * @param from The address which you want to transfer tokens from. * @param to The address which you want to transfer to. * @param value The amount of tokens to be transferred. * @return A boolean that indicates if the operation was successful. */ function transferFrom(address from, address to, uint256 value) external override returns (bool) { require( _isOperator(msg.sender, from) || (value <= _allowed[from][msg.sender]), "53"); // 0x53 insufficient allowance if(_allowed[from][msg.sender] >= value) { _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); } else { _allowed[from][msg.sender] = 0; } _transferByDefaultPartitions(msg.sender, from, to, value, ""); return true; } /************************************************************************************************/ /****************************** EXTERNAL FUNCTIONS (ERC1400 INTERFACE) **************************/ /************************************************************************************************/ /************************************* Document Management **************************************/ /** * @dev Access a document associated with the token. * @param name Short name (represented as a bytes32) associated to the document. * @return Requested document + document hash. */ function getDocument(bytes32 name) external view override returns (string memory, bytes32) { require(bytes(_documents[name].docURI).length != 0); // Action Blocked - Empty document return ( _documents[name].docURI, _documents[name].docHash ); } /** * @dev Associate a document with the token. * @param name Short name (represented as a bytes32) associated to the document. * @param uri Document content. * @param documentHash Hash of the document [optional parameter]. */ function setDocument(bytes32 name, string calldata uri, bytes32 documentHash) external override { require(_isController[msg.sender]); _documents[name] = Doc({ docURI: uri, docHash: documentHash }); emit Document(name, uri, documentHash); } /************************************************************************************************/ /************************************** Token Information ***************************************/ /** * @dev Get balance of a tokenholder for a specific partition. * @param partition Name of the partition. * @param tokenHolder Address for which the balance is returned. * @return Amount of token of partition 'partition' held by 'tokenHolder' in the token contract. */ function balanceOfByPartition(bytes32 partition, address tokenHolder) external view override returns (uint256) { return _balanceOfByPartition[tokenHolder][partition]; } /** * @dev Get partitions index of a tokenholder. * @param tokenHolder Address for which the partitions index are returned. * @return Array of partitions index of 'tokenHolder'. */ function partitionsOf(address tokenHolder) external view override returns (bytes32[] memory) { return _partitionsOf[tokenHolder]; } /************************************************************************************************/ /****************************************** Transfers *******************************************/ /** * @dev Transfer the amount of tokens from the address 'msg.sender' to the address 'to'. * @param to Token recipient. * @param value Number of tokens to transfer. * @param data Information attached to the transfer, by the token holder. */ function transferWithData(address to, uint256 value, bytes calldata data) external override { _transferByDefaultPartitions(msg.sender, msg.sender, to, value, data); } /** * @dev Transfer the amount of tokens on behalf of the address 'from' to the address 'to'. * @param from Token holder (or 'address(0)' to set from to 'msg.sender'). * @param to Token recipient. * @param value Number of tokens to transfer. * @param data Information attached to the transfer, and intended for the token holder ('from'). */ function transferFromWithData(address from, address to, uint256 value, bytes calldata data) external override { require(_isOperator(msg.sender, from), "58"); // 0x58 invalid operator (transfer agent) _transferByDefaultPartitions(msg.sender, from, to, value, data); } /************************************************************************************************/ /********************************** Partition Token Transfers ***********************************/ /** * @dev Transfer tokens from a specific partition. * @param partition Name of the partition. * @param to Token recipient. * @param value Number of tokens to transfer. * @param data Information attached to the transfer, by the token holder. * @return Destination partition. */ function transferByPartition( bytes32 partition, address to, uint256 value, bytes calldata data ) external override returns (bytes32) { return _transferByPartition(partition, msg.sender, msg.sender, to, value, data, ""); } /** * @dev Transfer tokens from a specific partition through an operator. * @param partition Name of the partition. * @param from Token holder. * @param to Token recipient. * @param value Number of tokens to transfer. * @param data Information attached to the transfer. [CAN CONTAIN THE DESTINATION PARTITION] * @param operatorData Information attached to the transfer, by the operator. * @return Destination partition. */ function operatorTransferByPartition( bytes32 partition, address from, address to, uint256 value, bytes calldata data, bytes calldata operatorData ) external override returns (bytes32) { require(_isOperatorForPartition(partition, msg.sender, from) || (value <= _allowedByPartition[partition][from][msg.sender]), "53"); // 0x53 insufficient allowance if(_allowedByPartition[partition][from][msg.sender] >= value) { _allowedByPartition[partition][from][msg.sender] = _allowedByPartition[partition][from][msg.sender].sub(value); } else { _allowedByPartition[partition][from][msg.sender] = 0; } return _transferByPartition(partition, msg.sender, from, to, value, data, operatorData); } /************************************************************************************************/ /************************************* Controller Operation *************************************/ /** * @dev Know if the token can be controlled by operators. * If a token returns 'false' for 'isControllable()'' then it MUST always return 'false' in the future. * @return bool 'true' if the token can still be controlled by operators, 'false' if it can't anymore. */ function isControllable() external view override returns (bool) { return _isControllable; } /************************************************************************************************/ /************************************* Operator Management **************************************/ /** * @dev Set a third party operator address as an operator of 'msg.sender' to transfer * and redeem tokens on its behalf. * @param operator Address to set as an operator for 'msg.sender'. */ function authorizeOperator(address operator) external override { require(operator != msg.sender); _authorizedOperator[operator][msg.sender] = true; emit AuthorizedOperator(operator, msg.sender); } /** * @dev Remove the right of the operator address to be an operator for 'msg.sender' * and to transfer and redeem tokens on its behalf. * @param operator Address to rescind as an operator for 'msg.sender'. */ function revokeOperator(address operator) external override { require(operator != msg.sender); _authorizedOperator[operator][msg.sender] = false; emit RevokedOperator(operator, msg.sender); } /** * @dev Set 'operator' as an operator for 'msg.sender' for a given partition. * @param partition Name of the partition. * @param operator Address to set as an operator for 'msg.sender'. */ function authorizeOperatorByPartition(bytes32 partition, address operator) external override { _authorizedOperatorByPartition[msg.sender][partition][operator] = true; emit AuthorizedOperatorByPartition(partition, operator, msg.sender); } /** * @dev Remove the right of the operator address to be an operator on a given * partition for 'msg.sender' and to transfer and redeem tokens on its behalf. * @param partition Name of the partition. * @param operator Address to rescind as an operator on given partition for 'msg.sender'. */ function revokeOperatorByPartition(bytes32 partition, address operator) external override { _authorizedOperatorByPartition[msg.sender][partition][operator] = false; emit RevokedOperatorByPartition(partition, operator, msg.sender); } /************************************************************************************************/ /************************************* Operator Information *************************************/ /** * @dev Indicate whether the operator address is an operator of the tokenHolder address. * @param operator Address which may be an operator of tokenHolder. * @param tokenHolder Address of a token holder which may have the operator address as an operator. * @return 'true' if operator is an operator of 'tokenHolder' and 'false' otherwise. */ function isOperator(address operator, address tokenHolder) external view override returns (bool) { return _isOperator(operator, tokenHolder); } /** * @dev Indicate whether the operator address is an operator of the tokenHolder * address for the given partition. * @param partition Name of the partition. * @param operator Address which may be an operator of tokenHolder for the given partition. * @param tokenHolder Address of a token holder which may have the operator address as an operator for the given partition. * @return 'true' if 'operator' is an operator of 'tokenHolder' for partition 'partition' and 'false' otherwise. */ function isOperatorForPartition(bytes32 partition, address operator, address tokenHolder) external view override returns (bool) { return _isOperatorForPartition(partition, operator, tokenHolder); } /************************************************************************************************/ /**************************************** Token Issuance ****************************************/ /** * @dev Know if new tokens can be issued in the future. * @return bool 'true' if tokens can still be issued by the issuer, 'false' if they can't anymore. */ function isIssuable() external view override returns (bool) { return _isIssuable; } /** * @dev Issue tokens from default partition. * @param tokenHolder Address for which we want to issue tokens. * @param value Number of tokens issued. * @param data Information attached to the issuance, by the issuer. */ function issue(address tokenHolder, uint256 value, bytes calldata data) external override onlyOwner isIssuableToken { require(_defaultPartitions.length != 0, "55"); // 0x55 funds locked (lockup period) _issueByPartition(_defaultPartitions[0], msg.sender, tokenHolder, value, data); } /** * @dev Issue tokens from a specific partition. * @param partition Name of the partition. * @param tokenHolder Address for which we want to issue tokens. * @param value Number of tokens issued. * @param data Information attached to the issuance, by the issuer. */ function issueByPartition(bytes32 partition, address tokenHolder, uint256 value, bytes calldata data) external override onlyOwner isIssuableToken { _issueByPartition(partition, msg.sender, tokenHolder, value, data); } /************************************************************************************************/ /*************************************** Token Redemption ***************************************/ /** * @dev Redeem the amount of tokens from the address 'msg.sender'. * @param value Number of tokens to redeem. * @param data Information attached to the redemption, by the token holder. */ function redeem(uint256 value, bytes calldata data) external override { _redeemByDefaultPartitions(msg.sender, msg.sender, value, data); } /** * @dev Redeem the amount of tokens on behalf of the address from. * @param from Token holder whose tokens will be redeemed (or address(0) to set from to msg.sender). * @param value Number of tokens to redeem. * @param data Information attached to the redemption. */ function redeemFrom(address from, uint256 value, bytes calldata data) external override { require(_isOperator(msg.sender, from), "58"); // 0x58 invalid operator (transfer agent) _redeemByDefaultPartitions(msg.sender, from, value, data); } /** * @dev Redeem tokens of a specific partition. * @param partition Name of the partition. * @param value Number of tokens redeemed. * @param data Information attached to the redemption, by the redeemer. */ function redeemByPartition(bytes32 partition, uint256 value, bytes calldata data) external override { _redeemByPartition(partition, msg.sender, msg.sender, value, data, ""); } /** * @dev Redeem tokens of a specific partition. * @param partition Name of the partition. * @param tokenHolder Address for which we want to redeem tokens. * @param value Number of tokens redeemed * @param operatorData Information attached to the redemption, by the operator. */ function operatorRedeemByPartition(bytes32 partition, address tokenHolder, uint256 value, bytes calldata operatorData) external override { require(_isOperatorForPartition(partition, msg.sender, tokenHolder), "58"); // 0x58 invalid operator (transfer agent) _redeemByPartition(partition, msg.sender, tokenHolder, value, "", operatorData); } /************************************************************************************************/ /************************************************************************************************/ /************************ EXTERNAL FUNCTIONS (ADDITIONAL - NOT MANDATORY) ***********************/ /************************************************************************************************/ /************************************ Token description *****************************************/ /** * @dev Get the name of the token, e.g., "MyToken". * @return Name of the token. */ function name() external view returns(string memory) { return _name; } /** * @dev Get the symbol of the token, e.g., "MYT". * @return Symbol of the token. */ function symbol() external view returns(string memory) { return _symbol; } /** * @dev Get the number of decimals of the token. * @return The number of decimals of the token. For retrocompatibility, decimals are forced to 18 in ERC1400. */ function decimals() external pure returns(uint8) { return uint8(18); } /** * @dev Get the smallest part of the token that’s not divisible. * @return The smallest non-divisible part of the token. */ function granularity() external view returns(uint256) { return _granularity; } /** * @dev Get list of existing partitions. * @return Array of all exisiting partitions. */ function totalPartitions() external view returns (bytes32[] memory) { return _totalPartitions; } /** * @dev Get the total number of issued tokens for a given partition. * @param partition Name of the partition. * @return Total supply of tokens currently in circulation, for a given partition. */ function totalSupplyByPartition(bytes32 partition) external view returns (uint256) { return _totalSupplyByPartition[partition]; } /************************************************************************************************/ /************************************************************************************************/ /************************************* INTERNAL FUNCTIONS ***************************************/ /************************************************************************************************/ /**************************************** Token Transfers ***************************************/ /** * @dev Perform the transfer of tokens. * @param from Token holder. * @param to Token recipient. * @param value Number of tokens to transfer. */ function _transferWithData( address from, address to, uint256 value ) internal isNotMigratedToken { require(_isMultiple(value), "50"); // 0x50 transfer failure require(to != address(0), "57"); // 0x57 invalid receiver require(_balances[from] >= value, "52"); // 0x52 insufficient balance _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); // ERC20 retrocompatibility } /** * @dev Transfer tokens from a specific partition. * @param fromPartition Partition of the tokens to transfer. * @param operator The address performing the transfer. * @param from Token holder. * @param to Token recipient. * @param value Number of tokens to transfer. * @param data Information attached to the transfer. [CAN CONTAIN THE DESTINATION PARTITION] * @param operatorData Information attached to the transfer, by the operator (if any). * @return Destination partition. */ function _transferByPartition( bytes32 fromPartition, address operator, address from, address to, uint256 value, bytes memory data, bytes memory operatorData ) internal returns (bytes32) { require(_balanceOfByPartition[from][fromPartition] >= value, "52"); // 0x52 insufficient balance bytes32 toPartition = fromPartition; if(operatorData.length != 0 && data.length >= 64) { toPartition = _getDestinationPartition(fromPartition, data); } //_callSenderExtension(fromPartition, operator, from, to, value, data, operatorData); //_callTokenExtension(fromPartition, operator, from, to, value, data, operatorData); _removeTokenFromPartition(from, fromPartition, value); _transferWithData(from, to, value); _addTokenToPartition(to, toPartition, value); //_callRecipientExtension(toPartition, operator, from, to, value, data, operatorData); emit TransferByPartition(fromPartition, operator, from, to, value, data, operatorData); if(toPartition != fromPartition) { emit ChangedPartition(fromPartition, toPartition, value); } return toPartition; } /** * @dev Transfer tokens from default partitions. * Function used for ERC20 retrocompatibility. * @param operator The address performing the transfer. * @param from Token holder. * @param to Token recipient. * @param value Number of tokens to transfer. * @param data Information attached to the transfer, and intended for the token holder ('from') [CAN CONTAIN THE DESTINATION PARTITION]. */ function _transferByDefaultPartitions( address operator, address from, address to, uint256 value, bytes memory data ) internal { require(_defaultPartitions.length != 0, "55"); // // 0x55 funds locked (lockup period) uint256 _remainingValue = value; uint256 _localBalance; for (uint i = 0; i < _defaultPartitions.length; i++) { _localBalance = _balanceOfByPartition[from][_defaultPartitions[i]]; if(_remainingValue <= _localBalance) { _transferByPartition(_defaultPartitions[i], operator, from, to, _remainingValue, data, ""); _remainingValue = 0; break; } else if (_localBalance != 0) { _transferByPartition(_defaultPartitions[i], operator, from, to, _localBalance, data, ""); _remainingValue = _remainingValue - _localBalance; } } require(_remainingValue == 0, "52"); // 0x52 insufficient balance } /** * @dev Retrieve the destination partition from the 'data' field. * By convention, a partition change is requested ONLY when 'data' starts * with the flag: 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff * When the flag is detected, the destination tranche is extracted from the * 32 bytes following the flag. * @param fromPartition Partition of the tokens to transfer. * @param data Information attached to the transfer. [CAN CONTAIN THE DESTINATION PARTITION] * @return toPartition Destination partition. */ function _getDestinationPartition(bytes32 fromPartition, bytes memory data) internal pure returns(bytes32 toPartition) { bytes32 changePartitionFlag = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; bytes32 flag; assembly { flag := mload(add(data, 32)) } if(flag == changePartitionFlag) { assembly { toPartition := mload(add(data, 64)) } } else { toPartition = fromPartition; } } /** * @dev Remove a token from a specific partition. * @param from Token holder. * @param partition Name of the partition. * @param value Number of tokens to transfer. */ function _removeTokenFromPartition(address from, bytes32 partition, uint256 value) internal { _balanceOfByPartition[from][partition] = _balanceOfByPartition[from][partition].sub(value); _totalSupplyByPartition[partition] = _totalSupplyByPartition[partition].sub(value); // If the total supply is zero, finds and deletes the partition. if(_totalSupplyByPartition[partition] == 0) { uint256 index1 = _indexOfTotalPartitions[partition]; require(index1 > 0, "50"); // 0x50 transfer failure // move the last item into the index being vacated bytes32 lastValue = _totalPartitions[_totalPartitions.length - 1]; _totalPartitions[index1 - 1] = lastValue; // adjust for 1-based indexing _indexOfTotalPartitions[lastValue] = index1; _totalPartitions.pop(); _indexOfTotalPartitions[partition] = 0; } // If the balance of the TokenHolder's partition is zero, finds and deletes the partition. if(_balanceOfByPartition[from][partition] == 0) { uint256 index2 = _indexOfPartitionsOf[from][partition]; require(index2 > 0, "50"); // 0x50 transfer failure // move the last item into the index being vacated bytes32 lastValue = _partitionsOf[from][_partitionsOf[from].length - 1]; _partitionsOf[from][index2 - 1] = lastValue; // adjust for 1-based indexing _indexOfPartitionsOf[from][lastValue] = index2; _partitionsOf[from].pop(); _indexOfPartitionsOf[from][partition] = 0; } } /** * @dev Add a token to a specific partition. * @param to Token recipient. * @param partition Name of the partition. * @param value Number of tokens to transfer. */ function _addTokenToPartition(address to, bytes32 partition, uint256 value) internal { if(value != 0) { if (_indexOfPartitionsOf[to][partition] == 0) { _partitionsOf[to].push(partition); _indexOfPartitionsOf[to][partition] = _partitionsOf[to].length; } _balanceOfByPartition[to][partition] = _balanceOfByPartition[to][partition].add(value); if (_indexOfTotalPartitions[partition] == 0) { _totalPartitions.push(partition); _indexOfTotalPartitions[partition] = _totalPartitions.length; } _totalSupplyByPartition[partition] = _totalSupplyByPartition[partition].add(value); } } /** * @dev Check if 'value' is multiple of the granularity. * @param value The quantity that want's to be checked. * @return 'true' if 'value' is a multiple of the granularity. */ function _isMultiple(uint256 value) internal view returns(bool) { return(value.div(_granularity).mul(_granularity) == value); } /************************************************************************************************/ /************************************* Operator Information *************************************/ /** * @dev Indicate whether the operator address is an operator of the tokenHolder address. * @param operator Address which may be an operator of 'tokenHolder'. * @param tokenHolder Address of a token holder which may have the 'operator' address as an operator. * @return 'true' if 'operator' is an operator of 'tokenHolder' and 'false' otherwise. */ function _isOperator(address operator, address tokenHolder) internal view returns (bool) { return (operator == tokenHolder || _authorizedOperator[operator][tokenHolder] || (_isControllable && _isController[operator]) ); } /** * @dev Indicate whether the operator address is an operator of the tokenHolder * address for the given partition. * @param partition Name of the partition. * @param operator Address which may be an operator of tokenHolder for the given partition. * @param tokenHolder Address of a token holder which may have the operator address as an operator for the given partition. * @return 'true' if 'operator' is an operator of 'tokenHolder' for partition 'partition' and 'false' otherwise. */ function _isOperatorForPartition(bytes32 partition, address operator, address tokenHolder) internal view returns (bool) { return (_isOperator(operator, tokenHolder) || _authorizedOperatorByPartition[tokenHolder][partition][operator] || (_isControllable && _isControllerByPartition[partition][operator]) ); } /************************************************************************************************/ /**************************************** Token Issuance ****************************************/ /** * @dev Perform the issuance of tokens. * @param operator Address which triggered the issuance. * @param to Token recipient. * @param value Number of tokens issued. * @param data Information attached to the issuance, and intended for the recipient (to). */ function _issue(address operator, address to, uint256 value, bytes memory data) internal isNotMigratedToken { require(_isMultiple(value), "50"); // 0x50 transfer failure require(to != address(0), "57"); // 0x57 invalid receiver _totalSupply = _totalSupply.add(value); _balances[to] = _balances[to].add(value); emit Issued(operator, to, value, data); emit Transfer(address(0), to, value); // ERC20 retrocompatibility } /** * @dev Issue tokens from a specific partition. * @param toPartition Name of the partition. * @param operator The address performing the issuance. * @param to Token recipient. * @param value Number of tokens to issue. * @param data Information attached to the issuance. */ function _issueByPartition( bytes32 toPartition, address operator, address to, uint256 value, bytes memory data ) internal { //_callTokenExtension(toPartition, operator, address(0), to, value, data, ""); _issue(operator, to, value, data); _addTokenToPartition(to, toPartition, value); //_callRecipientExtension(toPartition, operator, address(0), to, value, data, ""); emit IssuedByPartition(toPartition, operator, to, value, data, ""); } /************************************************************************************************/ /*************************************** Token Redemption ***************************************/ /** * @dev Perform the token redemption. * @param operator The address performing the redemption. * @param from Token holder whose tokens will be redeemed. * @param value Number of tokens to redeem. * @param data Information attached to the redemption. */ function _redeem(address operator, address from, uint256 value, bytes memory data) internal isNotMigratedToken { require(_isMultiple(value), "50"); // 0x50 transfer failure require(from != address(0), "56"); // 0x56 invalid sender require(_balances[from] >= value, "52"); // 0x52 insufficient balance _balances[from] = _balances[from].sub(value); _totalSupply = _totalSupply.sub(value); emit Redeemed(operator, from, value, data); emit Transfer(from, address(0), value); // ERC20 retrocompatibility } /** * @dev Redeem tokens of a specific partition. * @param fromPartition Name of the partition. * @param operator The address performing the redemption. * @param from Token holder whose tokens will be redeemed. * @param value Number of tokens to redeem. * @param data Information attached to the redemption. * @param operatorData Information attached to the redemption, by the operator (if any). */ function _redeemByPartition( bytes32 fromPartition, address operator, address from, uint256 value, bytes memory data, bytes memory operatorData ) internal { require(_balanceOfByPartition[from][fromPartition] >= value, "52"); // 0x52 insufficient balance //_callSenderExtension(fromPartition, operator, from, address(0), value, data, operatorData); //_callTokenExtension(fromPartition, operator, from, address(0), value, data, operatorData); _removeTokenFromPartition(from, fromPartition, value); _redeem(operator, from, value, data); emit RedeemedByPartition(fromPartition, operator, from, value, operatorData); } /** * @dev Redeem tokens from a default partitions. * @param operator The address performing the redeem. * @param from Token holder. * @param value Number of tokens to redeem. * @param data Information attached to the redemption. */ function _redeemByDefaultPartitions( address operator, address from, uint256 value, bytes memory data ) internal { require(_defaultPartitions.length != 0, "55"); // 0x55 funds locked (lockup period) uint256 _remainingValue = value; uint256 _localBalance; for (uint i = 0; i < _defaultPartitions.length; i++) { _localBalance = _balanceOfByPartition[from][_defaultPartitions[i]]; if(_remainingValue <= _localBalance) { _redeemByPartition(_defaultPartitions[i], operator, from, _remainingValue, data, ""); _remainingValue = 0; break; } else { _redeemByPartition(_defaultPartitions[i], operator, from, _localBalance, data, ""); _remainingValue = _remainingValue - _localBalance; } } require(_remainingValue == 0, "52"); // 0x52 insufficient balance } /************************************************************************************************/ /************************************************************************************************/ /************************ INTERNAL FUNCTIONS (ADDITIONAL - NOT MANDATORY) ***********************/ /************************************************************************************************/ /************************************ Token controllers *****************************************/ /** * @dev Set list of token controllers. * @param operators Controller addresses. */ function _setControllers(address[] memory operators) internal { for (uint i = 0; i<_controllers.length; i++){ _isController[_controllers[i]] = false; } for (uint j = 0; j<operators.length; j++){ _isController[operators[j]] = true; } _controllers = operators; } /** * @dev Set list of token partition controllers. * @param partition Name of the partition. * @param operators Controller addresses. */ function _setPartitionControllers(bytes32 partition, address[] memory operators) internal { for (uint i = 0; i<_controllersByPartition[partition].length; i++){ _isControllerByPartition[partition][_controllersByPartition[partition][i]] = false; } for (uint j = 0; j<operators.length; j++){ _isControllerByPartition[partition][operators[j]] = true; } _controllersByPartition[partition] = operators; } /************************************************************************************************/ }
Redeem tokens from a default partitions. operator The address performing the redeem. from Token holder. value Number of tokens to redeem. data Information attached to the redemption./
function _redeemByDefaultPartitions( address operator, address from, uint256 value, bytes memory data ) internal { uint256 _remainingValue = value; uint256 _localBalance; for (uint i = 0; i < _defaultPartitions.length; i++) { _localBalance = _balanceOfByPartition[from][_defaultPartitions[i]]; if(_remainingValue <= _localBalance) { _redeemByPartition(_defaultPartitions[i], operator, from, _remainingValue, data, ""); _remainingValue = 0; break; _redeemByPartition(_defaultPartitions[i], operator, from, _localBalance, data, ""); _remainingValue = _remainingValue - _localBalance; } } }
13,112,600
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; pragma abicoder v2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../interfaces/ICToken.sol"; import "../../interfaces/IPendleCompoundForge.sol"; import "../../interfaces/IComptroller.sol"; import "./../abstract/PendleForgeBase.sol"; contract PendleCompoundForge is PendleForgeBase, IPendleCompoundForge { using ExpiryUtils for string; using SafeMath for uint256; using Math for uint256; IComptroller public immutable comptroller; mapping(address => uint256) public initialRate; mapping(address => address) public underlyingToCToken; mapping(address => mapping(uint256 => uint256)) public lastRateBeforeExpiry; mapping(address => mapping(uint256 => mapping(address => uint256))) public lastRate; event RegisterCTokens(address[] underlyingAssets, address[] cTokens); constructor( address _governanceManager, IPendleRouter _router, IComptroller _comptroller, bytes32 _forgeId, address _rewardToken, address _rewardManager, address _yieldContractDeployer, address _coumpoundEth ) PendleForgeBase( _governanceManager, _router, _forgeId, _rewardToken, _rewardManager, _yieldContractDeployer ) { require(address(_comptroller) != address(0), "ZERO_ADDRESS"); comptroller = _comptroller; // Pre-register for cEther address weth = address(_router.weth()); underlyingToCToken[weth] = _coumpoundEth; initialRate[weth] = ICToken(_coumpoundEth).exchangeRateCurrent(); } /// For Compound we can't get the address of cToken directly, so we need to register it manually function registerCTokens(address[] calldata _underlyingAssets, address[] calldata _cTokens) external onlyGovernance { require(_underlyingAssets.length == _cTokens.length, "LENGTH_MISMATCH"); for (uint256 i = 0; i < _cTokens.length; ++i) { // once the underlying CToken has been set, it cannot be changed require(underlyingToCToken[_underlyingAssets[i]] == address(0), "FORBIDDEN"); verifyCToken(_underlyingAssets[i], _cTokens[i]); underlyingToCToken[_underlyingAssets[i]] = _cTokens[i]; initialRate[_underlyingAssets[i]] = ICToken(_cTokens[i]).exchangeRateCurrent(); } emit RegisterCTokens(_underlyingAssets, _cTokens); } /// Use to verify the validity of a cToken. The logic of this function is similar to how Compound verify an address is cToken function verifyCToken(address _underlyingAsset, address _cTokenAddress) internal { require( comptroller.markets(_cTokenAddress).isListed && ICToken(_cTokenAddress).isCToken() && ICToken(_cTokenAddress).underlying() == _underlyingAsset, "INVALID_CTOKEN_DATA" ); } /// @inheritdoc PendleForgeBase function _calcTotalAfterExpiry( address _underlyingAsset, uint256 _expiry, uint256 redeemedAmount ) internal view override returns (uint256 totalAfterExpiry) { totalAfterExpiry = redeemedAmount.mul(initialRate[_underlyingAsset]).div( lastRateBeforeExpiry[_underlyingAsset][_expiry] ); } /** @dev this function serves functions that take into account the lastRateBeforeExpiry Else, call getExchangeRate instead */ function getExchangeRateBeforeExpiry(address _underlyingAsset, uint256 _expiry) internal returns (uint256) { if (block.timestamp > _expiry) { return lastRateBeforeExpiry[_underlyingAsset][_expiry]; } uint256 exchangeRate = ICToken(underlyingToCToken[_underlyingAsset]).exchangeRateCurrent(); lastRateBeforeExpiry[_underlyingAsset][_expiry] = exchangeRate; return exchangeRate; } /// @inheritdoc IPendleCompoundForge function getExchangeRate(address _underlyingAsset) public override returns (uint256) { return ICToken(underlyingToCToken[_underlyingAsset]).exchangeRateCurrent(); } /// @inheritdoc PendleForgeBase function _calcUnderlyingToRedeem(address _underlyingAsset, uint256 _amountToRedeem) internal override returns (uint256 underlyingToRedeem) { uint256 currentRate = getExchangeRate(_underlyingAsset); underlyingToRedeem = _amountToRedeem.mul(initialRate[_underlyingAsset]).div(currentRate); } /// @inheritdoc PendleForgeBase function _calcAmountToMint(address _underlyingAsset, uint256 _amountToTokenize) internal override returns (uint256 amountToMint) { uint256 currentRate = getExchangeRate(_underlyingAsset); amountToMint = _amountToTokenize.mul(currentRate).div(initialRate[_underlyingAsset]); } /// @inheritdoc PendleForgeBase function _getYieldBearingToken(address _underlyingAsset) internal view override returns (address) { require(underlyingToCToken[_underlyingAsset] != address(0), "INVALID_UNDERLYING_ASSET"); return underlyingToCToken[_underlyingAsset]; } /// @inheritdoc PendleForgeBase /** * Different from AaveForge, here there is no compound interest occurred because the amount of cToken always remains unchanged, only the exchangeRate does. * Since there is no compound effect, we don't need to calc the compound interest of the XYT after it has expired like Aave, and also we don't need to update the dueInterest */ function _updateDueInterests( uint256 principal, address _underlyingAsset, uint256 _expiry, address _user ) internal override { uint256 prevRate = lastRate[_underlyingAsset][_expiry][_user]; uint256 currentRate = getExchangeRateBeforeExpiry(_underlyingAsset, _expiry); lastRate[_underlyingAsset][_expiry][_user] = currentRate; // first time getting XYT, or there is no update in exchangeRate if (prevRate == 0 || prevRate == currentRate) { return; } // split into 2 statements to avoid stack error uint256 interestFromXyt = principal.mul(currentRate).div(prevRate).sub(principal); interestFromXyt = interestFromXyt.mul(initialRate[_underlyingAsset]).div(currentRate); dueInterests[_underlyingAsset][_expiry][_user] = dueInterests[_underlyingAsset][_expiry][ _user ] .add(interestFromXyt); } /// @inheritdoc PendleForgeBase /** * different from AaveForge, here there is no compound interest occurred because the amount of cToken always remains unchanged, so just add the _feeAmount in */ function _updateForgeFee( address _underlyingAsset, uint256 _expiry, uint256 _feeAmount ) internal override { totalFee[_underlyingAsset][_expiry] = totalFee[_underlyingAsset][_expiry].add(_feeAmount); } } // SPDX-License-Identifier: MIT 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; } } // SPDX-License-Identifier: MIT /* * MIT License * =========== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * 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 OR COPYRIGHT HOLDERS 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 */ pragma solidity 0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title Compound ERC20 CToken * * @dev Implementation of the interest bearing token for the DLP protocol. * @author Compound */ interface ICToken is IERC20 { /*** User Interface ***/ function balanceOfUnderlying(address owner) external returns (uint256); function isCToken() external returns (bool); function underlying() external returns (address); function mint(uint256 mintAmount) external returns (uint256); function exchangeRateCurrent() external returns (uint256); function borrow(uint256 borrowAmount) external returns (uint256); function getAccountSnapshot(address account) external view returns ( uint256 error, uint256 balance, uint256 borrowed, uint256 exchangeRate ); function decimals() external view returns (uint256); } // SPDX-License-Identifier: MIT /* * MIT License * =========== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * 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 OR COPYRIGHT HOLDERS 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 */ pragma solidity 0.7.6; import "./IPendleForge.sol"; interface IPendleCompoundForge is IPendleForge { /** @dev directly get the exchangeRate from Compound */ function getExchangeRate(address _underlyingAsset) external returns (uint256); } // SPDX-License-Identifier: MIT /* * MIT License * =========== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * 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 OR COPYRIGHT HOLDERS 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 */ pragma solidity 0.7.6; pragma abicoder v2; interface IComptroller { struct Market { bool isListed; uint256 collateralFactorMantissa; } function markets(address) external view returns (Market memory); function claimComp( address[] memory holders, address[] memory cTokens, bool borrowers, bool suppliers ) external; function getAccountLiquidity(address account) external view returns ( uint256 error, uint256 liquidity, uint256 shortfall ); function getAssetsIn(address account) external view returns (address[] memory); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../libraries/ExpiryUtilsLib.sol"; import "../../interfaces/IPendleBaseToken.sol"; import "../../interfaces/IPendleData.sol"; import "../../interfaces/IPendleForge.sol"; import "../../interfaces/IPendleRewardManager.sol"; import "../../interfaces/IPendleYieldContractDeployer.sol"; import "../../interfaces/IPendleYieldTokenHolder.sol"; import "../../periphery/WithdrawableV2.sol"; import "../../libraries/MathLib.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; /// @notice Common contract base for a forge implementation. /// @dev Each specific forge implementation will need to implement the virtual functions abstract contract PendleForgeBase is IPendleForge, WithdrawableV2, ReentrancyGuard { using ExpiryUtils for string; using SafeMath for uint256; using Math for uint256; using SafeERC20 for IERC20; struct PendleTokens { IPendleYieldToken xyt; IPendleYieldToken ot; } IPendleRouter public immutable override router; IPendleData public immutable override data; bytes32 public immutable override forgeId; IERC20 public immutable override rewardToken; // COMP/StkAAVE IPendleRewardManager public immutable override rewardManager; IPendleYieldContractDeployer public immutable override yieldContractDeployer; IPendlePausingManager public immutable pausingManager; mapping(address => mapping(uint256 => mapping(address => uint256))) public override dueInterests; mapping(address => mapping(uint256 => uint256)) public totalFee; mapping(address => mapping(uint256 => address)) public override yieldTokenHolders; // yieldTokenHolders[underlyingAsset][expiry] string private constant OT = "OT"; string private constant XYT = "YT"; modifier onlyXYT(address _underlyingAsset, uint256 _expiry) { require( msg.sender == address(data.xytTokens(forgeId, _underlyingAsset, _expiry)), "ONLY_YT" ); _; } modifier onlyOT(address _underlyingAsset, uint256 _expiry) { require( msg.sender == address(data.otTokens(forgeId, _underlyingAsset, _expiry)), "ONLY_OT" ); _; } modifier onlyRouter() { require(msg.sender == address(router), "ONLY_ROUTER"); _; } constructor( address _governanceManager, IPendleRouter _router, bytes32 _forgeId, address _rewardToken, address _rewardManager, address _yieldContractDeployer ) PermissionsV2(_governanceManager) { require(address(_router) != address(0), "ZERO_ADDRESS"); require(_forgeId != 0x0, "ZERO_BYTES"); router = _router; forgeId = _forgeId; IPendleData _dataTemp = IPendleRouter(_router).data(); data = _dataTemp; rewardToken = IERC20(_rewardToken); rewardManager = IPendleRewardManager(_rewardManager); yieldContractDeployer = IPendleYieldContractDeployer(_yieldContractDeployer); pausingManager = _dataTemp.pausingManager(); } // INVARIANT: All write functions must go through this check. // All XYT/OT transfers must go through this check as well. As such, XYT/OT transfers are also paused function checkNotPaused(address _underlyingAsset, uint256 _expiry) internal { (bool paused, ) = pausingManager.checkYieldContractStatus(forgeId, _underlyingAsset, _expiry); require(!paused, "YIELD_CONTRACT_PAUSED"); } // Only the forgeEmergencyHandler can call this function, when its in emergencyMode // this will allow a spender to spend the whole balance of the specified tokens of the yieldTokenHolder contract // the spender should ideally be a contract with logic for users to withdraw out their funds. function setUpEmergencyMode( address _underlyingAsset, uint256 _expiry, address spender ) external override { (, bool emergencyMode) = pausingManager.checkYieldContractStatus(forgeId, _underlyingAsset, _expiry); require(emergencyMode, "NOT_EMERGENCY"); (address forgeEmergencyHandler, , ) = pausingManager.forgeEmergencyHandler(); require(msg.sender == forgeEmergencyHandler, "NOT_EMERGENCY_HANDLER"); IPendleYieldTokenHolder(yieldTokenHolders[_underlyingAsset][_expiry]).setUpEmergencyMode( spender ); } /** Use: To create a newYieldContract Conditions: * only call by Router * the yield contract for this pair of _underlyingAsset & _expiry must not exist yet (checked on Router) */ function newYieldContracts(address _underlyingAsset, uint256 _expiry) external override onlyRouter returns (address ot, address xyt) { checkNotPaused(_underlyingAsset, _expiry); address yieldToken = _getYieldBearingToken(_underlyingAsset); uint8 yieldTokenDecimals = IPendleYieldToken(yieldToken).decimals(); // require(yieldToken != address(0), "INVALID_ASSET"); Guaranteed by _getYieldBearingToken // Deploy the OT contract -> XYT contract -> yieldTokenHolder ot = yieldContractDeployer.forgeOwnershipToken( _underlyingAsset, OT.concat(IPendleBaseToken(yieldToken).name(), _expiry, " "), OT.concat(IPendleBaseToken(yieldToken).symbol(), _expiry, "-"), yieldTokenDecimals, _expiry ); xyt = yieldContractDeployer.forgeFutureYieldToken( _underlyingAsset, XYT.concat(IPendleBaseToken(yieldToken).name(), _expiry, " "), XYT.concat(IPendleBaseToken(yieldToken).symbol(), _expiry, "-"), yieldTokenDecimals, _expiry ); yieldTokenHolders[_underlyingAsset][_expiry] = yieldContractDeployer .deployYieldTokenHolder(yieldToken, _expiry); data.storeTokens(forgeId, ot, xyt, _underlyingAsset, _expiry); emit NewYieldContracts(forgeId, _underlyingAsset, _expiry, ot, xyt, yieldToken); } /** Use: * To redeem the underlying asset & due interests after the XYT has expired Conditions: * only be called by Router * only callable after XYT has expired (checked on Router) * If _transferOutRate != RONE, there should be a forwardYieldToken call outside Consideration: * Why not use redeemUnderlying? Because redeemAfterExpiry doesn't require XYT (which has zero value now). Users just need OT to redeem */ function redeemAfterExpiry( address _user, address _underlyingAsset, uint256 _expiry ) external override onlyRouter returns (uint256 redeemedAmount) { checkNotPaused(_underlyingAsset, _expiry); IERC20 yieldToken = IERC20(_getYieldBearingToken(_underlyingAsset)); PendleTokens memory tokens = _getTokens(_underlyingAsset, _expiry); uint256 expiredOTamount = tokens.ot.balanceOf(_user); require(expiredOTamount > 0, "NOTHING_TO_REDEEM"); // burn ot only, since users don't need xyt to redeem this tokens.ot.burn(_user, expiredOTamount); // calc the value of the OT after since it expired (total of its underlying value + dueInterests since expiry) // no forge fee is charged on redeeming OT. Forge fee is only charged on redeeming XYT redeemedAmount = _calcTotalAfterExpiry(_underlyingAsset, _expiry, expiredOTamount); // redeem the interest of any XYT (of the same underlyingAsset+expiry) that the user is having redeemedAmount = redeemedAmount.add( _beforeTransferDueInterests(tokens, _underlyingAsset, _expiry, _user, false) ); // transfer back to the user redeemedAmount = _safeTransfer( yieldToken, _underlyingAsset, _expiry, _user, redeemedAmount ); // Notice for anyone taking values from this event: // The redeemedAmount includes the interest due to any XYT held // to get the exact yieldToken redeemed from OT, we need to deduct the (amount +forgeFeeAmount) of interests // settled that was emitted in the DueInterestsSettled event emitted earlier in this same transaction emit RedeemYieldToken( forgeId, _underlyingAsset, _expiry, expiredOTamount, redeemedAmount, _user ); } /** Use: * To redeem the underlying asset & due interests before the expiry of the XYT. In this case, for each OT used to redeem, there must be an XYT (of the same yield contract) Conditions: * only be called by Router * only callable if the XYT hasn't expired */ function redeemUnderlying( address _user, address _underlyingAsset, uint256 _expiry, uint256 _amountToRedeem ) external override onlyRouter returns (uint256 redeemedAmount) { checkNotPaused(_underlyingAsset, _expiry); PendleTokens memory tokens = _getTokens(_underlyingAsset, _expiry); IERC20 yieldToken = IERC20(_getYieldBearingToken(_underlyingAsset)); tokens.ot.burn(_user, _amountToRedeem); tokens.xyt.burn(_user, _amountToRedeem); /* * calc the amount of underlying asset for OT + the amount of dueInterests for XYT * dueInterests for XYT has been updated during the process of burning XYT, so we skip updating dueInterests in the _beforeTransferDueInterests function */ redeemedAmount = _calcUnderlyingToRedeem(_underlyingAsset, _amountToRedeem).add( _beforeTransferDueInterests(tokens, _underlyingAsset, _expiry, _user, true) ); // transfer the amountTransferOut back to the user redeemedAmount = _safeTransfer( yieldToken, _underlyingAsset, _expiry, _user, redeemedAmount ); // Notice for anyone taking values from this event: // The redeemedAmount includes the interest due to the XYT held // to get the exact yieldToken redeemed from OT+XYT, we need to deduct the (amount +forgeFeeAmount) of interests // settled that was emitted in the DueInterestsSettled event emitted earlier in this same transaction emit RedeemYieldToken( forgeId, _underlyingAsset, _expiry, _amountToRedeem, redeemedAmount, _user ); return redeemedAmount; } /** Use: * To redeem the due interests. This function can always be called regardless of whether the XYT has expired or not Conditions: * only be called by Router */ function redeemDueInterests( address _user, address _underlyingAsset, uint256 _expiry ) external override onlyRouter returns (uint256 amountOut) { checkNotPaused(_underlyingAsset, _expiry); PendleTokens memory tokens = _getTokens(_underlyingAsset, _expiry); IERC20 yieldToken = IERC20(_getYieldBearingToken(_underlyingAsset)); // update the dueInterests of the user before we transfer out amountOut = _beforeTransferDueInterests(tokens, _underlyingAsset, _expiry, _user, false); amountOut = _safeTransfer(yieldToken, _underlyingAsset, _expiry, _user, amountOut); } /** Use: * To update the dueInterests for users(before their balances of XYT changes) * This must be called before any transfer / mint/ burn action of XYT (and this has been implemented in the beforeTokenTransfer of the PendleFutureYieldToken) Conditions: * Can only be called by the respective XYT contract, before transferring XYTs */ function updateDueInterests( address _underlyingAsset, uint256 _expiry, address _user ) external override onlyXYT(_underlyingAsset, _expiry) nonReentrant { checkNotPaused(_underlyingAsset, _expiry); PendleTokens memory tokens = _getTokens(_underlyingAsset, _expiry); uint256 principal = tokens.xyt.balanceOf(_user); _updateDueInterests(principal, _underlyingAsset, _expiry, _user); } /** Use: * To redeem the rewards (COMP and StkAAVE) for users(before their balances of OT changes) * This must be called before any transfer / mint/ burn action of OT (and this has been implemented in the beforeTokenTransfer of the PendleOwnershipToken) Conditions: * Can only be called by the respective OT contract, before transferring OTs Note: This function is just a proxy to call to rewardManager */ function updatePendingRewards( address _underlyingAsset, uint256 _expiry, address _user ) external override onlyOT(_underlyingAsset, _expiry) nonReentrant { checkNotPaused(_underlyingAsset, _expiry); rewardManager.updatePendingRewards(_underlyingAsset, _expiry, _user); } /** Use: * To mint OT & XYT given that the user has transferred in _amountToTokenize of aToken/cToken * The newly minted OT & XYT can be minted to somebody else different from the user who transfer the aToken/cToken in Conditions: * Should only be called by Router * The yield contract (OT & XYT) must not be expired yet (checked at Router) */ function mintOtAndXyt( address _underlyingAsset, uint256 _expiry, uint256 _amountToTokenize, address _to ) external override onlyRouter returns ( address ot, address xyt, uint256 amountTokenMinted ) { checkNotPaused(_underlyingAsset, _expiry); PendleTokens memory tokens = _getTokens(_underlyingAsset, _expiry); amountTokenMinted = _calcAmountToMint(_underlyingAsset, _amountToTokenize); // updatePendingRewards will be called in mint tokens.ot.mint(_to, amountTokenMinted); // updateDueInterests will be called in mint tokens.xyt.mint(_to, amountTokenMinted); emit MintYieldTokens( forgeId, _underlyingAsset, _expiry, _amountToTokenize, amountTokenMinted, _to ); return (address(tokens.ot), address(tokens.xyt), amountTokenMinted); } /** Use: * To withdraw the forgeFee Conditions: * Should only be called by Governance * This function must be the only way to withdrawForgeFee Consideration: * Although this function can be called directly, it doesn't have ReentrancyGuard since it can only be called by governance */ function withdrawForgeFee(address _underlyingAsset, uint256 _expiry) external override onlyGovernance { checkNotPaused(_underlyingAsset, _expiry); IERC20 yieldToken = IERC20(_getYieldBearingToken(_underlyingAsset)); //ping to update interest up to now _updateForgeFee(_underlyingAsset, _expiry, 0); uint256 _totalFee = totalFee[_underlyingAsset][_expiry]; totalFee[_underlyingAsset][_expiry] = 0; address treasuryAddress = data.treasury(); _totalFee = _safeTransfer( yieldToken, _underlyingAsset, _expiry, treasuryAddress, _totalFee ); emit ForgeFeeWithdrawn(forgeId, _underlyingAsset, _expiry, _totalFee); } function getYieldBearingToken(address _underlyingAsset) external override returns (address) { return _getYieldBearingToken(_underlyingAsset); } /** @notice To be called before the dueInterest of any users is redeemed. @param _skipUpdateDueInterests: this is set to true, if there was already a call to _updateDueInterests() in this transaction INVARIANT: there must be a transfer of the interests (amountOut) to the user after this function is called */ function _beforeTransferDueInterests( PendleTokens memory _tokens, address _underlyingAsset, uint256 _expiry, address _user, bool _skipUpdateDueInterests ) internal returns (uint256 amountOut) { uint256 principal = _tokens.xyt.balanceOf(_user); if (!_skipUpdateDueInterests) { _updateDueInterests(principal, _underlyingAsset, _expiry, _user); } amountOut = dueInterests[_underlyingAsset][_expiry][_user]; dueInterests[_underlyingAsset][_expiry][_user] = 0; uint256 forgeFee = data.forgeFee(); uint256 forgeFeeAmount; /* * Collect the forgeFee * INVARIANT: all XYT interest payout must go through this line */ if (forgeFee > 0) { forgeFeeAmount = amountOut.rmul(forgeFee); amountOut = amountOut.sub(forgeFeeAmount); _updateForgeFee(_underlyingAsset, _expiry, forgeFeeAmount); } emit DueInterestsSettled( forgeId, _underlyingAsset, _expiry, amountOut, forgeFeeAmount, _user ); } /** Use: * Must be the only way to transfer aToken/cToken out Consideration: * Due to mathematical precision, in some extreme cases, the forge may lack a few wei of tokens to transfer back That's why there is a call to minimize the amount to transfer out with the balance of the contract * Nonetheless, because we are collecting some forge fee, so it's expected that all users will receive the full amount of aToken/cToken (and we will receive a little less than the correct amount) */ function _safeTransfer( IERC20 _yieldToken, address _underlyingAsset, uint256 _expiry, address _user, uint256 _amount ) internal returns (uint256) { address yieldTokenHolder = yieldTokenHolders[_underlyingAsset][_expiry]; _amount = Math.min(_amount, _yieldToken.balanceOf(yieldTokenHolder)); if (_amount == 0) return 0; _yieldToken.safeTransferFrom(yieldTokenHolder, _user, _amount); return _amount; } function _getTokens(address _underlyingAsset, uint256 _expiry) internal view returns (PendleTokens memory _tokens) { (_tokens.ot, _tokens.xyt) = data.getPendleYieldTokens(forgeId, _underlyingAsset, _expiry); } // There shouldn't be any fund in here // hence governance is allowed to withdraw anything from here. function _allowedToWithdraw(address) internal pure override returns (bool allowed) { allowed = true; } /// INVARIANT: after _updateDueInterests is called, dueInterests[][][] must already be /// updated with all the due interest for the user, until exactly the current timestamp (no caching whatsoever) /// Refer to updateDueInterests function for more info function _updateDueInterests( uint256 _principal, address _underlyingAsset, uint256 _expiry, address _user ) internal virtual; /** Use: * To update the amount of forgeFee (taking into account the compound interest effect) * To be called whenever the forge collect fees, or before withdrawing the fee * @param _feeAmount the new fee that this forge just collected */ function _updateForgeFee( address _underlyingAsset, uint256 _expiry, uint256 _feeAmount ) internal virtual; /// calculate the (principal + interest) from the last action before expiry to now. function _calcTotalAfterExpiry( address _underlyingAsset, uint256 _expiry, uint256 redeemedAmount ) internal virtual returns (uint256 totalAfterExpiry); /// Calc the amount of underlying asset to redeem. Default is 1 OT -> 1 yieldToken, except for Compound function _calcUnderlyingToRedeem(address, uint256 _amountToRedeem) internal virtual returns (uint256 underlyingToRedeem) { underlyingToRedeem = _amountToRedeem; } /// Calc the amount of OT & XYT to mint. Default is 1 yieldToken -> 1 OT & 1 XYT, except for Compound function _calcAmountToMint(address, uint256 _amountToTokenize) internal virtual returns (uint256 amountToMint) { amountToMint = _amountToTokenize; } /// Get the address of the yieldBearingToken from Aave/Compound function _getYieldBearingToken(address _underlyingAsset) internal virtual returns (address); } // SPDX-License-Identifier: MIT 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); } // SPDX-License-Identifier: MIT /* * MIT License * =========== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * 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 OR COPYRIGHT HOLDERS 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 */ pragma solidity 0.7.6; import "./IPendleRouter.sol"; import "./IPendleRewardManager.sol"; import "./IPendleYieldContractDeployer.sol"; import "./IPendleData.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IPendleForge { /** * @dev Emitted when the Forge has minted the OT and XYT tokens. * @param forgeId The forgeId * @param underlyingAsset The address of the underlying yield token. * @param expiry The expiry of the XYT token * @param amountToTokenize The amount of yield bearing assets to tokenize * @param amountTokenMinted The amount of OT/XYT minted **/ event MintYieldTokens( bytes32 forgeId, address indexed underlyingAsset, uint256 indexed expiry, uint256 amountToTokenize, uint256 amountTokenMinted, address indexed user ); /** * @dev Emitted when the Forge has created new yield token contracts. * @param forgeId The forgeId * @param underlyingAsset The address of the underlying asset. * @param expiry The date in epoch time when the contract will expire. * @param ot The address of the ownership token. * @param xyt The address of the new future yield token. **/ event NewYieldContracts( bytes32 forgeId, address indexed underlyingAsset, uint256 indexed expiry, address ot, address xyt, address yieldBearingAsset ); /** * @dev Emitted when the Forge has redeemed the OT and XYT tokens. * @param forgeId The forgeId * @param underlyingAsset the address of the underlying asset * @param expiry The expiry of the XYT token * @param amountToRedeem The amount of OT to be redeemed. * @param redeemedAmount The amount of yield token received **/ event RedeemYieldToken( bytes32 forgeId, address indexed underlyingAsset, uint256 indexed expiry, uint256 amountToRedeem, uint256 redeemedAmount, address indexed user ); /** * @dev Emitted when interest claim is settled * @param forgeId The forgeId * @param underlyingAsset the address of the underlying asset * @param expiry The expiry of the XYT token * @param user Interest receiver Address * @param amount The amount of interest claimed **/ event DueInterestsSettled( bytes32 forgeId, address indexed underlyingAsset, uint256 indexed expiry, uint256 amount, uint256 forgeFeeAmount, address indexed user ); /** * @dev Emitted when forge fee is withdrawn * @param forgeId The forgeId * @param underlyingAsset the address of the underlying asset * @param expiry The expiry of the XYT token * @param amount The amount of interest claimed **/ event ForgeFeeWithdrawn( bytes32 forgeId, address indexed underlyingAsset, uint256 indexed expiry, uint256 amount ); function setUpEmergencyMode( address _underlyingAsset, uint256 _expiry, address spender ) external; function newYieldContracts(address underlyingAsset, uint256 expiry) external returns (address ot, address xyt); function redeemAfterExpiry( address user, address underlyingAsset, uint256 expiry ) external returns (uint256 redeemedAmount); function redeemDueInterests( address user, address underlyingAsset, uint256 expiry ) external returns (uint256 interests); function updateDueInterests( address underlyingAsset, uint256 expiry, address user ) external; function updatePendingRewards( address _underlyingAsset, uint256 _expiry, address _user ) external; function redeemUnderlying( address user, address underlyingAsset, uint256 expiry, uint256 amountToRedeem ) external returns (uint256 redeemedAmount); function mintOtAndXyt( address underlyingAsset, uint256 expiry, uint256 amountToTokenize, address to ) external returns ( address ot, address xyt, uint256 amountTokenMinted ); function withdrawForgeFee(address underlyingAsset, uint256 expiry) external; function getYieldBearingToken(address underlyingAsset) external returns (address); /** * @notice Gets a reference to the PendleRouter contract. * @return Returns the router contract reference. **/ function router() external view returns (IPendleRouter); function data() external view returns (IPendleData); function rewardManager() external view returns (IPendleRewardManager); function yieldContractDeployer() external view returns (IPendleYieldContractDeployer); function rewardToken() external view returns (IERC20); /** * @notice Gets the bytes32 ID of the forge. * @return Returns the forge and protocol identifier. **/ function forgeId() external view returns (bytes32); function dueInterests( address _underlyingAsset, uint256 expiry, address _user ) external view returns (uint256); function yieldTokenHolders(address _underlyingAsset, uint256 _expiry) external view returns (address yieldTokenHolder); } // SPDX-License-Identifier: MIT /* * MIT License * =========== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * 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 OR COPYRIGHT HOLDERS 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 */ pragma solidity 0.7.6; pragma abicoder v2; import "../interfaces/IWETH.sol"; import "./IPendleData.sol"; import "../libraries/PendleStructs.sol"; import "./IPendleMarketFactory.sol"; interface IPendleRouter { /** * @notice Emitted when a market for a future yield token and an ERC20 token is created. * @param marketFactoryId Forge identifier. * @param xyt The address of the tokenized future yield token as the base asset. * @param token The address of an ERC20 token as the quote asset. * @param market The address of the newly created market. **/ event MarketCreated( bytes32 marketFactoryId, address indexed xyt, address indexed token, address indexed market ); /** * @notice Emitted when a swap happens on the market. * @param trader The address of msg.sender. * @param inToken The input token. * @param outToken The output token. * @param exactIn The exact amount being traded. * @param exactOut The exact amount received. * @param market The market address. **/ event SwapEvent( address indexed trader, address inToken, address outToken, uint256 exactIn, uint256 exactOut, address market ); /** * @dev Emitted when user adds liquidity * @param sender The user who added liquidity. * @param token0Amount the amount of token0 (xyt) provided by user * @param token1Amount the amount of token1 provided by user * @param market The market address. * @param exactOutLp The exact LP minted */ event Join( address indexed sender, uint256 token0Amount, uint256 token1Amount, address market, uint256 exactOutLp ); /** * @dev Emitted when user removes liquidity * @param sender The user who removed liquidity. * @param token0Amount the amount of token0 (xyt) given to user * @param token1Amount the amount of token1 given to user * @param market The market address. * @param exactInLp The exact Lp to remove */ event Exit( address indexed sender, uint256 token0Amount, uint256 token1Amount, address market, uint256 exactInLp ); /** * @notice Gets a reference to the PendleData contract. * @return Returns the data contract reference. **/ function data() external view returns (IPendleData); /** * @notice Gets a reference of the WETH9 token contract address. * @return WETH token reference. **/ function weth() external view returns (IWETH); /*********** * FORGE * ***********/ function newYieldContracts( bytes32 forgeId, address underlyingAsset, uint256 expiry ) external returns (address ot, address xyt); function redeemAfterExpiry( bytes32 forgeId, address underlyingAsset, uint256 expiry ) external returns (uint256 redeemedAmount); function redeemDueInterests( bytes32 forgeId, address underlyingAsset, uint256 expiry, address user ) external returns (uint256 interests); function redeemUnderlying( bytes32 forgeId, address underlyingAsset, uint256 expiry, uint256 amountToRedeem ) external returns (uint256 redeemedAmount); function renewYield( bytes32 forgeId, uint256 oldExpiry, address underlyingAsset, uint256 newExpiry, uint256 renewalRate ) external returns ( uint256 redeemedAmount, uint256 amountRenewed, address ot, address xyt, uint256 amountTokenMinted ); function tokenizeYield( bytes32 forgeId, address underlyingAsset, uint256 expiry, uint256 amountToTokenize, address to ) external returns ( address ot, address xyt, uint256 amountTokenMinted ); /*********** * MARKET * ***********/ function addMarketLiquidityDual( bytes32 _marketFactoryId, address _xyt, address _token, uint256 _desiredXytAmount, uint256 _desiredTokenAmount, uint256 _xytMinAmount, uint256 _tokenMinAmount ) external payable returns ( uint256 amountXytUsed, uint256 amountTokenUsed, uint256 lpOut ); function addMarketLiquiditySingle( bytes32 marketFactoryId, address xyt, address token, bool forXyt, uint256 exactInAsset, uint256 minOutLp ) external payable returns (uint256 exactOutLp); function removeMarketLiquidityDual( bytes32 marketFactoryId, address xyt, address token, uint256 exactInLp, uint256 minOutXyt, uint256 minOutToken ) external returns (uint256 exactOutXyt, uint256 exactOutToken); function removeMarketLiquiditySingle( bytes32 marketFactoryId, address xyt, address token, bool forXyt, uint256 exactInLp, uint256 minOutAsset ) external returns (uint256 exactOutXyt, uint256 exactOutToken); /** * @notice Creates a market given a protocol ID, future yield token, and an ERC20 token. * @param marketFactoryId Market Factory identifier. * @param xyt Token address of the future yield token as base asset. * @param token Token address of an ERC20 token as quote asset. * @return market Returns the address of the newly created market. **/ function createMarket( bytes32 marketFactoryId, address xyt, address token ) external returns (address market); function bootstrapMarket( bytes32 marketFactoryId, address xyt, address token, uint256 initialXytLiquidity, uint256 initialTokenLiquidity ) external payable; function swapExactIn( address tokenIn, address tokenOut, uint256 inTotalAmount, uint256 minOutTotalAmount, bytes32 marketFactoryId ) external payable returns (uint256 outTotalAmount); function swapExactOut( address tokenIn, address tokenOut, uint256 outTotalAmount, uint256 maxInTotalAmount, bytes32 marketFactoryId ) external payable returns (uint256 inTotalAmount); function redeemLpInterests(address market, address user) external returns (uint256 interests); } // SPDX-License-Identifier: MIT /* * MIT License * =========== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * 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 OR COPYRIGHT HOLDERS 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 */ pragma solidity 0.7.6; interface IPendleRewardManager { event UpdateFrequencySet(address[], uint256[]); event SkippingRewardsSet(bool); event DueRewardsSettled( bytes32 forgeId, address underlyingAsset, uint256 expiry, uint256 amountOut, address user ); function redeemRewards( address _underlyingAsset, uint256 _expiry, address _user ) external returns (uint256 dueRewards); function updatePendingRewards( address _underlyingAsset, uint256 _expiry, address _user ) external; function updateParamLManual(address _underlyingAsset, uint256 _expiry) external; function setUpdateFrequency( address[] calldata underlyingAssets, uint256[] calldata frequencies ) external; function setSkippingRewards(bool skippingRewards) external; function forgeId() external returns (bytes32); } // SPDX-License-Identifier: MIT /* * MIT License * =========== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * 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 OR COPYRIGHT HOLDERS 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 */ pragma solidity 0.7.6; interface IPendleYieldContractDeployer { function forgeId() external returns (bytes32); function forgeOwnershipToken( address _underlyingAsset, string memory _name, string memory _symbol, uint8 _decimals, uint256 _expiry ) external returns (address ot); function forgeFutureYieldToken( address _underlyingAsset, string memory _name, string memory _symbol, uint8 _decimals, uint256 _expiry ) external returns (address xyt); function deployYieldTokenHolder(address yieldToken, uint256 expiry) external returns (address yieldTokenHolder); } // SPDX-License-Identifier: MIT /* * MIT License * =========== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * 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 OR COPYRIGHT HOLDERS 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 */ pragma solidity 0.7.6; import "./IPendleRouter.sol"; import "./IPendleYieldToken.sol"; import "./IPendlePausingManager.sol"; import "./IPendleMarket.sol"; interface IPendleData { /** * @notice Emitted when validity of a forge-factory pair is updated * @param _forgeId the forge id * @param _marketFactoryId the market factory id * @param _valid valid or not **/ event ForgeFactoryValiditySet(bytes32 _forgeId, bytes32 _marketFactoryId, bool _valid); /** * @notice Emitted when Pendle and PendleFactory addresses have been updated. * @param treasury The address of the new treasury contract. **/ event TreasurySet(address treasury); /** * @notice Emitted when LockParams is changed **/ event LockParamsSet(uint256 lockNumerator, uint256 lockDenominator); /** * @notice Emitted when ExpiryDivisor is changed **/ event ExpiryDivisorSet(uint256 expiryDivisor); /** * @notice Emitted when forge fee is changed **/ event ForgeFeeSet(uint256 forgeFee); /** * @notice Emitted when interestUpdateRateDeltaForMarket is changed * @param interestUpdateRateDeltaForMarket new interestUpdateRateDeltaForMarket setting **/ event InterestUpdateRateDeltaForMarketSet(uint256 interestUpdateRateDeltaForMarket); /** * @notice Emitted when market fees are changed * @param _swapFee new swapFee setting * @param _protocolSwapFee new protocolSwapFee setting **/ event MarketFeesSet(uint256 _swapFee, uint256 _protocolSwapFee); /** * @notice Emitted when the curve shift block delta is changed * @param _blockDelta new block delta setting **/ event CurveShiftBlockDeltaSet(uint256 _blockDelta); /** * @dev Emitted when new forge is added * @param marketFactoryId Human Readable Market Factory ID in Bytes * @param marketFactoryAddress The Market Factory Address */ event NewMarketFactory(bytes32 indexed marketFactoryId, address indexed marketFactoryAddress); /** * @notice Set/update validity of a forge-factory pair * @param _forgeId the forge id * @param _marketFactoryId the market factory id * @param _valid valid or not **/ function setForgeFactoryValidity( bytes32 _forgeId, bytes32 _marketFactoryId, bool _valid ) external; /** * @notice Sets the PendleTreasury contract addresses. * @param newTreasury Address of new treasury contract. **/ function setTreasury(address newTreasury) external; /** * @notice Gets a reference to the PendleRouter contract. * @return Returns the router contract reference. **/ function router() external view returns (IPendleRouter); /** * @notice Gets a reference to the PendleRouter contract. * @return Returns the router contract reference. **/ function pausingManager() external view returns (IPendlePausingManager); /** * @notice Gets the treasury contract address where fees are being sent to. * @return Address of the treasury contract. **/ function treasury() external view returns (address); /*********** * FORGE * ***********/ /** * @notice Emitted when a forge for a protocol is added. * @param forgeId Forge and protocol identifier. * @param forgeAddress The address of the added forge. **/ event ForgeAdded(bytes32 indexed forgeId, address indexed forgeAddress); /** * @notice Adds a new forge for a protocol. * @param forgeId Forge and protocol identifier. * @param forgeAddress The address of the added forge. **/ function addForge(bytes32 forgeId, address forgeAddress) external; /** * @notice Store new OT and XYT details. * @param forgeId Forge and protocol identifier. * @param ot The address of the new XYT. * @param xyt The address of the new XYT. * @param underlyingAsset Token address of the underlying asset. * @param expiry Yield contract expiry in epoch time. **/ function storeTokens( bytes32 forgeId, address ot, address xyt, address underlyingAsset, uint256 expiry ) external; /** * @notice Set a new forge fee * @param _forgeFee new forge fee **/ function setForgeFee(uint256 _forgeFee) external; /** * @notice Gets the OT and XYT tokens. * @param forgeId Forge and protocol identifier. * @param underlyingYieldToken Token address of the underlying yield token. * @param expiry Yield contract expiry in epoch time. * @return ot The OT token references. * @return xyt The XYT token references. **/ function getPendleYieldTokens( bytes32 forgeId, address underlyingYieldToken, uint256 expiry ) external view returns (IPendleYieldToken ot, IPendleYieldToken xyt); /** * @notice Gets a forge given the identifier. * @param forgeId Forge and protocol identifier. * @return forgeAddress Returns the forge address. **/ function getForgeAddress(bytes32 forgeId) external view returns (address forgeAddress); /** * @notice Checks if an XYT token is valid. * @param forgeId The forgeId of the forge. * @param underlyingAsset Token address of the underlying asset. * @param expiry Yield contract expiry in epoch time. * @return True if valid, false otherwise. **/ function isValidXYT( bytes32 forgeId, address underlyingAsset, uint256 expiry ) external view returns (bool); /** * @notice Checks if an OT token is valid. * @param forgeId The forgeId of the forge. * @param underlyingAsset Token address of the underlying asset. * @param expiry Yield contract expiry in epoch time. * @return True if valid, false otherwise. **/ function isValidOT( bytes32 forgeId, address underlyingAsset, uint256 expiry ) external view returns (bool); function validForgeFactoryPair(bytes32 _forgeId, bytes32 _marketFactoryId) external view returns (bool); /** * @notice Gets a reference to a specific OT. * @param forgeId Forge and protocol identifier. * @param underlyingYieldToken Token address of the underlying yield token. * @param expiry Yield contract expiry in epoch time. * @return ot Returns the reference to an OT. **/ function otTokens( bytes32 forgeId, address underlyingYieldToken, uint256 expiry ) external view returns (IPendleYieldToken ot); /** * @notice Gets a reference to a specific XYT. * @param forgeId Forge and protocol identifier. * @param underlyingAsset Token address of the underlying asset * @param expiry Yield contract expiry in epoch time. * @return xyt Returns the reference to an XYT. **/ function xytTokens( bytes32 forgeId, address underlyingAsset, uint256 expiry ) external view returns (IPendleYieldToken xyt); /*********** * MARKET * ***********/ event MarketPairAdded(address indexed market, address indexed xyt, address indexed token); function addMarketFactory(bytes32 marketFactoryId, address marketFactoryAddress) external; function isMarket(address _addr) external view returns (bool result); function isXyt(address _addr) external view returns (bool result); function addMarket( bytes32 marketFactoryId, address xyt, address token, address market ) external; function setMarketFees(uint256 _swapFee, uint256 _protocolSwapFee) external; function setInterestUpdateRateDeltaForMarket(uint256 _interestUpdateRateDeltaForMarket) external; function setLockParams(uint256 _lockNumerator, uint256 _lockDenominator) external; function setExpiryDivisor(uint256 _expiryDivisor) external; function setCurveShiftBlockDelta(uint256 _blockDelta) external; /** * @notice Displays the number of markets currently existing. * @return Returns markets length, **/ function allMarketsLength() external view returns (uint256); function forgeFee() external view returns (uint256); function interestUpdateRateDeltaForMarket() external view returns (uint256); function expiryDivisor() external view returns (uint256); function lockNumerator() external view returns (uint256); function lockDenominator() external view returns (uint256); function swapFee() external view returns (uint256); function protocolSwapFee() external view returns (uint256); function curveShiftBlockDelta() external view returns (uint256); function getMarketByIndex(uint256 index) external view returns (address market); /** * @notice Gets a market given a future yield token and an ERC20 token. * @param xyt Token address of the future yield token as base asset. * @param token Token address of an ERC20 token as quote asset. * @return market Returns the market address. **/ function getMarket( bytes32 marketFactoryId, address xyt, address token ) external view returns (address market); /** * @notice Gets a market factory given the identifier. * @param marketFactoryId MarketFactory identifier. * @return marketFactoryAddress Returns the factory address. **/ function getMarketFactoryAddress(bytes32 marketFactoryId) external view returns (address marketFactoryAddress); function getMarketFromKey( address xyt, address token, bytes32 marketFactoryId ) external view returns (address market); } // SPDX-License-Identifier: MIT /* * MIT License * =========== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * 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 OR COPYRIGHT HOLDERS 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 */ pragma solidity 0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IWETH is IERC20 { function deposit() external payable; function withdraw(uint256 wad) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity 0.7.6; struct TokenReserve { uint256 weight; uint256 balance; } struct PendingTransfer { uint256 amount; bool isOut; } // SPDX-License-Identifier: MIT /* * MIT License * =========== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * 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 OR COPYRIGHT HOLDERS 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 */ pragma solidity 0.7.6; import "./IPendleRouter.sol"; interface IPendleMarketFactory { /** * @notice Creates a market given a protocol ID, future yield token, and an ERC20 token. * @param xyt Token address of the futuonlyCorere yield token as base asset. * @param token Token address of an ERC20 token as quote asset. * @return market Returns the address of the newly created market. **/ function createMarket(address xyt, address token) external returns (address market); /** * @notice Gets a reference to the PendleRouter contract. * @return Returns the router contract reference. **/ function router() external view returns (IPendleRouter); function marketFactoryId() external view returns (bytes32); } // SPDX-License-Identifier: MIT /* * MIT License * =========== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * 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 OR COPYRIGHT HOLDERS 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 */ pragma solidity 0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./IPendleBaseToken.sol"; import "./IPendleForge.sol"; interface IPendleYieldToken is IERC20, IPendleBaseToken { /** * @notice Emitted when burning OT or XYT tokens. * @param user The address performing the burn. * @param amount The amount to be burned. **/ event Burn(address indexed user, uint256 amount); /** * @notice Emitted when minting OT or XYT tokens. * @param user The address performing the mint. * @param amount The amount to be minted. **/ event Mint(address indexed user, uint256 amount); /** * @notice Burns OT or XYT tokens from user, reducing the total supply. * @param user The address performing the burn. * @param amount The amount to be burned. **/ function burn(address user, uint256 amount) external; /** * @notice Mints new OT or XYT tokens for user, increasing the total supply. * @param user The address to send the minted tokens. * @param amount The amount to be minted. **/ function mint(address user, uint256 amount) external; /** * @notice Gets the forge address of the PendleForge contract for this yield token. * @return Retuns the forge address. **/ function forge() external view returns (IPendleForge); /** * @notice Returns the address of the underlying asset. * @return Returns the underlying asset address. **/ function underlyingAsset() external view returns (address); /** * @notice Returns the address of the underlying yield token. * @return Returns the underlying yield token address. **/ function underlyingYieldToken() external view returns (address); /** * @notice let the router approve itself to spend OT/XYT/LP from any wallet * @param user user to approve **/ function approveRouter(address user) external; } // SPDX-License-Identifier: MIT /* * MIT License * =========== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * 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 OR COPYRIGHT HOLDERS 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 */ pragma solidity 0.7.6; interface IPendlePausingManager { event AddPausingAdmin(address admin); event RemovePausingAdmin(address admin); event PendingForgeEmergencyHandler(address _pendingForgeHandler); event PendingMarketEmergencyHandler(address _pendingMarketHandler); event PendingLiqMiningEmergencyHandler(address _pendingLiqMiningHandler); event ForgeEmergencyHandlerSet(address forgeEmergencyHandler); event MarketEmergencyHandlerSet(address marketEmergencyHandler); event LiqMiningEmergencyHandlerSet(address liqMiningEmergencyHandler); event PausingManagerLocked(); event ForgeHandlerLocked(); event MarketHandlerLocked(); event LiqMiningHandlerLocked(); event SetForgePaused(bytes32 forgeId, bool settingToPaused); event SetForgeAssetPaused(bytes32 forgeId, address underlyingAsset, bool settingToPaused); event SetForgeAssetExpiryPaused( bytes32 forgeId, address underlyingAsset, uint256 expiry, bool settingToPaused ); event SetForgeLocked(bytes32 forgeId); event SetForgeAssetLocked(bytes32 forgeId, address underlyingAsset); event SetForgeAssetExpiryLocked(bytes32 forgeId, address underlyingAsset, uint256 expiry); event SetMarketFactoryPaused(bytes32 marketFactoryId, bool settingToPaused); event SetMarketPaused(bytes32 marketFactoryId, address market, bool settingToPaused); event SetMarketFactoryLocked(bytes32 marketFactoryId); event SetMarketLocked(bytes32 marketFactoryId, address market); event SetLiqMiningPaused(address liqMiningContract, bool settingToPaused); event SetLiqMiningLocked(address liqMiningContract); function forgeEmergencyHandler() external view returns ( address handler, address pendingHandler, uint256 timelockDeadline ); function marketEmergencyHandler() external view returns ( address handler, address pendingHandler, uint256 timelockDeadline ); function liqMiningEmergencyHandler() external view returns ( address handler, address pendingHandler, uint256 timelockDeadline ); function permLocked() external view returns (bool); function permForgeHandlerLocked() external view returns (bool); function permMarketHandlerLocked() external view returns (bool); function permLiqMiningHandlerLocked() external view returns (bool); function isPausingAdmin(address) external view returns (bool); function setPausingAdmin(address admin, bool isAdmin) external; function requestForgeHandlerChange(address _pendingForgeHandler) external; function requestMarketHandlerChange(address _pendingMarketHandler) external; function requestLiqMiningHandlerChange(address _pendingLiqMiningHandler) external; function applyForgeHandlerChange() external; function applyMarketHandlerChange() external; function applyLiqMiningHandlerChange() external; function lockPausingManagerPermanently() external; function lockForgeHandlerPermanently() external; function lockMarketHandlerPermanently() external; function lockLiqMiningHandlerPermanently() external; function setForgePaused(bytes32 forgeId, bool paused) external; function setForgeAssetPaused( bytes32 forgeId, address underlyingAsset, bool paused ) external; function setForgeAssetExpiryPaused( bytes32 forgeId, address underlyingAsset, uint256 expiry, bool paused ) external; function setForgeLocked(bytes32 forgeId) external; function setForgeAssetLocked(bytes32 forgeId, address underlyingAsset) external; function setForgeAssetExpiryLocked( bytes32 forgeId, address underlyingAsset, uint256 expiry ) external; function checkYieldContractStatus( bytes32 forgeId, address underlyingAsset, uint256 expiry ) external returns (bool _paused, bool _locked); function setMarketFactoryPaused(bytes32 marketFactoryId, bool paused) external; function setMarketPaused( bytes32 marketFactoryId, address market, bool paused ) external; function setMarketFactoryLocked(bytes32 marketFactoryId) external; function setMarketLocked(bytes32 marketFactoryId, address market) external; function checkMarketStatus(bytes32 marketFactoryId, address market) external returns (bool _paused, bool _locked); function setLiqMiningPaused(address liqMiningContract, bool settingToPaused) external; function setLiqMiningLocked(address liqMiningContract) external; function checkLiqMiningStatus(address liqMiningContract) external returns (bool _paused, bool _locked); } // SPDX-License-Identifier: MIT /* * MIT License * =========== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * 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 OR COPYRIGHT HOLDERS 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 */ pragma solidity 0.7.6; pragma abicoder v2; import "./IPendleRouter.sol"; import "./IPendleBaseToken.sol"; import "../libraries/PendleStructs.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IPendleMarket is IERC20 { /** * @notice Emitted when reserves pool has been updated * @param reserve0 The XYT reserves. * @param weight0 The XYT weight * @param reserve1 The generic token reserves. * For the generic Token weight it can be inferred by (2^40) - weight0 **/ event Sync(uint256 reserve0, uint256 weight0, uint256 reserve1); function setUpEmergencyMode(address spender) external; function bootstrap( address user, uint256 initialXytLiquidity, uint256 initialTokenLiquidity ) external returns (PendingTransfer[2] memory transfers, uint256 exactOutLp); function addMarketLiquiditySingle( address user, address inToken, uint256 inAmount, uint256 minOutLp ) external returns (PendingTransfer[2] memory transfers, uint256 exactOutLp); function addMarketLiquidityDual( address user, uint256 _desiredXytAmount, uint256 _desiredTokenAmount, uint256 _xytMinAmount, uint256 _tokenMinAmount ) external returns (PendingTransfer[2] memory transfers, uint256 lpOut); function removeMarketLiquidityDual( address user, uint256 inLp, uint256 minOutXyt, uint256 minOutToken ) external returns (PendingTransfer[2] memory transfers); function removeMarketLiquiditySingle( address user, address outToken, uint256 exactInLp, uint256 minOutToken ) external returns (PendingTransfer[2] memory transfers); function swapExactIn( address inToken, uint256 inAmount, address outToken, uint256 minOutAmount ) external returns (uint256 outAmount, PendingTransfer[2] memory transfers); function swapExactOut( address inToken, uint256 maxInAmount, address outToken, uint256 outAmount ) external returns (uint256 inAmount, PendingTransfer[2] memory transfers); function redeemLpInterests(address user) external returns (uint256 interests); function getReserves() external view returns ( uint256 xytBalance, uint256 xytWeight, uint256 tokenBalance, uint256 tokenWeight, uint256 currentBlock ); function factoryId() external view returns (bytes32); function token() external view returns (address); function xyt() external view returns (address); } // SPDX-License-Identifier: MIT /* * MIT License * =========== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * 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 OR COPYRIGHT HOLDERS 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 */ pragma solidity 0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IPendleBaseToken is IERC20 { /** * @notice Decreases the allowance granted to spender by the caller. * @param spender The address to reduce the allowance from. * @param subtractedValue The amount allowance to subtract. * @return Returns true if allowance has decreased, otherwise false. **/ function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool); /** * @notice The yield contract start in epoch time. * @return Returns the yield start date. **/ function start() external view returns (uint256); /** * @notice The yield contract expiry in epoch time. * @return Returns the yield expiry date. **/ function expiry() external view returns (uint256); /** * @notice Increases the allowance granted to spender by the caller. * @param spender The address to increase the allowance from. * @param addedValue The amount allowance to add. * @return Returns true if allowance has increased, otherwise false **/ function increaseAllowance(address spender, uint256 addedValue) external returns (bool); /** * @notice Returns the number of decimals the token uses. * @return Returns the token's decimals. **/ function decimals() external view returns (uint8); /** * @notice Returns the name of the token. * @return Returns the token's name. **/ function name() external view returns (string memory); /** * @notice Returns the symbol of the token. * @return Returns the token's symbol. **/ function symbol() external view returns (string memory); /** * @notice approve using the owner's signature **/ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.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 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: GPL-2.0-or-later pragma solidity 0.7.6; pragma abicoder v2; import "@openzeppelin/contracts/math/SafeMath.sol"; library ExpiryUtils { struct Date { uint16 year; uint8 month; uint8 day; } uint256 private constant DAY_IN_SECONDS = 86400; uint256 private constant YEAR_IN_SECONDS = 31536000; uint256 private constant LEAP_YEAR_IN_SECONDS = 31622400; uint16 private constant ORIGIN_YEAR = 1970; /** * @notice Concatenates a Pendle token name/symbol, a yield token name/symbol, * and an expiry, using a delimiter (usually "-" or " "). * @param _bt The Pendle token name/symbol. * @param _yt The yield token name/symbol. * @param _expiry The expiry in epoch time. * @param _delimiter Can be any delimiter, but usually "-" or " ". * @return result Returns the concatenated string. **/ function concat( string memory _bt, string memory _yt, uint256 _expiry, string memory _delimiter ) internal pure returns (string memory result) { result = string( abi.encodePacked(_bt, _delimiter, _yt, _delimiter, toRFC2822String(_expiry)) ); } function toRFC2822String(uint256 _timestamp) internal pure returns (string memory s) { Date memory d = parseTimestamp(_timestamp); string memory day = uintToString(d.day); string memory month = monthName(d); string memory year = uintToString(d.year); s = string(abi.encodePacked(day, month, year)); } function getDaysInMonth(uint8 _month, uint16 _year) private pure returns (uint8) { if ( _month == 1 || _month == 3 || _month == 5 || _month == 7 || _month == 8 || _month == 10 || _month == 12 ) { return 31; } else if (_month == 4 || _month == 6 || _month == 9 || _month == 11) { return 30; } else if (isLeapYear(_year)) { return 29; } else { return 28; } } function getYear(uint256 _timestamp) private pure returns (uint16) { uint256 secondsAccountedFor = 0; uint16 year; uint256 numLeapYears; // Year year = uint16(ORIGIN_YEAR + _timestamp / YEAR_IN_SECONDS); numLeapYears = leapYearsBefore(year) - leapYearsBefore(ORIGIN_YEAR); secondsAccountedFor += LEAP_YEAR_IN_SECONDS * numLeapYears; secondsAccountedFor += YEAR_IN_SECONDS * (year - ORIGIN_YEAR - numLeapYears); while (secondsAccountedFor > _timestamp) { if (isLeapYear(uint16(year - 1))) { secondsAccountedFor -= LEAP_YEAR_IN_SECONDS; } else { secondsAccountedFor -= YEAR_IN_SECONDS; } year -= 1; } return year; } function isLeapYear(uint16 _year) private pure returns (bool) { return ((_year % 4 == 0) && (_year % 100 != 0)) || (_year % 400 == 0); } function leapYearsBefore(uint256 _year) private pure returns (uint256) { _year -= 1; return _year / 4 - _year / 100 + _year / 400; } function monthName(Date memory d) private pure returns (string memory) { string[12] memory months = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"]; return months[d.month - 1]; } function parseTimestamp(uint256 _timestamp) private pure returns (Date memory d) { uint256 secondsAccountedFor = 0; uint256 buf; uint8 i; // Year d.year = getYear(_timestamp); buf = leapYearsBefore(d.year) - leapYearsBefore(ORIGIN_YEAR); secondsAccountedFor += LEAP_YEAR_IN_SECONDS * buf; secondsAccountedFor += YEAR_IN_SECONDS * (d.year - ORIGIN_YEAR - buf); // Month uint256 secondsInMonth; for (i = 1; i <= 12; i++) { secondsInMonth = DAY_IN_SECONDS * getDaysInMonth(i, d.year); if (secondsInMonth + secondsAccountedFor > _timestamp) { d.month = i; break; } secondsAccountedFor += secondsInMonth; } // Day for (i = 1; i <= getDaysInMonth(d.month, d.year); i++) { if (DAY_IN_SECONDS + secondsAccountedFor > _timestamp) { d.day = i; break; } secondsAccountedFor += DAY_IN_SECONDS; } } function uintToString(uint256 _i) private pure returns (string memory) { if (_i == 0) { return "0"; } uint256 j = _i; uint256 len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint256 k = len - 1; while (_i != 0) { bstr[k--] = bytes1(uint8(48 + (_i % 10))); _i /= 10; } return string(bstr); } } // SPDX-License-Identifier: MIT /* * MIT License * =========== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * 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 OR COPYRIGHT HOLDERS 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 */ pragma solidity 0.7.6; interface IPendleYieldTokenHolder { function redeemRewards() external; function setUpEmergencyMode(address spender) external; function yieldToken() external returns (address); function forge() external returns (address); function rewardToken() external returns (address); function expiry() external returns (uint256); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./PermissionsV2.sol"; abstract contract WithdrawableV2 is PermissionsV2 { using SafeERC20 for IERC20; event EtherWithdraw(uint256 amount, address sendTo); event TokenWithdraw(IERC20 token, uint256 amount, address sendTo); /** * @dev Allows governance to withdraw Ether in a Pendle contract * in case of accidental ETH transfer into the contract. * @param amount The amount of Ether to withdraw. * @param sendTo The recipient address. */ function withdrawEther(uint256 amount, address payable sendTo) external onlyGovernance { (bool success, ) = sendTo.call{value: amount}(""); require(success, "WITHDRAW_FAILED"); emit EtherWithdraw(amount, sendTo); } /** * @dev Allows governance to withdraw all IERC20 compatible tokens in a Pendle * contract in case of accidental token transfer into the contract. * @param token IERC20 The address of the token contract. * @param amount The amount of IERC20 tokens to withdraw. * @param sendTo The recipient address. */ function withdrawToken( IERC20 token, uint256 amount, address sendTo ) external onlyGovernance { require(_allowedToWithdraw(address(token)), "TOKEN_NOT_ALLOWED"); token.safeTransfer(sendTo, amount); emit TokenWithdraw(token, amount, sendTo); } // must be overridden by the sub contracts, so we must consider explicitly // in each and every contract which tokens are allowed to be withdrawn function _allowedToWithdraw(address) internal view virtual returns (bool allowed); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity 0.7.6; pragma abicoder v2; import "@openzeppelin/contracts/math/SafeMath.sol"; library Math { using SafeMath for uint256; uint256 internal constant BIG_NUMBER = (uint256(1) << uint256(200)); uint256 internal constant PRECISION_BITS = 40; uint256 internal constant RONE = uint256(1) << PRECISION_BITS; uint256 internal constant PI = (314 * RONE) / 10**2; uint256 internal constant PI_PLUSONE = (414 * RONE) / 10**2; uint256 internal constant PRECISION_POW = 1e2; function checkMultOverflow(uint256 _x, uint256 _y) internal pure returns (bool) { if (_y == 0) return false; return (((_x * _y) / _y) != _x); } /** @notice find the integer part of log2(p/q) => find largest x s.t p >= q * 2^x => find largest x s.t 2^x <= p / q */ function log2Int(uint256 _p, uint256 _q) internal pure returns (uint256) { uint256 res = 0; uint256 remain = _p / _q; while (remain > 0) { res++; remain /= 2; } return res - 1; } /** @notice log2 for a number that it in [1,2) @dev _x is FP, return a FP @dev function is from Kyber. Long modified the condition to be (_x >= one) && (_x < two) to avoid the case where x = 2 may lead to incorrect result */ function log2ForSmallNumber(uint256 _x) internal pure returns (uint256) { uint256 res = 0; uint256 one = (uint256(1) << PRECISION_BITS); uint256 two = 2 * one; uint256 addition = one; require((_x >= one) && (_x < two), "MATH_ERROR"); require(PRECISION_BITS < 125, "MATH_ERROR"); for (uint256 i = PRECISION_BITS; i > 0; i--) { _x = (_x * _x) / one; addition = addition / 2; if (_x >= two) { _x = _x / 2; res += addition; } } return res; } /** @notice log2 of (p/q). returns result in FP form @dev function is from Kyber. @dev _p & _q is FP, return a FP */ function logBase2(uint256 _p, uint256 _q) internal pure returns (uint256) { uint256 n = 0; if (_p > _q) { n = log2Int(_p, _q); } require(n * RONE <= BIG_NUMBER, "MATH_ERROR"); require(!checkMultOverflow(_p, RONE), "MATH_ERROR"); require(!checkMultOverflow(n, RONE), "MATH_ERROR"); require(!checkMultOverflow(uint256(1) << n, _q), "MATH_ERROR"); uint256 y = (_p * RONE) / (_q * (uint256(1) << n)); uint256 log2Small = log2ForSmallNumber(y); assert(log2Small <= BIG_NUMBER); return n * RONE + log2Small; } /** @notice calculate ln(p/q). returned result >= 0 @dev function is from Kyber. @dev _p & _q is FP, return a FP */ function ln(uint256 p, uint256 q) internal pure returns (uint256) { uint256 ln2Numerator = 6931471805599453094172; uint256 ln2Denomerator = 10000000000000000000000; uint256 log2x = logBase2(p, q); require(!checkMultOverflow(ln2Numerator, log2x), "MATH_ERROR"); return (ln2Numerator * log2x) / ln2Denomerator; } /** @notice extract the fractional part of a FP @dev value is a FP, return a FP */ function fpart(uint256 value) internal pure returns (uint256) { return value % RONE; } /** @notice convert a FP to an Int @dev value is a FP, return an Int */ function toInt(uint256 value) internal pure returns (uint256) { return value / RONE; } /** @notice convert an Int to a FP @dev value is an Int, return a FP */ function toFP(uint256 value) internal pure returns (uint256) { return value * RONE; } /** @notice return e^exp in FP form @dev estimation by formula at http://pages.mtu.edu/~shene/COURSES/cs201/NOTES/chap04/exp.html the function is based on exp function of: https://github.com/NovakDistributed/macroverse/blob/master/contracts/RealMath.sol @dev the function is expected to converge quite fast, after about 20 iteration @dev exp is a FP, return a FP */ function rpowe(uint256 exp) internal pure returns (uint256) { uint256 res = 0; uint256 curTerm = RONE; for (uint256 n = 0; ; n++) { res += curTerm; curTerm = rmul(curTerm, rdiv(exp, toFP(n + 1))); if (curTerm == 0) { break; } if (n == 500) { /* testing shows that in the most extreme case, it will take 430 turns to converge. however, it's expected that the numbers will not exceed 2^120 in normal situation the most extreme case is rpow((1<<256)-1,(1<<40)-1) (equal to rpow((2^256-1)/2^40,0.99..9)) */ revert("RPOWE_SLOW_CONVERGE"); } } return res; } /** @notice calculate base^exp with base and exp being FP int @dev to improve accuracy, base^exp = base^(int(exp)+frac(exp)) = base^int(exp) * base^frac @dev base & exp are FP, return a FP */ function rpow(uint256 base, uint256 exp) internal pure returns (uint256) { if (exp == 0) { // Anything to the 0 is 1 return RONE; } if (base == 0) { // 0 to anything except 0 is 0 return 0; } uint256 frac = fpart(exp); // get the fractional part uint256 whole = exp - frac; uint256 wholePow = rpowi(base, toInt(whole)); // whole is a FP, convert to Int uint256 fracPow; // instead of calculating base ^ frac, we will calculate e ^ (frac*ln(base)) if (base < RONE) { /* since the base is smaller than 1.0, ln(base) < 0. Since 1 / (e^(frac*ln(1/base))) = e ^ (frac*ln(base)), we will calculate 1 / (e^(frac*ln(1/base))) instead. */ uint256 newExp = rmul(frac, ln(rdiv(RONE, base), RONE)); fracPow = rdiv(RONE, rpowe(newExp)); } else { /* base is greater than 1, calculate normally */ uint256 newExp = rmul(frac, ln(base, RONE)); fracPow = rpowe(newExp); } return rmul(wholePow, fracPow); } /** @notice return base^exp with base in FP form and exp in Int @dev this function use a technique called: exponentiating by squaring complexity O(log(q)) @dev function is from Kyber. @dev base is a FP, exp is an Int, return a FP */ function rpowi(uint256 base, uint256 exp) internal pure returns (uint256) { uint256 res = exp % 2 != 0 ? base : RONE; for (exp /= 2; exp != 0; exp /= 2) { base = rmul(base, base); if (exp % 2 != 0) { res = rmul(res, base); } } return res; } /** @dev y is an Int, returns an Int @dev babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) @dev from Uniswap */ function sqrt(uint256 y) internal pure returns (uint256 z) { if (y > 3) { z = y; uint256 x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } /** @notice divide 2 FP, return a FP @dev function is from Balancer. @dev x & y are FP, return a FP */ function rdiv(uint256 x, uint256 y) internal pure returns (uint256) { return (y / 2).add(x.mul(RONE)).div(y); } /** @notice multiply 2 FP, return a FP @dev function is from Balancer. @dev x & y are FP, return a FP */ function rmul(uint256 x, uint256 y) internal pure returns (uint256) { return (RONE / 2).add(x.mul(y)).div(RONE); } 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 subMax0(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a - b : 0; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <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 () internal { _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.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); } } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../core/PendleGovernanceManager.sol"; import "../interfaces/IPermissionsV2.sol"; abstract contract PermissionsV2 is IPermissionsV2 { PendleGovernanceManager public immutable override governanceManager; address internal initializer; constructor(address _governanceManager) { require(_governanceManager != address(0), "ZERO_ADDRESS"); initializer = msg.sender; governanceManager = PendleGovernanceManager(_governanceManager); } modifier initialized() { require(initializer == address(0), "NOT_INITIALIZED"); _; } modifier onlyGovernance() { require(msg.sender == _governance(), "ONLY_GOVERNANCE"); _; } function _governance() internal view returns (address) { return governanceManager.governance(); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; contract PendleGovernanceManager { address public governance; address public pendingGovernance; event GovernanceClaimed(address newGovernance, address previousGovernance); event TransferGovernancePending(address pendingGovernance); constructor(address _governance) { require(_governance != address(0), "ZERO_ADDRESS"); governance = _governance; } modifier onlyGovernance() { require(msg.sender == governance, "ONLY_GOVERNANCE"); _; } /** * @dev Allows the pendingGovernance address to finalize the change governance process. */ function claimGovernance() external { require(pendingGovernance == msg.sender, "WRONG_GOVERNANCE"); emit GovernanceClaimed(pendingGovernance, governance); governance = pendingGovernance; pendingGovernance = address(0); } /** * @dev Allows the current governance to set the pendingGovernance address. * @param _governance The address to transfer ownership to. */ function transferGovernance(address _governance) external onlyGovernance { require(_governance != address(0), "ZERO_ADDRESS"); pendingGovernance = _governance; emit TransferGovernancePending(pendingGovernance); } } // SPDX-License-Identifier: MIT /* * MIT License * =========== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * 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 OR COPYRIGHT HOLDERS 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 */ pragma solidity 0.7.6; pragma abicoder v2; import "../core/PendleGovernanceManager.sol"; interface IPermissionsV2 { function governanceManager() external returns (PendleGovernanceManager); }
SPDX-License-Identifier: MIT MIT License =========== Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 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 OR COPYRIGHT HOLDERS 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/
interface IPendleData { event ForgeFactoryValiditySet(bytes32 _forgeId, bytes32 _marketFactoryId, bool _valid); event TreasurySet(address treasury); event LockParamsSet(uint256 lockNumerator, uint256 lockDenominator); event ExpiryDivisorSet(uint256 expiryDivisor); event ForgeFeeSet(uint256 forgeFee); event InterestUpdateRateDeltaForMarketSet(uint256 interestUpdateRateDeltaForMarket); event MarketFeesSet(uint256 _swapFee, uint256 _protocolSwapFee); event CurveShiftBlockDeltaSet(uint256 _blockDelta); event NewMarketFactory(bytes32 indexed marketFactoryId, address indexed marketFactoryAddress); function setForgeFactoryValidity( bytes32 _forgeId, bytes32 _marketFactoryId, bool _valid ) external; function setTreasury(address newTreasury) external; function router() external view returns (IPendleRouter); function pausingManager() external view returns (IPendlePausingManager); function treasury() external view returns (address); event ForgeAdded(bytes32 indexed forgeId, address indexed forgeAddress); function addForge(bytes32 forgeId, address forgeAddress) external; function storeTokens( bytes32 forgeId, address ot, address xyt, address underlyingAsset, uint256 expiry ) external; function setForgeFee(uint256 _forgeFee) external; function getPendleYieldTokens( bytes32 forgeId, address underlyingYieldToken, uint256 expiry ) external view returns (IPendleYieldToken ot, IPendleYieldToken xyt); function getForgeAddress(bytes32 forgeId) external view returns (address forgeAddress); function isValidXYT( bytes32 forgeId, address underlyingAsset, uint256 expiry ) external view returns (bool); function isValidOT( bytes32 forgeId, address underlyingAsset, uint256 expiry ) external view returns (bool); function validForgeFactoryPair(bytes32 _forgeId, bytes32 _marketFactoryId) external view returns (bool); function otTokens( bytes32 forgeId, address underlyingYieldToken, uint256 expiry ) external view returns (IPendleYieldToken ot); function xytTokens( bytes32 forgeId, address underlyingAsset, uint256 expiry ) external view returns (IPendleYieldToken xyt); event MarketPairAdded(address indexed market, address indexed xyt, address indexed token); function addMarketFactory(bytes32 marketFactoryId, address marketFactoryAddress) external; function isMarket(address _addr) external view returns (bool result); function isXyt(address _addr) external view returns (bool result); function addMarket( bytes32 marketFactoryId, address xyt, address token, address market ) external; function setMarketFees(uint256 _swapFee, uint256 _protocolSwapFee) external; function setInterestUpdateRateDeltaForMarket(uint256 _interestUpdateRateDeltaForMarket) external; function setLockParams(uint256 _lockNumerator, uint256 _lockDenominator) external; function setExpiryDivisor(uint256 _expiryDivisor) external; function setCurveShiftBlockDelta(uint256 _blockDelta) external; function allMarketsLength() external view returns (uint256); function forgeFee() external view returns (uint256); function interestUpdateRateDeltaForMarket() external view returns (uint256); function expiryDivisor() external view returns (uint256); function lockNumerator() external view returns (uint256); function lockDenominator() external view returns (uint256); function swapFee() external view returns (uint256); function protocolSwapFee() external view returns (uint256); function curveShiftBlockDelta() external view returns (uint256); function getMarketByIndex(uint256 index) external view returns (address market); function getMarket( bytes32 marketFactoryId, address xyt, address token ) external view returns (address market); function getMarketFactoryAddress(bytes32 marketFactoryId) external view returns (address marketFactoryAddress); function getMarketFromKey( address xyt, address token, bytes32 marketFactoryId ) external view returns (address market); }
5,928,099
//SPDX-License-Identifier: MIT pragma solidity 0.7.5; import "@openzeppelin/contracts/math/Math.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; // Inheritance import "../interfaces/IStakingRewards.sol"; import "../interfaces/Pausable.sol"; import "../interfaces/RewardsDistributionRecipient.sol"; import "../interfaces/OnDemandToken.sol"; import "../interfaces/MintableToken.sol"; // based on synthetix contract StakingRewards is IStakingRewards, RewardsDistributionRecipient, ReentrancyGuard, Pausable { using SafeERC20 for IERC20; struct Times { uint32 periodFinish; uint32 rewardsDuration; uint32 lastUpdateTime; uint96 totalRewardsSupply; } // ========== STATE VARIABLES ========== // uint256 public immutable maxEverTotalRewards; IERC20 public immutable rewardsToken; IERC20 public immutable stakingToken; uint256 public rewardRate = 0; uint256 public rewardPerTokenStored; mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public rewards; uint256 private _totalSupply; mapping(address => uint256) private _balances; Times public timeData; bool public stopped; // ========== EVENTS ========== // event RewardAdded(uint256 reward); event Staked(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); event RewardsDurationUpdated(uint256 newDuration); event FarmingFinished(); // ========== MODIFIERS ========== // modifier whenActive() { require(!stopped, "farming is stopped"); _; } modifier updateReward(address account) virtual { uint256 newRewardPerTokenStored = rewardPerToken(); rewardPerTokenStored = newRewardPerTokenStored; timeData.lastUpdateTime = uint32(lastTimeRewardApplicable()); if (account != address(0)) { rewards[account] = earned(account); userRewardPerTokenPaid[account] = newRewardPerTokenStored; } _; } // ========== CONSTRUCTOR ========== // constructor( address _owner, address _rewardsDistribution, address _stakingToken, address _rewardsToken ) Owned(_owner) { require(OnDemandToken(_rewardsToken).ON_DEMAND_TOKEN(), "rewardsToken must be OnDemandToken"); stakingToken = IERC20(_stakingToken); rewardsToken = IERC20(_rewardsToken); rewardsDistribution = _rewardsDistribution; timeData.rewardsDuration = 2592000; // 30 days maxEverTotalRewards = MintableToken(_rewardsToken).maxAllowedTotalSupply(); } // ========== RESTRICTED FUNCTIONS ========== // function notifyRewardAmount( uint256 _reward ) override virtual external whenActive onlyRewardsDistribution updateReward(address(0)) { Times memory t = timeData; uint256 newRewardRate; if (block.timestamp >= t.periodFinish) { newRewardRate = _reward / t.rewardsDuration; } else { uint256 remaining = t.periodFinish - block.timestamp; uint256 leftover = remaining * rewardRate; newRewardRate = (_reward + leftover) / t.rewardsDuration; } require(newRewardRate != 0, "invalid rewardRate"); rewardRate = newRewardRate; // always increasing by _reward even if notification is in a middle of period // because leftover is included uint256 totalRewardsSupply = timeData.totalRewardsSupply + _reward; require(totalRewardsSupply <= maxEverTotalRewards, "rewards overflow"); timeData.totalRewardsSupply = uint96(totalRewardsSupply); timeData.lastUpdateTime = uint32(block.timestamp); timeData.periodFinish = uint32(block.timestamp + t.rewardsDuration); emit RewardAdded(_reward); } function setRewardsDuration(uint256 _rewardsDuration) external whenActive onlyOwner { require(_rewardsDuration != 0, "empty _rewardsDuration"); require( block.timestamp > timeData.periodFinish, "Previous period must be complete before changing the duration" ); timeData.rewardsDuration = uint32(_rewardsDuration); emit RewardsDurationUpdated(_rewardsDuration); } // when farming was started with 1y and 12tokens // and we want to finish after 4 months, we need to end up with situation // like we were starting with 4mo and 4 tokens. function finishFarming() virtual external whenActive onlyOwner { Times memory t = timeData; require(block.timestamp < t.periodFinish, "can't stop if not started or already finished"); stopped = true; if (_totalSupply != 0) { uint256 remaining = t.periodFinish - block.timestamp; timeData.rewardsDuration = uint32(t.rewardsDuration - remaining); } timeData.periodFinish = uint32(block.timestamp); emit FarmingFinished(); } // ========== MUTATIVE FUNCTIONS ========== // function exit() override external { withdraw(_balances[msg.sender]); getReward(); } function stake(uint256 amount) override external { _stake(msg.sender, amount, false); } function rescueToken(ERC20 _token, address _recipient, uint256 _amount) external onlyOwner() { if (address(_token) == address(stakingToken)) { require(_totalSupply <= stakingToken.balanceOf(address(this)) - _amount, "amount is too big to rescue"); } else if (address(_token) == address(rewardsToken)) { revert("reward token can not be rescued"); } _token.transfer(_recipient, _amount); } function periodFinish() external view returns (uint256) { return timeData.periodFinish; } function rewardsDuration() external view returns (uint256) { return timeData.rewardsDuration; } function lastUpdateTime() external view returns (uint256) { return timeData.lastUpdateTime; } function balanceOf(address account) override external view returns (uint256) { return _balances[account]; } function getRewardForDuration() override external view returns (uint256) { return rewardRate * timeData.rewardsDuration; } function version() external pure virtual returns (uint256) { return 1; } function withdraw(uint256 amount) override public { _withdraw(amount, msg.sender, msg.sender); } function getReward() override public { _getReward(msg.sender, msg.sender); } // ========== VIEWS ========== // function totalSupply() override public view returns (uint256) { return _totalSupply; } function lastTimeRewardApplicable() override public view returns (uint256) { return Math.min(block.timestamp, timeData.periodFinish); } function rewardPerToken() override public view returns (uint256) { if (_totalSupply == 0) { return rewardPerTokenStored; } return rewardPerTokenStored + ( (lastTimeRewardApplicable() - timeData.lastUpdateTime) * rewardRate * 1e18 / _totalSupply ); } function earned(address account) override virtual public view returns (uint256) { return (_balances[account] * (rewardPerToken() - userRewardPerTokenPaid[account]) / 1e18) + rewards[account]; } function _stake(address user, uint256 amount, bool migration) internal nonReentrant notPaused updateReward(user) { require(timeData.periodFinish != 0, "Stake period not started yet"); require(amount != 0, "Cannot stake 0"); _totalSupply = _totalSupply + amount; _balances[user] = _balances[user] + amount; if (migration) { // other contract will send tokens to us, this will save ~13K gas } else { // not using safe transfer, because we working with trusted tokens require(stakingToken.transferFrom(user, address(this), amount), "token transfer failed"); } emit Staked(user, amount); } /// @param amount tokens to withdraw /// @param user address /// @param recipient address, where to send tokens, if we migrating token address can be zero function _withdraw(uint256 amount, address user, address recipient) internal nonReentrant updateReward(user) { require(amount != 0, "Cannot withdraw 0"); // not using safe math, because there is no way to overflow if stake tokens not overflow _totalSupply = _totalSupply - amount; _balances[user] = _balances[user] - amount; // not using safe transfer, because we working with trusted tokens require(stakingToken.transfer(recipient, amount), "token transfer failed"); emit Withdrawn(user, amount); } /// @param user address /// @param recipient address, where to send reward function _getReward(address user, address recipient) internal virtual nonReentrant updateReward(user) returns (uint256 reward) { reward = rewards[user]; if (reward != 0) { rewards[user] = 0; OnDemandToken(address(rewardsToken)).mint(recipient, reward); emit RewardPaid(user, reward); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <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); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; 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 {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 { using SafeMath for uint256; 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. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual 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 view virtual returns (uint8) { return _decimals; } /** * @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); _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 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 virtual { _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 { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.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 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.0 <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 () internal { _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.7.5; interface IStakingRewards { // Mutative function stake(uint256 amount) external; function withdraw(uint256 amount) external; function getReward() external; function exit() external; // Views function lastTimeRewardApplicable() external view returns (uint256); function rewardPerToken() external view returns (uint256); function earned(address account) external view returns (uint256); function getRewardForDuration() external view returns (uint256); function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); } //SPDX-License-Identifier: MIT pragma solidity 0.7.5; // Inheritance import "./Owned.sol"; abstract contract Pausable is Owned { bool public paused; event PauseChanged(bool isPaused); modifier notPaused { require(!paused, "This action cannot be performed while the contract is paused"); _; } constructor() { // This contract is abstract, and thus cannot be instantiated directly require(owner() != address(0), "Owner must be set"); // Paused will be false } /** * @notice Change the paused state of the contract * @dev Only the contract owner may call this. */ function setPaused(bool _paused) external onlyOwner { // Ensure we're actually changing the state before we do anything if (_paused == paused) { return; } // Set our paused state. paused = _paused; // Let everyone know that our pause state has changed. emit PauseChanged(paused); } } //SPDX-License-Identifier: MIT pragma solidity 0.7.5; // Inheritance import "./Owned.sol"; // https://docs.synthetix.io/contracts/RewardsDistributionRecipient abstract contract RewardsDistributionRecipient is Owned { address public rewardsDistribution; modifier onlyRewardsDistribution() { require(msg.sender == rewardsDistribution, "Caller is not RewardsDistributor"); _; } function notifyRewardAmount(uint256 reward) virtual external; function setRewardsDistribution(address _rewardsDistribution) external onlyOwner { rewardsDistribution = _rewardsDistribution; } } //SPDX-License-Identifier: MIT pragma solidity 0.7.5; import "./MintableToken.sol"; abstract contract OnDemandToken is MintableToken { bool constant public ON_DEMAND_TOKEN = true; mapping (address => bool) public minters; event SetupMinter(address minter, bool active); modifier onlyOwnerOrMinter() { address msgSender = _msgSender(); require(owner() == msgSender || minters[msgSender], "access denied"); _; } function setupMinter(address _minter, bool _active) external onlyOwner() { minters[_minter] = _active; emit SetupMinter(_minter, _active); } function setupMinters(address[] calldata _minters, bool[] calldata _actives) external onlyOwner() { for (uint256 i; i < _minters.length; i++) { minters[_minters[i]] = _actives[i]; emit SetupMinter(_minters[i], _actives[i]); } } function mint(address _holder, uint256 _amount) external virtual override onlyOwnerOrMinter() assertMaxSupply(_amount) { require(_amount != 0, "zero amount"); _mint(_holder, _amount); } } //SPDX-License-Identifier: MIT pragma solidity 0.7.5; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../interfaces/Owned.sol"; import "../interfaces/IBurnableToken.sol"; /// @author umb.network abstract contract MintableToken is Owned, ERC20, IBurnableToken { uint256 public immutable maxAllowedTotalSupply; uint256 public everMinted; modifier assertMaxSupply(uint256 _amountToMint) { _assertMaxSupply(_amountToMint); _; } // ========== CONSTRUCTOR ========== // constructor (uint256 _maxAllowedTotalSupply) { require(_maxAllowedTotalSupply != 0, "_maxAllowedTotalSupply is empty"); maxAllowedTotalSupply = _maxAllowedTotalSupply; } // ========== MUTATIVE FUNCTIONS ========== // function burn(uint256 _amount) override external { _burn(msg.sender, _amount); } // ========== RESTRICTED FUNCTIONS ========== // function mint(address _holder, uint256 _amount) virtual external onlyOwner() assertMaxSupply(_amount) { require(_amount != 0, "zero amount"); _mint(_holder, _amount); } function _assertMaxSupply(uint256 _amountToMint) internal { uint256 everMintedTotal = everMinted + _amountToMint; everMinted = everMintedTotal; require(everMintedTotal <= maxAllowedTotalSupply, "total supply limit exceeded"); } } // 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; } } // SPDX-License-Identifier: MIT 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); } // SPDX-License-Identifier: MIT 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; } } // 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); } } } } //SPDX-License-Identifier: MIT pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; abstract contract Owned is Ownable { constructor(address _owner) { transferOwnership(_owner); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <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 () 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; } } //SPDX-License-Identifier: MIT pragma solidity 0.7.5; interface IBurnableToken { function burn(uint256 _amount) external; }
when farming was started with 1y and 12tokens and we want to finish after 4 months, we need to end up with situation like we were starting with 4mo and 4 tokens.
function finishFarming() virtual external whenActive onlyOwner { Times memory t = timeData; require(block.timestamp < t.periodFinish, "can't stop if not started or already finished"); stopped = true; if (_totalSupply != 0) { uint256 remaining = t.periodFinish - block.timestamp; timeData.rewardsDuration = uint32(t.rewardsDuration - remaining); } timeData.periodFinish = uint32(block.timestamp); emit FarmingFinished(); }
405,894
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.6.8; import "./ProtoBufRuntime.sol"; import "./GoogleProtobufAny.sol"; library PartSetHeader { //struct definition struct Data { uint64 total; bytes hash; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[3] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_total(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_hash(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_total( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (uint64 x, uint256 sz) = ProtoBufRuntime._decode_uint64(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.total = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_hash( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.hash = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; if (r.total != 0) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_uint64(r.total, pointer, bs); } if (r.hash.length != 0) { pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.hash, pointer, bs); } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_uint64(r.total); e += 1 + ProtoBufRuntime._sz_lendelim(r.hash.length); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (r.total != 0) { return false; } if (r.hash.length != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.total = input.total; output.hash = input.hash; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library PartSetHeader library BlockID { //struct definition struct Data { bytes hash; PartSetHeader.Data part_set_header; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[3] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_hash(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_part_set_header(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_hash( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.hash = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_part_set_header( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (PartSetHeader.Data memory x, uint256 sz) = _decode_PartSetHeader(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.part_set_header = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_PartSetHeader(uint256 p, bytes memory bs) internal pure returns (PartSetHeader.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (PartSetHeader.Data memory r, ) = PartSetHeader._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; if (r.hash.length != 0) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.hash, pointer, bs); } pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += PartSetHeader._encode_nested(r.part_set_header, pointer, bs); return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_lendelim(r.hash.length); e += 1 + ProtoBufRuntime._sz_lendelim(PartSetHeader._estimate(r.part_set_header)); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (r.hash.length != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.hash = input.hash; PartSetHeader.store(input.part_set_header, output.part_set_header); } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library BlockID library Timestamp { //struct definition struct Data { int64 secs; int64 nanos; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[3] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_secs(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_nanos(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_secs( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 x, uint256 sz) = ProtoBufRuntime._decode_int64(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.secs = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_nanos( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 x, uint256 sz) = ProtoBufRuntime._decode_int64(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.nanos = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; if (r.secs != 0) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_int64(r.secs, pointer, bs); } if (r.nanos != 0) { pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_int64(r.nanos, pointer, bs); } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_int64(r.secs); e += 1 + ProtoBufRuntime._sz_int64(r.nanos); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (r.secs != 0) { return false; } if (r.nanos != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.secs = input.secs; output.nanos = input.nanos; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library Timestamp library Consensus { //struct definition struct Data { uint64 height; uint64 app; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[3] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_height(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_app(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_height( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (uint64 x, uint256 sz) = ProtoBufRuntime._decode_uint64(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.height = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_app( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (uint64 x, uint256 sz) = ProtoBufRuntime._decode_uint64(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.app = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; if (r.height != 0) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_uint64(r.height, pointer, bs); } if (r.app != 0) { pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_uint64(r.app, pointer, bs); } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_uint64(r.height); e += 1 + ProtoBufRuntime._sz_uint64(r.app); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (r.height != 0) { return false; } if (r.app != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.height = input.height; output.app = input.app; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library Consensus library TmHeader { //struct definition struct Data { Consensus.Data version; string chain_id; int64 height; Timestamp.Data time; BlockID.Data last_block_id; bytes last_commit_hash; bytes data_hash; bytes validators_hash; bytes next_validators_hash; bytes consensus_hash; bytes app_hash; bytes last_results_hash; bytes evidence_hash; bytes proposer_address; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[15] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_version(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_chain_id(pointer, bs, r, counters); } else if (fieldId == 3) { pointer += _read_height(pointer, bs, r, counters); } else if (fieldId == 4) { pointer += _read_time(pointer, bs, r, counters); } else if (fieldId == 5) { pointer += _read_last_block_id(pointer, bs, r, counters); } else if (fieldId == 6) { pointer += _read_last_commit_hash(pointer, bs, r, counters); } else if (fieldId == 7) { pointer += _read_data_hash(pointer, bs, r, counters); } else if (fieldId == 8) { pointer += _read_validators_hash(pointer, bs, r, counters); } else if (fieldId == 9) { pointer += _read_next_validators_hash(pointer, bs, r, counters); } else if (fieldId == 10) { pointer += _read_consensus_hash(pointer, bs, r, counters); } else if (fieldId == 11) { pointer += _read_app_hash(pointer, bs, r, counters); } else if (fieldId == 12) { pointer += _read_last_results_hash(pointer, bs, r, counters); } else if (fieldId == 13) { pointer += _read_evidence_hash(pointer, bs, r, counters); } else if (fieldId == 14) { pointer += _read_proposer_address(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_version( uint256 p, bytes memory bs, Data memory r, uint[15] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (Consensus.Data memory x, uint256 sz) = _decode_Consensus(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.version = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_chain_id( uint256 p, bytes memory bs, Data memory r, uint[15] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (string memory x, uint256 sz) = ProtoBufRuntime._decode_string(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.chain_id = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_height( uint256 p, bytes memory bs, Data memory r, uint[15] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 x, uint256 sz) = ProtoBufRuntime._decode_int64(p, bs); if (isNil(r)) { counters[3] += 1; } else { r.height = x; if (counters[3] > 0) counters[3] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_time( uint256 p, bytes memory bs, Data memory r, uint[15] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (Timestamp.Data memory x, uint256 sz) = _decode_Timestamp(p, bs); if (isNil(r)) { counters[4] += 1; } else { r.time = x; if (counters[4] > 0) counters[4] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_last_block_id( uint256 p, bytes memory bs, Data memory r, uint[15] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (BlockID.Data memory x, uint256 sz) = _decode_BlockID(p, bs); if (isNil(r)) { counters[5] += 1; } else { r.last_block_id = x; if (counters[5] > 0) counters[5] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_last_commit_hash( uint256 p, bytes memory bs, Data memory r, uint[15] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[6] += 1; } else { r.last_commit_hash = x; if (counters[6] > 0) counters[6] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_data_hash( uint256 p, bytes memory bs, Data memory r, uint[15] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[7] += 1; } else { r.data_hash = x; if (counters[7] > 0) counters[7] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_validators_hash( uint256 p, bytes memory bs, Data memory r, uint[15] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[8] += 1; } else { r.validators_hash = x; if (counters[8] > 0) counters[8] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_next_validators_hash( uint256 p, bytes memory bs, Data memory r, uint[15] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[9] += 1; } else { r.next_validators_hash = x; if (counters[9] > 0) counters[9] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_consensus_hash( uint256 p, bytes memory bs, Data memory r, uint[15] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[10] += 1; } else { r.consensus_hash = x; if (counters[10] > 0) counters[10] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_app_hash( uint256 p, bytes memory bs, Data memory r, uint[15] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[11] += 1; } else { r.app_hash = x; if (counters[11] > 0) counters[11] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_last_results_hash( uint256 p, bytes memory bs, Data memory r, uint[15] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[12] += 1; } else { r.last_results_hash = x; if (counters[12] > 0) counters[12] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_evidence_hash( uint256 p, bytes memory bs, Data memory r, uint[15] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[13] += 1; } else { r.evidence_hash = x; if (counters[13] > 0) counters[13] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_proposer_address( uint256 p, bytes memory bs, Data memory r, uint[15] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[14] += 1; } else { r.proposer_address = x; if (counters[14] > 0) counters[14] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_Consensus(uint256 p, bytes memory bs) internal pure returns (Consensus.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (Consensus.Data memory r, ) = Consensus._decode(pointer, bs, sz); return (r, sz + bytesRead); } /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_Timestamp(uint256 p, bytes memory bs) internal pure returns (Timestamp.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (Timestamp.Data memory r, ) = Timestamp._decode(pointer, bs, sz); return (r, sz + bytesRead); } /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_BlockID(uint256 p, bytes memory bs) internal pure returns (BlockID.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (BlockID.Data memory r, ) = BlockID._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += Consensus._encode_nested(r.version, pointer, bs); if (bytes(r.chain_id).length != 0) { pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_string(r.chain_id, pointer, bs); } if (r.height != 0) { pointer += ProtoBufRuntime._encode_key( 3, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_int64(r.height, pointer, bs); } pointer += ProtoBufRuntime._encode_key( 4, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += Timestamp._encode_nested(r.time, pointer, bs); pointer += ProtoBufRuntime._encode_key( 5, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += BlockID._encode_nested(r.last_block_id, pointer, bs); if (r.last_commit_hash.length != 0) { pointer += ProtoBufRuntime._encode_key( 6, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.last_commit_hash, pointer, bs); } if (r.data_hash.length != 0) { pointer += ProtoBufRuntime._encode_key( 7, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.data_hash, pointer, bs); } if (r.validators_hash.length != 0) { pointer += ProtoBufRuntime._encode_key( 8, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.validators_hash, pointer, bs); } if (r.next_validators_hash.length != 0) { pointer += ProtoBufRuntime._encode_key( 9, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.next_validators_hash, pointer, bs); } if (r.consensus_hash.length != 0) { pointer += ProtoBufRuntime._encode_key( 10, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.consensus_hash, pointer, bs); } if (r.app_hash.length != 0) { pointer += ProtoBufRuntime._encode_key( 11, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.app_hash, pointer, bs); } if (r.last_results_hash.length != 0) { pointer += ProtoBufRuntime._encode_key( 12, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.last_results_hash, pointer, bs); } if (r.evidence_hash.length != 0) { pointer += ProtoBufRuntime._encode_key( 13, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.evidence_hash, pointer, bs); } if (r.proposer_address.length != 0) { pointer += ProtoBufRuntime._encode_key( 14, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.proposer_address, pointer, bs); } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_lendelim(Consensus._estimate(r.version)); e += 1 + ProtoBufRuntime._sz_lendelim(bytes(r.chain_id).length); e += 1 + ProtoBufRuntime._sz_int64(r.height); e += 1 + ProtoBufRuntime._sz_lendelim(Timestamp._estimate(r.time)); e += 1 + ProtoBufRuntime._sz_lendelim(BlockID._estimate(r.last_block_id)); e += 1 + ProtoBufRuntime._sz_lendelim(r.last_commit_hash.length); e += 1 + ProtoBufRuntime._sz_lendelim(r.data_hash.length); e += 1 + ProtoBufRuntime._sz_lendelim(r.validators_hash.length); e += 1 + ProtoBufRuntime._sz_lendelim(r.next_validators_hash.length); e += 1 + ProtoBufRuntime._sz_lendelim(r.consensus_hash.length); e += 1 + ProtoBufRuntime._sz_lendelim(r.app_hash.length); e += 1 + ProtoBufRuntime._sz_lendelim(r.last_results_hash.length); e += 1 + ProtoBufRuntime._sz_lendelim(r.evidence_hash.length); e += 1 + ProtoBufRuntime._sz_lendelim(r.proposer_address.length); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (bytes(r.chain_id).length != 0) { return false; } if (r.height != 0) { return false; } if (r.last_commit_hash.length != 0) { return false; } if (r.data_hash.length != 0) { return false; } if (r.validators_hash.length != 0) { return false; } if (r.next_validators_hash.length != 0) { return false; } if (r.consensus_hash.length != 0) { return false; } if (r.app_hash.length != 0) { return false; } if (r.last_results_hash.length != 0) { return false; } if (r.evidence_hash.length != 0) { return false; } if (r.proposer_address.length != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { Consensus.store(input.version, output.version); output.chain_id = input.chain_id; output.height = input.height; Timestamp.store(input.time, output.time); BlockID.store(input.last_block_id, output.last_block_id); output.last_commit_hash = input.last_commit_hash; output.data_hash = input.data_hash; output.validators_hash = input.validators_hash; output.next_validators_hash = input.next_validators_hash; output.consensus_hash = input.consensus_hash; output.app_hash = input.app_hash; output.last_results_hash = input.last_results_hash; output.evidence_hash = input.evidence_hash; output.proposer_address = input.proposer_address; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library TmHeader library Vote { //struct definition struct Data { TYPES_PROTO_GLOBAL_ENUMS.SignedMsgType typ; int64 height; int64 round; BlockID.Data block_id; Timestamp.Data timestamp; bytes validator_address; int64 validator_index; bytes signature; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[9] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_typ(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_height(pointer, bs, r, counters); } else if (fieldId == 3) { pointer += _read_round(pointer, bs, r, counters); } else if (fieldId == 4) { pointer += _read_block_id(pointer, bs, r, counters); } else if (fieldId == 5) { pointer += _read_timestamp(pointer, bs, r, counters); } else if (fieldId == 6) { pointer += _read_validator_address(pointer, bs, r, counters); } else if (fieldId == 7) { pointer += _read_validator_index(pointer, bs, r, counters); } else if (fieldId == 8) { pointer += _read_signature(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_typ( uint256 p, bytes memory bs, Data memory r, uint[9] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 tmp, uint256 sz) = ProtoBufRuntime._decode_enum(p, bs); TYPES_PROTO_GLOBAL_ENUMS.SignedMsgType x = TYPES_PROTO_GLOBAL_ENUMS.decode_SignedMsgType(tmp); if (isNil(r)) { counters[1] += 1; } else { r.typ = x; if(counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_height( uint256 p, bytes memory bs, Data memory r, uint[9] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 x, uint256 sz) = ProtoBufRuntime._decode_int64(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.height = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_round( uint256 p, bytes memory bs, Data memory r, uint[9] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 x, uint256 sz) = ProtoBufRuntime._decode_int64(p, bs); if (isNil(r)) { counters[3] += 1; } else { r.round = x; if (counters[3] > 0) counters[3] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_block_id( uint256 p, bytes memory bs, Data memory r, uint[9] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (BlockID.Data memory x, uint256 sz) = _decode_BlockID(p, bs); if (isNil(r)) { counters[4] += 1; } else { r.block_id = x; if (counters[4] > 0) counters[4] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_timestamp( uint256 p, bytes memory bs, Data memory r, uint[9] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (Timestamp.Data memory x, uint256 sz) = _decode_Timestamp(p, bs); if (isNil(r)) { counters[5] += 1; } else { r.timestamp = x; if (counters[5] > 0) counters[5] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_validator_address( uint256 p, bytes memory bs, Data memory r, uint[9] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[6] += 1; } else { r.validator_address = x; if (counters[6] > 0) counters[6] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_validator_index( uint256 p, bytes memory bs, Data memory r, uint[9] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 x, uint256 sz) = ProtoBufRuntime._decode_int64(p, bs); if (isNil(r)) { counters[7] += 1; } else { r.validator_index = x; if (counters[7] > 0) counters[7] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_signature( uint256 p, bytes memory bs, Data memory r, uint[9] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[8] += 1; } else { r.signature = x; if (counters[8] > 0) counters[8] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_BlockID(uint256 p, bytes memory bs) internal pure returns (BlockID.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (BlockID.Data memory r, ) = BlockID._decode(pointer, bs, sz); return (r, sz + bytesRead); } /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_Timestamp(uint256 p, bytes memory bs) internal pure returns (Timestamp.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (Timestamp.Data memory r, ) = Timestamp._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; if (uint(r.typ) != 0) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.Varint, pointer, bs ); int32 _enum_typ = TYPES_PROTO_GLOBAL_ENUMS.encode_SignedMsgType(r.typ); pointer += ProtoBufRuntime._encode_enum(_enum_typ, pointer, bs); } if (r.height != 0) { pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_int64(r.height, pointer, bs); } if (r.round != 0) { pointer += ProtoBufRuntime._encode_key( 3, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_int64(r.round, pointer, bs); } pointer += ProtoBufRuntime._encode_key( 4, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += BlockID._encode_nested(r.block_id, pointer, bs); pointer += ProtoBufRuntime._encode_key( 5, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += Timestamp._encode_nested(r.timestamp, pointer, bs); if (r.validator_address.length != 0) { pointer += ProtoBufRuntime._encode_key( 6, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.validator_address, pointer, bs); } if (r.validator_index != 0) { pointer += ProtoBufRuntime._encode_key( 7, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_int64(r.validator_index, pointer, bs); } if (r.signature.length != 0) { pointer += ProtoBufRuntime._encode_key( 8, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.signature, pointer, bs); } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_enum(TYPES_PROTO_GLOBAL_ENUMS.encode_SignedMsgType(r.typ)); e += 1 + ProtoBufRuntime._sz_int64(r.height); e += 1 + ProtoBufRuntime._sz_int64(r.round); e += 1 + ProtoBufRuntime._sz_lendelim(BlockID._estimate(r.block_id)); e += 1 + ProtoBufRuntime._sz_lendelim(Timestamp._estimate(r.timestamp)); e += 1 + ProtoBufRuntime._sz_lendelim(r.validator_address.length); e += 1 + ProtoBufRuntime._sz_int64(r.validator_index); e += 1 + ProtoBufRuntime._sz_lendelim(r.signature.length); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (uint(r.typ) != 0) { return false; } if (r.height != 0) { return false; } if (r.round != 0) { return false; } if (r.validator_address.length != 0) { return false; } if (r.validator_index != 0) { return false; } if (r.signature.length != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.typ = input.typ; output.height = input.height; output.round = input.round; BlockID.store(input.block_id, output.block_id); Timestamp.store(input.timestamp, output.timestamp); output.validator_address = input.validator_address; output.validator_index = input.validator_index; output.signature = input.signature; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library Vote library Commit { //struct definition struct Data { int64 height; int64 round; BlockID.Data block_id; CommitSig.Data[] signatures; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[5] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_height(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_round(pointer, bs, r, counters); } else if (fieldId == 3) { pointer += _read_block_id(pointer, bs, r, counters); } else if (fieldId == 4) { pointer += _read_signatures(pointer, bs, nil(), counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } pointer = offset; r.signatures = new CommitSig.Data[](counters[4]); while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_height(pointer, bs, nil(), counters); } else if (fieldId == 2) { pointer += _read_round(pointer, bs, nil(), counters); } else if (fieldId == 3) { pointer += _read_block_id(pointer, bs, nil(), counters); } else if (fieldId == 4) { pointer += _read_signatures(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_height( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 x, uint256 sz) = ProtoBufRuntime._decode_int64(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.height = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_round( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 x, uint256 sz) = ProtoBufRuntime._decode_int64(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.round = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_block_id( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (BlockID.Data memory x, uint256 sz) = _decode_BlockID(p, bs); if (isNil(r)) { counters[3] += 1; } else { r.block_id = x; if (counters[3] > 0) counters[3] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_signatures( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (CommitSig.Data memory x, uint256 sz) = _decode_CommitSig(p, bs); if (isNil(r)) { counters[4] += 1; } else { r.signatures[r.signatures.length - counters[4]] = x; if (counters[4] > 0) counters[4] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_BlockID(uint256 p, bytes memory bs) internal pure returns (BlockID.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (BlockID.Data memory r, ) = BlockID._decode(pointer, bs, sz); return (r, sz + bytesRead); } /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_CommitSig(uint256 p, bytes memory bs) internal pure returns (CommitSig.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (CommitSig.Data memory r, ) = CommitSig._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; uint256 i; if (r.height != 0) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_int64(r.height, pointer, bs); } if (r.round != 0) { pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_int64(r.round, pointer, bs); } pointer += ProtoBufRuntime._encode_key( 3, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += BlockID._encode_nested(r.block_id, pointer, bs); if (r.signatures.length != 0) { for(i = 0; i < r.signatures.length; i++) { pointer += ProtoBufRuntime._encode_key( 4, ProtoBufRuntime.WireType.LengthDelim, pointer, bs) ; pointer += CommitSig._encode_nested(r.signatures[i], pointer, bs); } } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e;uint256 i; e += 1 + ProtoBufRuntime._sz_int64(r.height); e += 1 + ProtoBufRuntime._sz_int64(r.round); e += 1 + ProtoBufRuntime._sz_lendelim(BlockID._estimate(r.block_id)); for(i = 0; i < r.signatures.length; i++) { e += 1 + ProtoBufRuntime._sz_lendelim(CommitSig._estimate(r.signatures[i])); } return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (r.height != 0) { return false; } if (r.round != 0) { return false; } if (r.signatures.length != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.height = input.height; output.round = input.round; BlockID.store(input.block_id, output.block_id); for(uint256 i4 = 0; i4 < input.signatures.length; i4++) { output.signatures.push(input.signatures[i4]); } } //array helpers for Signatures /** * @dev Add value to an array * @param self The in-memory struct * @param value The value to add */ function addSignatures(Data memory self, CommitSig.Data memory value) internal pure { /** * First resize the array. Then add the new element to the end. */ CommitSig.Data[] memory tmp = new CommitSig.Data[](self.signatures.length + 1); for (uint256 i = 0; i < self.signatures.length; i++) { tmp[i] = self.signatures[i]; } tmp[self.signatures.length] = value; self.signatures = tmp; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library Commit library CommitSig { //struct definition struct Data { TYPES_PROTO_GLOBAL_ENUMS.BlockIDFlag block_id_flag; bytes validator_address; Timestamp.Data timestamp; bytes signature; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[5] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_block_id_flag(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_validator_address(pointer, bs, r, counters); } else if (fieldId == 3) { pointer += _read_timestamp(pointer, bs, r, counters); } else if (fieldId == 4) { pointer += _read_signature(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_block_id_flag( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 tmp, uint256 sz) = ProtoBufRuntime._decode_enum(p, bs); TYPES_PROTO_GLOBAL_ENUMS.BlockIDFlag x = TYPES_PROTO_GLOBAL_ENUMS.decode_BlockIDFlag(tmp); if (isNil(r)) { counters[1] += 1; } else { r.block_id_flag = x; if(counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_validator_address( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.validator_address = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_timestamp( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (Timestamp.Data memory x, uint256 sz) = _decode_Timestamp(p, bs); if (isNil(r)) { counters[3] += 1; } else { r.timestamp = x; if (counters[3] > 0) counters[3] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_signature( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[4] += 1; } else { r.signature = x; if (counters[4] > 0) counters[4] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_Timestamp(uint256 p, bytes memory bs) internal pure returns (Timestamp.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (Timestamp.Data memory r, ) = Timestamp._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; if (uint(r.block_id_flag) != 0) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.Varint, pointer, bs ); int32 _enum_block_id_flag = TYPES_PROTO_GLOBAL_ENUMS.encode_BlockIDFlag(r.block_id_flag); pointer += ProtoBufRuntime._encode_enum(_enum_block_id_flag, pointer, bs); } if (r.validator_address.length != 0) { pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.validator_address, pointer, bs); } pointer += ProtoBufRuntime._encode_key( 3, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += Timestamp._encode_nested(r.timestamp, pointer, bs); if (r.signature.length != 0) { pointer += ProtoBufRuntime._encode_key( 4, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.signature, pointer, bs); } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_enum(TYPES_PROTO_GLOBAL_ENUMS.encode_BlockIDFlag(r.block_id_flag)); e += 1 + ProtoBufRuntime._sz_lendelim(r.validator_address.length); e += 1 + ProtoBufRuntime._sz_lendelim(Timestamp._estimate(r.timestamp)); e += 1 + ProtoBufRuntime._sz_lendelim(r.signature.length); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (uint(r.block_id_flag) != 0) { return false; } if (r.validator_address.length != 0) { return false; } if (r.signature.length != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.block_id_flag = input.block_id_flag; output.validator_address = input.validator_address; Timestamp.store(input.timestamp, output.timestamp); output.signature = input.signature; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library CommitSig library SignedHeader { //struct definition struct Data { TmHeader.Data header; Commit.Data commit; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[3] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_header(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_commit(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_header( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (TmHeader.Data memory x, uint256 sz) = _decode_TmHeader(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.header = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_commit( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (Commit.Data memory x, uint256 sz) = _decode_Commit(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.commit = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_TmHeader(uint256 p, bytes memory bs) internal pure returns (TmHeader.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (TmHeader.Data memory r, ) = TmHeader._decode(pointer, bs, sz); return (r, sz + bytesRead); } /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_Commit(uint256 p, bytes memory bs) internal pure returns (Commit.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (Commit.Data memory r, ) = Commit._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += TmHeader._encode_nested(r.header, pointer, bs); pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += Commit._encode_nested(r.commit, pointer, bs); return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_lendelim(TmHeader._estimate(r.header)); e += 1 + ProtoBufRuntime._sz_lendelim(Commit._estimate(r.commit)); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { TmHeader.store(input.header, output.header); Commit.store(input.commit, output.commit); } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library SignedHeader library CanonicalBlockID { //struct definition struct Data { bytes hash; CanonicalPartSetHeader.Data part_set_header; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[3] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_hash(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_part_set_header(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_hash( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.hash = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_part_set_header( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (CanonicalPartSetHeader.Data memory x, uint256 sz) = _decode_CanonicalPartSetHeader(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.part_set_header = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_CanonicalPartSetHeader(uint256 p, bytes memory bs) internal pure returns (CanonicalPartSetHeader.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (CanonicalPartSetHeader.Data memory r, ) = CanonicalPartSetHeader._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; if (r.hash.length != 0) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.hash, pointer, bs); } pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += CanonicalPartSetHeader._encode_nested(r.part_set_header, pointer, bs); return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_lendelim(r.hash.length); e += 1 + ProtoBufRuntime._sz_lendelim(CanonicalPartSetHeader._estimate(r.part_set_header)); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (r.hash.length != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.hash = input.hash; CanonicalPartSetHeader.store(input.part_set_header, output.part_set_header); } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library CanonicalBlockID library CanonicalPartSetHeader { //struct definition struct Data { uint64 total; bytes hash; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[3] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_total(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_hash(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_total( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (uint64 x, uint256 sz) = ProtoBufRuntime._decode_uint64(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.total = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_hash( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.hash = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; if (r.total != 0) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_uint64(r.total, pointer, bs); } if (r.hash.length != 0) { pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.hash, pointer, bs); } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_uint64(r.total); e += 1 + ProtoBufRuntime._sz_lendelim(r.hash.length); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (r.total != 0) { return false; } if (r.hash.length != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.total = input.total; output.hash = input.hash; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library CanonicalPartSetHeader library CanonicalVote { //struct definition struct Data { TYPES_PROTO_GLOBAL_ENUMS.SignedMsgType typ; int64 height; int64 round; CanonicalBlockID.Data block_id; Timestamp.Data timestamp; string chain_id; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[7] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_typ(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_height(pointer, bs, r, counters); } else if (fieldId == 3) { pointer += _read_round(pointer, bs, r, counters); } else if (fieldId == 4) { pointer += _read_block_id(pointer, bs, r, counters); } else if (fieldId == 5) { pointer += _read_timestamp(pointer, bs, r, counters); } else if (fieldId == 6) { pointer += _read_chain_id(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_typ( uint256 p, bytes memory bs, Data memory r, uint[7] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 tmp, uint256 sz) = ProtoBufRuntime._decode_enum(p, bs); TYPES_PROTO_GLOBAL_ENUMS.SignedMsgType x = TYPES_PROTO_GLOBAL_ENUMS.decode_SignedMsgType(tmp); if (isNil(r)) { counters[1] += 1; } else { r.typ = x; if(counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_height( uint256 p, bytes memory bs, Data memory r, uint[7] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 x, uint256 sz) = ProtoBufRuntime._decode_sfixed64(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.height = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_round( uint256 p, bytes memory bs, Data memory r, uint[7] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 x, uint256 sz) = ProtoBufRuntime._decode_sfixed64(p, bs); if (isNil(r)) { counters[3] += 1; } else { r.round = x; if (counters[3] > 0) counters[3] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_block_id( uint256 p, bytes memory bs, Data memory r, uint[7] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (CanonicalBlockID.Data memory x, uint256 sz) = _decode_CanonicalBlockID(p, bs); if (isNil(r)) { counters[4] += 1; } else { r.block_id = x; if (counters[4] > 0) counters[4] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_timestamp( uint256 p, bytes memory bs, Data memory r, uint[7] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (Timestamp.Data memory x, uint256 sz) = _decode_Timestamp(p, bs); if (isNil(r)) { counters[5] += 1; } else { r.timestamp = x; if (counters[5] > 0) counters[5] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_chain_id( uint256 p, bytes memory bs, Data memory r, uint[7] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (string memory x, uint256 sz) = ProtoBufRuntime._decode_string(p, bs); if (isNil(r)) { counters[6] += 1; } else { r.chain_id = x; if (counters[6] > 0) counters[6] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_CanonicalBlockID(uint256 p, bytes memory bs) internal pure returns (CanonicalBlockID.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (CanonicalBlockID.Data memory r, ) = CanonicalBlockID._decode(pointer, bs, sz); return (r, sz + bytesRead); } /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_Timestamp(uint256 p, bytes memory bs) internal pure returns (Timestamp.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (Timestamp.Data memory r, ) = Timestamp._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; if (uint(r.typ) != 0) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.Varint, pointer, bs ); int32 _enum_typ = TYPES_PROTO_GLOBAL_ENUMS.encode_SignedMsgType(r.typ); pointer += ProtoBufRuntime._encode_enum(_enum_typ, pointer, bs); } if (r.height != 0) { pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.Fixed64, pointer, bs ); pointer += ProtoBufRuntime._encode_sfixed64(r.height, pointer, bs); } if (r.round != 0) { pointer += ProtoBufRuntime._encode_key( 3, ProtoBufRuntime.WireType.Fixed64, pointer, bs ); pointer += ProtoBufRuntime._encode_sfixed64(r.round, pointer, bs); } pointer += ProtoBufRuntime._encode_key( 4, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += CanonicalBlockID._encode_nested(r.block_id, pointer, bs); pointer += ProtoBufRuntime._encode_key( 5, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += Timestamp._encode_nested(r.timestamp, pointer, bs); if (bytes(r.chain_id).length != 0) { pointer += ProtoBufRuntime._encode_key( 6, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_string(r.chain_id, pointer, bs); } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_enum(TYPES_PROTO_GLOBAL_ENUMS.encode_SignedMsgType(r.typ)); e += 1 + 8; e += 1 + 8; e += 1 + ProtoBufRuntime._sz_lendelim(CanonicalBlockID._estimate(r.block_id)); e += 1 + ProtoBufRuntime._sz_lendelim(Timestamp._estimate(r.timestamp)); e += 1 + ProtoBufRuntime._sz_lendelim(bytes(r.chain_id).length); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (uint(r.typ) != 0) { return false; } if (r.height != 0) { return false; } if (r.round != 0) { return false; } if (bytes(r.chain_id).length != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.typ = input.typ; output.height = input.height; output.round = input.round; CanonicalBlockID.store(input.block_id, output.block_id); Timestamp.store(input.timestamp, output.timestamp); output.chain_id = input.chain_id; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library CanonicalVote library Height { //struct definition struct Data { uint64 revision_number; uint64 revision_height; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[3] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_revision_number(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_revision_height(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_revision_number( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (uint64 x, uint256 sz) = ProtoBufRuntime._decode_uint64(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.revision_number = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_revision_height( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (uint64 x, uint256 sz) = ProtoBufRuntime._decode_uint64(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.revision_height = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; if (r.revision_number != 0) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_uint64(r.revision_number, pointer, bs); } if (r.revision_height != 0) { pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_uint64(r.revision_height, pointer, bs); } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_uint64(r.revision_number); e += 1 + ProtoBufRuntime._sz_uint64(r.revision_height); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (r.revision_number != 0) { return false; } if (r.revision_height != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.revision_number = input.revision_number; output.revision_height = input.revision_height; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library Height library TYPES_PROTO_GLOBAL_ENUMS { //enum definition // Solidity enum definitions enum BlockIDFlag { BLOCK_ID_FLAG_UNKNOWN, BLOCK_ID_FLAG_ABSENT, BLOCK_ID_FLAG_COMMIT, BLOCK_ID_FLAG_NIL } // Solidity enum encoder function encode_BlockIDFlag(BlockIDFlag x) internal pure returns (int32) { if (x == BlockIDFlag.BLOCK_ID_FLAG_UNKNOWN) { return 0; } if (x == BlockIDFlag.BLOCK_ID_FLAG_ABSENT) { return 1; } if (x == BlockIDFlag.BLOCK_ID_FLAG_COMMIT) { return 2; } if (x == BlockIDFlag.BLOCK_ID_FLAG_NIL) { return 3; } revert(); } // Solidity enum decoder function decode_BlockIDFlag(int64 x) internal pure returns (BlockIDFlag) { if (x == 0) { return BlockIDFlag.BLOCK_ID_FLAG_UNKNOWN; } if (x == 1) { return BlockIDFlag.BLOCK_ID_FLAG_ABSENT; } if (x == 2) { return BlockIDFlag.BLOCK_ID_FLAG_COMMIT; } if (x == 3) { return BlockIDFlag.BLOCK_ID_FLAG_NIL; } revert(); } // Solidity enum definitions enum SignedMsgType { SIGNED_MSG_TYPE_UNKNOWN, SIGNED_MSG_TYPE_PREVOTE, SIGNED_MSG_TYPE_PRECOMMIT, SIGNED_MSG_TYPE_PROPOSAL } // Solidity enum encoder function encode_SignedMsgType(SignedMsgType x) internal pure returns (int32) { if (x == SignedMsgType.SIGNED_MSG_TYPE_UNKNOWN) { return 0; } if (x == SignedMsgType.SIGNED_MSG_TYPE_PREVOTE) { return 1; } if (x == SignedMsgType.SIGNED_MSG_TYPE_PRECOMMIT) { return 2; } if (x == SignedMsgType.SIGNED_MSG_TYPE_PROPOSAL) { return 32; } revert(); } // Solidity enum decoder function decode_SignedMsgType(int64 x) internal pure returns (SignedMsgType) { if (x == 0) { return SignedMsgType.SIGNED_MSG_TYPE_UNKNOWN; } if (x == 1) { return SignedMsgType.SIGNED_MSG_TYPE_PREVOTE; } if (x == 2) { return SignedMsgType.SIGNED_MSG_TYPE_PRECOMMIT; } if (x == 32) { return SignedMsgType.SIGNED_MSG_TYPE_PROPOSAL; } revert(); } } //library TYPES_PROTO_GLOBAL_ENUMS
The decoder for reading a field p The offset of bytes array to start decode bs The bytes array to be decoded r The in-memory struct counters The counters for repeated fields return The number of bytes decoded/ if `r` is NULL, then only counting the number of fields./
function _read_height( uint256 p, bytes memory bs, Data memory r, uint[7] memory counters ) internal pure returns (uint) { (int64 x, uint256 sz) = ProtoBufRuntime._decode_sfixed64(p, bs); if (isNil(r)) { counters[2] += 1; r.height = x; if (counters[2] > 0) counters[2] -= 1; } return sz; }
2,568,590
./full_match/80001/0x80bd74f03075f875F4bee9f201ac884555Eb9B7D/sources/InfinityUnits.sol
uint256 tokenId = _tokenIdCounter.current();existingURIs[_tokenUri] = 1;
function safeBatchMint( address to, uint256[] memory amounts, uint256[] memory ids, string[] memory _tokenUris ) external /*onlyOwner*/ { _mintBatch(to, ids, amounts, ''); for (uint i = 0; i < ids.length; i++) { if (!unitIds[ids[i]]) _setURI(ids[i], _tokenUris[i]); }
5,635,575
// SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import '@openzeppelin/contracts/access/Ownable.sol'; import "@openzeppelin/contracts/utils/Counters.sol"; import "@chainlink/contracts/src/v0.8/VRFConsumerBase.sol"; /* * @title Contract for Pixelvault list randomizations using Chainlink VRF * * @author Niftydude */ contract ListRandomizer is VRFConsumerBase, Ownable { using Counters for Counters.Counter; Counters.Counter private counter; bytes32 internal keyHash; uint256 internal fee; mapping(uint256 => Randomization) public randomizations; struct Randomization { uint256 listLength; string description; uint256 randomNumber; bool isFulfilled; string entryListIpfsHash; } constructor( address _vrfCoordinator, address _linkToken, bytes32 _keyHash, uint256 _fee ) VRFConsumerBase(_vrfCoordinator, _linkToken) { keyHash = _keyHash; fee = _fee; } /** * @notice initiate a new randomization * * @param _listLength the number of entries in the list * @param _entryListIpfsHash ipfs hash pointing to the list of entries * */ function startRandomization( uint256 _listLength, string memory _entryListIpfsHash, string memory _description ) external onlyOwner returns (bytes32 requestId) { require(counter.current() == 0 || randomizations[counter.current()-1].isFulfilled, "Previous randomization not fulfilled"); require( LINK.balanceOf(address(this)) >= fee, "Not enough LINK" ); Randomization storage d = randomizations[counter.current()]; d.listLength = _listLength; d.entryListIpfsHash = _entryListIpfsHash; d.description = _description; counter.increment(); return requestRandomness(keyHash, fee); } /** * @notice return randomized list for a given randomization * * @param _id the randomization id to return the list for */ function getRandomList(uint256 _id) external view returns (uint256[] memory) { require(randomizations[_id].isFulfilled, "Randomization not fulfilled yet"); uint256[] memory arr = new uint256[](randomizations[_id].listLength); for (uint256 i = 0; i < randomizations[_id].listLength; i++) { uint256 j = (uint256(keccak256(abi.encode(randomizations[_id].randomNumber, i))) % (i + 1)); arr[i] = arr[j]; arr[j] = i+1; } return arr; } function withdrawLink() external onlyOwner { LINK.transfer(owner(), LINK.balanceOf(address(this))); } /** * Callback function used by VRF Coordinator */ function fulfillRandomness(bytes32, uint256 randomness) internal override { randomizations[counter.current()-1].randomNumber = randomness; randomizations[counter.current()-1].isFulfilled = true; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) 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() { _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() { 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 { _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 { require(newOwner != address(0), "Ownable: new owner is the zero address"); _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); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) pragma solidity ^0.8.0; /** * @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; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./interfaces/LinkTokenInterface.sol"; import "./VRFRequestIDBase.sol"; /** **************************************************************************** * @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. * ***************************************************************************** * @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 constuctor(<other arguments>, address _vrfCoordinator, address _link) * @dev VRFConsumerBase(_vrfCoordinator, _link) 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), and have told you the minimum LINK * @dev price for VRF service. Make sure your contract has sufficient LINK, and * @dev call requestRandomness(keyHash, fee, seed), where seed is the input you * @dev want to generate randomness from. * * @dev Once the VRFCoordinator has received and validated the oracle's response * @dev to your request, it will call your contract's fulfillRandomness method. * * @dev The randomness argument to fulfillRandomness is the actual random value * @dev generated from your seed. * * @dev The requestId argument is generated from the keyHash and the seed by * @dev makeRequestId(keyHash, seed). If your contract could have concurrent * @dev requests open, you can use the requestId to track which seed is * @dev associated with which randomness. See VRFRequestIDBase.sol for more * @dev details. (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. (Which is critical to making unpredictable randomness! See the * @dev next section.) * * ***************************************************************************** * @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 ultimate input to the VRF is mixed with the block hash of the * @dev block in which the request is made, user-provided seeds have no impact * @dev on its economic security properties. They are only included for API * @dev compatability with previous versions of this contract. * * @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. */ abstract contract VRFConsumerBase is VRFRequestIDBase { /** * @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 VRFConsumerBase 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 randomness the VRF output */ function fulfillRandomness(bytes32 requestId, uint256 randomness) internal virtual; /** * @dev In order to keep backwards compatibility we have kept the user * seed field around. We remove the use of it because given that the blockhash * enters later, it overrides whatever randomness the used seed provides. * Given that it adds no security, and can easily lead to misunderstandings, * we have removed it from usage and can now provide a simpler API. */ uint256 private constant USER_SEED_PLACEHOLDER = 0; /** * @notice requestRandomness initiates a request for VRF output given _seed * * @dev The fulfillRandomness method receives the output, once it's provided * @dev by the Oracle, and verified by the vrfCoordinator. * * @dev The _keyHash must already be registered with the VRFCoordinator, and * @dev the _fee must exceed the fee specified during registration of the * @dev _keyHash. * * @dev The _seed parameter is vestigial, and is kept only for API * @dev compatibility with older versions. It can't *hurt* to mix in some of * @dev your own randomness, here, but it's not necessary because the VRF * @dev oracle will mix the hash of the block containing your request into the * @dev VRF seed it ultimately uses. * * @param _keyHash ID of public key against which randomness is generated * @param _fee The amount of LINK to send with the request * * @return requestId unique ID for this request * * @dev The returned requestId can be used to distinguish responses to * @dev concurrent requests. It is passed as the first argument to * @dev fulfillRandomness. */ function requestRandomness(bytes32 _keyHash, uint256 _fee) internal returns (bytes32 requestId) { LINK.transferAndCall(vrfCoordinator, _fee, abi.encode(_keyHash, USER_SEED_PLACEHOLDER)); // This is the seed passed to VRFCoordinator. The oracle will mix this with // the hash of the block containing this request to obtain the seed/input // which is finally passed to the VRF cryptographic machinery. uint256 vRFSeed = makeVRFInputSeed(_keyHash, USER_SEED_PLACEHOLDER, address(this), nonces[_keyHash]); // nonces[_keyHash] must stay in sync with // VRFCoordinator.nonces[_keyHash][this], which was incremented by the above // successful LINK.transferAndCall (in VRFCoordinator.randomnessRequest). // This provides protection against the user repeating their input seed, // which would result in a predictable/duplicate output, if multiple such // requests appeared in the same block. nonces[_keyHash] = nonces[_keyHash] + 1; return makeRequestId(_keyHash, vRFSeed); } LinkTokenInterface internal immutable LINK; address private immutable vrfCoordinator; // Nonces for each VRF key from which randomness has been requested. // // Must stay in sync with VRFCoordinator[_keyHash][this] mapping(bytes32 => uint256) /* keyHash */ /* nonce */ private nonces; /** * @param _vrfCoordinator address of VRFCoordinator contract * @param _link address of LINK token contract * * @dev https://docs.chain.link/docs/link-token-contracts */ constructor(address _vrfCoordinator, address _link) { vrfCoordinator = _vrfCoordinator; LINK = LinkTokenInterface(_link); } // rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF // proof. rawFulfillRandomness then calls fulfillRandomness, after validating // the origin of the call function rawFulfillRandomness(bytes32 requestId, uint256 randomness) external { require(msg.sender == vrfCoordinator, "Only VRFCoordinator can fulfill"); fulfillRandomness(requestId, randomness); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (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) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface LinkTokenInterface { function allowance(address owner, address spender) external view returns (uint256 remaining); function approve(address spender, uint256 value) external returns (bool success); function balanceOf(address owner) external view returns (uint256 balance); function decimals() external view returns (uint8 decimalPlaces); function decreaseApproval(address spender, uint256 addedValue) external returns (bool success); function increaseApproval(address spender, uint256 subtractedValue) external; function name() external view returns (string memory tokenName); function symbol() external view returns (string memory tokenSymbol); function totalSupply() external view returns (uint256 totalTokensIssued); function transfer(address to, uint256 value) external returns (bool success); function transferAndCall( address to, uint256 value, bytes calldata data ) external returns (bool success); function transferFrom( address from, address to, uint256 value ) external returns (bool success); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract VRFRequestIDBase { /** * @notice returns the seed which is actually input to the VRF coordinator * * @dev To prevent repetition of VRF output due to repetition of the * @dev user-supplied seed, that seed is combined in a hash with the * @dev user-specific nonce, and the address of the consuming contract. The * @dev risk of repetition is mostly mitigated by inclusion of a blockhash in * @dev the final seed, but the nonce does protect against repetition in * @dev requests which are included in a single block. * * @param _userSeed VRF seed input provided by user * @param _requester Address of the requesting contract * @param _nonce User-specific nonce at the time of the request */ function makeVRFInputSeed( bytes32 _keyHash, uint256 _userSeed, address _requester, uint256 _nonce ) internal pure returns (uint256) { return uint256(keccak256(abi.encode(_keyHash, _userSeed, _requester, _nonce))); } /** * @notice Returns the id for this request * @param _keyHash The serviceAgreement ID to be used for this request * @param _vRFInputSeed The seed to be passed directly to the VRF * @return The id for this request * * @dev Note that _vRFInputSeed is not the seed passed by the consuming * @dev contract, but the one generated by makeVRFInputSeed */ function makeRequestId(bytes32 _keyHash, uint256 _vRFInputSeed) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_keyHash, _vRFInputSeed)); } }
initiate a new randomization _listLength the number of entries in the list _entryListIpfsHash ipfs hash pointing to the list of entries/
function startRandomization( uint256 _listLength, string memory _entryListIpfsHash, string memory _description ) external onlyOwner returns (bytes32 requestId) { require(counter.current() == 0 || randomizations[counter.current()-1].isFulfilled, "Previous randomization not fulfilled"); require( LINK.balanceOf(address(this)) >= fee, "Not enough LINK" ); Randomization storage d = randomizations[counter.current()]; d.listLength = _listLength; d.entryListIpfsHash = _entryListIpfsHash; d.description = _description; counter.increment(); return requestRandomness(keyHash, fee); }
71,355
pragma solidity 0.4.20; 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; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); 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); event Transfer(address indexed from, address indexed to, uint256 value); event Burn(address indexed burner, uint256 value); } // ---------------------------------------------------------------------------- // VIOLET ERC20 Standard Token // ---------------------------------------------------------------------------- contract VLTToken is ERC20Interface { using SafeMath for uint256; address public owner = msg.sender; bytes32 public symbol; bytes32 public name; uint8 public decimals; uint256 public _totalSupply; mapping(address => uint256) internal balances; mapping(address => mapping (address => uint256)) internal allowed; modifier onlyOwner() { require(msg.sender == owner); _; } // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function VLTToken() public { symbol = "VAI"; name = "VIOLET"; decimals = 18; _totalSupply = 250000000 * 10**uint256(decimals); balances[owner] = _totalSupply; Transfer(address(0), owner, _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 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) { // allow sending 0 tokens if (_value == 0) { Transfer(msg.sender, _to, _value); // Follow the spec to louch the event when transfer 0 return; } 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) { 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) { // allow sending 0 tokens if (_value == 0) { Transfer(_from, _to, _value); // Follow the spec to louch the event when transfer 0 return; } 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, uint _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, uint _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; } /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { require(_value <= balances[msg.sender]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure address burner = msg.sender; balances[burner] = balances[burner].sub(_value); _totalSupply = _totalSupply.sub(_value); Burn(burner, _value); Transfer(burner, address(0), _value); } /** * 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) { require(_value <= balances[_from]); // Check if the targeted balance is enough require(_value <= allowed[_from][msg.sender]); // Check allowed allowance balances[_from] = balances[_from].sub(_value); // Subtract from the targeted balance allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); // Subtract from the sender's allowance _totalSupply = _totalSupply.sub(_value); // Update totalSupply Burn(_from, _value); Transfer(_from, address(0), _value); return true; } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } } contract ERC20Basic { uint256 public totalSupply; 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); } 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); } 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; } } /** * @title ViolaCrowdsale * @dev ViolaCrowdsale reserves token from supply when eth is received * funds will be forwarded after the end of crowdsale. Tokens will be claimable * within 7 days after crowdsale ends. */ contract ViolaCrowdsale is Ownable { using SafeMath for uint256; enum State { Deployed, PendingStart, Active, Paused, Ended, Completed } //Status of contract State public status = State.Deployed; // The token being sold VLTToken public violaToken; //For keeping track of whitelist address. cap >0 = whitelisted mapping(address=>uint) public maxBuyCap; //For checking if address passed KYC mapping(address => bool)public addressKYC; //Total wei sum an address has invested mapping(address=>uint) public investedSum; //Total violaToken an address is allocated mapping(address=>uint) public tokensAllocated; //Total violaToken an address purchased externally is allocated mapping(address=>uint) public externalTokensAllocated; //Total bonus violaToken an address is entitled after vesting mapping(address=>uint) public bonusTokensAllocated; //Total bonus violaToken an address purchased externally is entitled after vesting mapping(address=>uint) public externalBonusTokensAllocated; //Store addresses that has registered for crowdsale before (pushed via setWhitelist) //Does not mean whitelisted as it can be revoked. Just to track address for loop address[] public registeredAddress; //Total amount not approved for withdrawal uint256 public totalApprovedAmount = 0; //Start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; uint256 public bonusVestingPeriod = 60 days; /** * Note all values are calculated in wei(uint256) including token amount * 1 ether = 1000000000000000000 wei * 1 viola = 1000000000000000000 vi lawei */ //Address where funds are collected address public wallet; //Min amount investor can purchase uint256 public minWeiToPurchase; // how many token units *in wei* a buyer gets *per wei* uint256 public rate; //Extra bonus token to give *in percentage* uint public bonusTokenRateLevelOne = 20; uint public bonusTokenRateLevelTwo = 15; uint public bonusTokenRateLevelThree = 10; uint public bonusTokenRateLevelFour = 0; //Total amount of tokens allocated for crowdsale uint256 public totalTokensAllocated; //Total amount of tokens reserved from external sources //Sub set of totalTokensAllocated ( totalTokensAllocated - totalReservedTokenAllocated = total tokens allocated for purchases using ether ) uint256 public totalReservedTokenAllocated; //Numbers of token left above 0 to still be considered sold uint256 public leftoverTokensBuffer; /** * event for front end logging */ event TokenPurchase(address indexed purchaser, uint256 value, uint256 amount, uint256 bonusAmount); event ExternalTokenPurchase(address indexed purchaser, uint256 amount, uint256 bonusAmount); event ExternalPurchaseRefunded(address indexed purchaser, uint256 amount, uint256 bonusAmount); event TokenDistributed(address indexed tokenReceiver, uint256 tokenAmount); event BonusTokenDistributed(address indexed tokenReceiver, uint256 tokenAmount); event TopupTokenAllocated(address indexed tokenReceiver, uint256 amount, uint256 bonusAmount); event CrowdsalePending(); event CrowdsaleStarted(); event CrowdsaleEnded(); event BonusRateChanged(); event Refunded(address indexed beneficiary, uint256 weiAmount); //Set inital arguments of the crowdsale function initialiseCrowdsale (uint256 _startTime, uint256 _rate, address _tokenAddress, address _wallet) onlyOwner external { require(status == State.Deployed); require(_startTime >= now); require(_rate > 0); require(address(_tokenAddress) != address(0)); require(_wallet != address(0)); startTime = _startTime; endTime = _startTime + 30 days; rate = _rate; wallet = _wallet; violaToken = VLTToken(_tokenAddress); status = State.PendingStart; CrowdsalePending(); } /** * Crowdsale state functions * To track state of current crowdsale */ // To be called by Ethereum alarm clock or anyone //Can only be called successfully when time is valid function startCrowdsale() external { require(withinPeriod()); require(violaToken != address(0)); require(getTokensLeft() > 0); require(status == State.PendingStart); status = State.Active; CrowdsaleStarted(); } //To be called by owner or contract //Ends the crowdsale when tokens are sold out function endCrowdsale() public { if (!tokensHasSoldOut()) { require(msg.sender == owner); } require(status == State.Active); bonusVestingPeriod = now + 60 days; status = State.Ended; CrowdsaleEnded(); } //Emergency pause function pauseCrowdsale() onlyOwner external { require(status == State.Active); status = State.Paused; } //Resume paused crowdsale function unpauseCrowdsale() onlyOwner external { require(status == State.Paused); status = State.Active; } function completeCrowdsale() onlyOwner external { require(hasEnded()); require(violaToken.allowance(owner, this) == 0); status = State.Completed; _forwardFunds(); assert(this.balance == 0); } function burnExtraTokens() onlyOwner external { require(hasEnded()); uint256 extraTokensToBurn = violaToken.allowance(owner, this); violaToken.burnFrom(owner, extraTokensToBurn); assert(violaToken.allowance(owner, this) == 0); } // send ether to the fund collection wallet function _forwardFunds() internal { wallet.transfer(this.balance); } function partialForwardFunds(uint _amountToTransfer) onlyOwner external { require(status == State.Ended); require(_amountToTransfer < totalApprovedAmount); totalApprovedAmount = totalApprovedAmount.sub(_amountToTransfer); wallet.transfer(_amountToTransfer); } /** * Setter functions for crowdsale parameters * Only owner can set values */ function setLeftoverTokensBuffer(uint256 _tokenBuffer) onlyOwner external { require(_tokenBuffer > 0); require(getTokensLeft() >= _tokenBuffer); leftoverTokensBuffer = _tokenBuffer; } //Set the ether to token rate function setRate(uint _rate) onlyOwner external { require(_rate > 0); rate = _rate; } function setBonusTokenRateLevelOne(uint _rate) onlyOwner external { //require(_rate > 0); bonusTokenRateLevelOne = _rate; BonusRateChanged(); } function setBonusTokenRateLevelTwo(uint _rate) onlyOwner external { //require(_rate > 0); bonusTokenRateLevelTwo = _rate; BonusRateChanged(); } function setBonusTokenRateLevelThree(uint _rate) onlyOwner external { //require(_rate > 0); bonusTokenRateLevelThree = _rate; BonusRateChanged(); } function setBonusTokenRateLevelFour(uint _rate) onlyOwner external { //require(_rate > 0); bonusTokenRateLevelFour = _rate; BonusRateChanged(); } function setMinWeiToPurchase(uint _minWeiToPurchase) onlyOwner external { minWeiToPurchase = _minWeiToPurchase; } /** * Whitelisting and KYC functions * Whitelisted address can buy tokens, KYC successful purchaser can claim token. Refund if fail KYC */ //Set the amount of wei an address can purchase up to //@dev Value of 0 = not whitelisted //@dev cap is in *18 decimals* ( 1 token = 1*10^18) function setWhitelistAddress( address _investor, uint _cap ) onlyOwner external { require(_cap > 0); require(_investor != address(0)); maxBuyCap[_investor] = _cap; registeredAddress.push(_investor); //add event } //Remove the address from whitelist function removeWhitelistAddress(address _investor) onlyOwner external { require(_investor != address(0)); maxBuyCap[_investor] = 0; uint256 weiAmount = investedSum[_investor]; if (weiAmount > 0) { _refund(_investor); } } //Flag address as KYC approved. Address is now approved to claim tokens function approveKYC(address _kycAddress) onlyOwner external { require(_kycAddress != address(0)); addressKYC[_kycAddress] = true; uint256 weiAmount = investedSum[_kycAddress]; totalApprovedAmount = totalApprovedAmount.add(weiAmount); } //Set KYC status as failed. Refund any eth back to address function revokeKYC(address _kycAddress) onlyOwner external { require(_kycAddress != address(0)); addressKYC[_kycAddress] = false; uint256 weiAmount = investedSum[_kycAddress]; totalApprovedAmount = totalApprovedAmount.sub(weiAmount); if (weiAmount > 0) { _refund(_kycAddress); } } /** * Getter functions for crowdsale parameters * Does not use gas */ //Checks if token has been sold out function tokensHasSoldOut() view internal returns (bool) { if (getTokensLeft() <= leftoverTokensBuffer) { return true; } else { return false; } } // @return true if the transaction can buy tokens function withinPeriod() public view returns (bool) { return now >= startTime && now <= endTime; } // @return true if crowdsale event has ended function hasEnded() public view returns (bool) { if (status == State.Ended) { return true; } return now > endTime; } function getTokensLeft() public view returns (uint) { return violaToken.allowance(owner, this).sub(totalTokensAllocated); } function transferTokens (address receiver, uint tokenAmount) internal { require(violaToken.transferFrom(owner, receiver, tokenAmount)); } function getTimeBasedBonusRate() public view returns(uint) { bool bonusDuration1 = now >= startTime && now <= (startTime + 1 days); //First 24hr bool bonusDuration2 = now > (startTime + 1 days) && now <= (startTime + 3 days);//Next 48 hr bool bonusDuration3 = now > (startTime + 3 days) && now <= (startTime + 10 days);//4th to 10th day bool bonusDuration4 = now > (startTime + 10 days) && now <= endTime;//11th day onwards if (bonusDuration1) { return bonusTokenRateLevelOne; } else if (bonusDuration2) { return bonusTokenRateLevelTwo; } else if (bonusDuration3) { return bonusTokenRateLevelThree; } else if (bonusDuration4) { return bonusTokenRateLevelFour; } else { return 0; } } function getTotalTokensByAddress(address _investor) public view returns(uint) { return getTotalNormalTokensByAddress(_investor).add(getTotalBonusTokensByAddress(_investor)); } function getTotalNormalTokensByAddress(address _investor) public view returns(uint) { return tokensAllocated[_investor].add(externalTokensAllocated[_investor]); } function getTotalBonusTokensByAddress(address _investor) public view returns(uint) { return bonusTokensAllocated[_investor].add(externalBonusTokensAllocated[_investor]); } function _clearTotalNormalTokensByAddress(address _investor) internal { tokensAllocated[_investor] = 0; externalTokensAllocated[_investor] = 0; } function _clearTotalBonusTokensByAddress(address _investor) internal { bonusTokensAllocated[_investor] = 0; externalBonusTokensAllocated[_investor] = 0; } /** * Functions to handle buy tokens * Fallback function as entry point for eth */ // Called when ether is sent to contract function () external payable { buyTokens(msg.sender); } //Used to buy tokens function buyTokens(address investor) internal { require(status == State.Active); require(msg.value >= minWeiToPurchase); uint weiAmount = msg.value; checkCapAndRecord(investor,weiAmount); allocateToken(investor,weiAmount); } //Internal call to check max user cap function checkCapAndRecord(address investor, uint weiAmount) internal { uint remaindingCap = maxBuyCap[investor]; require(remaindingCap >= weiAmount); maxBuyCap[investor] = remaindingCap.sub(weiAmount); investedSum[investor] = investedSum[investor].add(weiAmount); } //Internal call to allocated tokens purchased function allocateToken(address investor, uint weiAmount) internal { // calculate token amount to be created uint tokens = weiAmount.mul(rate); uint bonusTokens = tokens.mul(getTimeBasedBonusRate()).div(100); uint tokensToAllocate = tokens.add(bonusTokens); require(getTokensLeft() >= tokensToAllocate); totalTokensAllocated = totalTokensAllocated.add(tokensToAllocate); tokensAllocated[investor] = tokensAllocated[investor].add(tokens); bonusTokensAllocated[investor] = bonusTokensAllocated[investor].add(bonusTokens); if (tokensHasSoldOut()) { endCrowdsale(); } TokenPurchase(investor, weiAmount, tokens, bonusTokens); } /** * Functions for refunds & claim tokens * */ //Refund users in case of unsuccessful crowdsale function _refund(address _investor) internal { uint256 investedAmt = investedSum[_investor]; require(investedAmt > 0); uint totalInvestorTokens = tokensAllocated[_investor].add(bonusTokensAllocated[_investor]); if (status == State.Active) { //Refunded tokens go back to sale pool totalTokensAllocated = totalTokensAllocated.sub(totalInvestorTokens); } _clearAddressFromCrowdsale(_investor); _investor.transfer(investedAmt); Refunded(_investor, investedAmt); } //Partial refund users function refundPartial(address _investor, uint _refundAmt, uint _tokenAmt, uint _bonusTokenAmt) onlyOwner external { uint investedAmt = investedSum[_investor]; require(investedAmt > _refundAmt); require(tokensAllocated[_investor] > _tokenAmt); require(bonusTokensAllocated[_investor] > _bonusTokenAmt); investedSum[_investor] = investedSum[_investor].sub(_refundAmt); tokensAllocated[_investor] = tokensAllocated[_investor].sub(_tokenAmt); bonusTokensAllocated[_investor] = bonusTokensAllocated[_investor].sub(_bonusTokenAmt); uint totalRefundTokens = _tokenAmt.add(_bonusTokenAmt); if (status == State.Active) { //Refunded tokens go back to sale pool totalTokensAllocated = totalTokensAllocated.sub(totalRefundTokens); } _investor.transfer(_refundAmt); Refunded(_investor, _refundAmt); } //Used by investor to claim token function claimTokens() external { require(hasEnded()); require(addressKYC[msg.sender]); address tokenReceiver = msg.sender; uint tokensToClaim = getTotalNormalTokensByAddress(tokenReceiver); require(tokensToClaim > 0); _clearTotalNormalTokensByAddress(tokenReceiver); violaToken.transferFrom(owner, tokenReceiver, tokensToClaim); TokenDistributed(tokenReceiver, tokensToClaim); } //Used by investor to claim bonus token function claimBonusTokens() external { require(hasEnded()); require(now >= bonusVestingPeriod); require(addressKYC[msg.sender]); address tokenReceiver = msg.sender; uint tokensToClaim = getTotalBonusTokensByAddress(tokenReceiver); require(tokensToClaim > 0); _clearTotalBonusTokensByAddress(tokenReceiver); violaToken.transferFrom(owner, tokenReceiver, tokensToClaim); BonusTokenDistributed(tokenReceiver, tokensToClaim); } //Used by owner to distribute bonus token function distributeBonusTokens(address _tokenReceiver) onlyOwner external { require(hasEnded()); require(now >= bonusVestingPeriod); address tokenReceiver = _tokenReceiver; uint tokensToClaim = getTotalBonusTokensByAddress(tokenReceiver); require(tokensToClaim > 0); _clearTotalBonusTokensByAddress(tokenReceiver); transferTokens(tokenReceiver, tokensToClaim); BonusTokenDistributed(tokenReceiver,tokensToClaim); } //Used by owner to distribute token function distributeICOTokens(address _tokenReceiver) onlyOwner external { require(hasEnded()); address tokenReceiver = _tokenReceiver; uint tokensToClaim = getTotalNormalTokensByAddress(tokenReceiver); require(tokensToClaim > 0); _clearTotalNormalTokensByAddress(tokenReceiver); transferTokens(tokenReceiver, tokensToClaim); TokenDistributed(tokenReceiver,tokensToClaim); } //For owner to reserve token for presale // function reserveTokens(uint _amount) onlyOwner external { // require(getTokensLeft() >= _amount); // totalTokensAllocated = totalTokensAllocated.add(_amount); // totalReservedTokenAllocated = totalReservedTokenAllocated.add(_amount); // } // //To distribute tokens not allocated by crowdsale contract // function distributePresaleTokens(address _tokenReceiver, uint _amount) onlyOwner external { // require(hasEnded()); // require(_tokenReceiver != address(0)); // require(_amount > 0); // violaToken.transferFrom(owner, _tokenReceiver, _amount); // TokenDistributed(_tokenReceiver,_amount); // } //For external purchases & pre-sale via btc/fiat function externalPurchaseTokens(address _investor, uint _amount, uint _bonusAmount) onlyOwner external { require(_amount > 0); uint256 totalTokensToAllocate = _amount.add(_bonusAmount); require(getTokensLeft() >= totalTokensToAllocate); totalTokensAllocated = totalTokensAllocated.add(totalTokensToAllocate); totalReservedTokenAllocated = totalReservedTokenAllocated.add(totalTokensToAllocate); externalTokensAllocated[_investor] = externalTokensAllocated[_investor].add(_amount); externalBonusTokensAllocated[_investor] = externalBonusTokensAllocated[_investor].add(_bonusAmount); ExternalTokenPurchase(_investor, _amount, _bonusAmount); } function refundAllExternalPurchase(address _investor) onlyOwner external { require(_investor != address(0)); require(externalTokensAllocated[_investor] > 0); uint externalTokens = externalTokensAllocated[_investor]; uint externalBonusTokens = externalBonusTokensAllocated[_investor]; externalTokensAllocated[_investor] = 0; externalBonusTokensAllocated[_investor] = 0; uint totalInvestorTokens = externalTokens.add(externalBonusTokens); totalReservedTokenAllocated = totalReservedTokenAllocated.sub(totalInvestorTokens); totalTokensAllocated = totalTokensAllocated.sub(totalInvestorTokens); ExternalPurchaseRefunded(_investor,externalTokens,externalBonusTokens); } function refundExternalPurchase(address _investor, uint _amountToRefund, uint _bonusAmountToRefund) onlyOwner external { require(_investor != address(0)); require(externalTokensAllocated[_investor] >= _amountToRefund); require(externalBonusTokensAllocated[_investor] >= _bonusAmountToRefund); uint totalTokensToRefund = _amountToRefund.add(_bonusAmountToRefund); externalTokensAllocated[_investor] = externalTokensAllocated[_investor].sub(_amountToRefund); externalBonusTokensAllocated[_investor] = externalBonusTokensAllocated[_investor].sub(_bonusAmountToRefund); totalReservedTokenAllocated = totalReservedTokenAllocated.sub(totalTokensToRefund); totalTokensAllocated = totalTokensAllocated.sub(totalTokensToRefund); ExternalPurchaseRefunded(_investor,_amountToRefund,_bonusAmountToRefund); } function _clearAddressFromCrowdsale(address _investor) internal { tokensAllocated[_investor] = 0; bonusTokensAllocated[_investor] = 0; investedSum[_investor] = 0; maxBuyCap[_investor] = 0; } function allocateTopupToken(address _investor, uint _amount, uint _bonusAmount) onlyOwner external { require(hasEnded()); require(_amount > 0); uint256 tokensToAllocate = _amount.add(_bonusAmount); require(getTokensLeft() >= tokensToAllocate); totalTokensAllocated = totalTokensAllocated.add(_amount); tokensAllocated[_investor] = tokensAllocated[_investor].add(_amount); bonusTokensAllocated[_investor] = bonusTokensAllocated[_investor].add(_bonusAmount); TopupTokenAllocated(_investor, _amount, _bonusAmount); } //For cases where token are mistakenly sent / airdrops function emergencyERC20Drain( ERC20 token, uint amount ) external onlyOwner { require(status == State.Completed); token.transfer(owner,amount); } }
Internal call to check max user cap
function checkCapAndRecord(address investor, uint weiAmount) internal { uint remaindingCap = maxBuyCap[investor]; require(remaindingCap >= weiAmount); maxBuyCap[investor] = remaindingCap.sub(weiAmount); investedSum[investor] = investedSum[investor].add(weiAmount); }
5,343,247
pragma solidity ^0.4.24; /////設定管理者///// contract owned { address public owner; function owned() { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner { owner = newOwner; } } 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 game is owned{ //初始設定 address public tokenAddress = 0x340e85491c5F581360811d0cE5CC7476c72900Ba; mapping (address => uint) readyTime; uint public amount = 1000*10**18 ; //*100為10^2,幣為兩位小數 uint public cooldown = 300; //冷卻時間(秒) mapping (address => uint8) record; //管理權限 function set_amount(uint new_amount)onlyOwner{ amount = new_amount*10**18; } function set_address(address new_address)onlyOwner{ tokenAddress = new_address; } function set_cooldown(uint new_cooldown)onlyOwner{ cooldown = new_cooldown; } function withdraw(uint _amount)onlyOwner{ require(ERC20Basic(tokenAddress).transfer(owner, _amount*10**18)); } //來猜拳!!! function (){ play_game(0); } function play_paper(){ play_game(0); } function play_scissors(){ play_game(1); } function play_stone(){ play_game(2); } function play_game(uint8 play) internal{ require(readyTime[msg.sender] < block.timestamp); require(play <= 2); uint8 comp=uint8(uint(keccak256(block.difficulty, block.timestamp))%3); uint8 result = compare(play, comp); record[msg.sender] = result * 9 + play * 3 + comp ; if (result == 2){ //玩家贏 require(ERC20Basic(tokenAddress).transfer(msg.sender, amount)); } else if(result == 1){ //平手 } else if(result == 0) //玩家輸 readyTime[msg.sender] = block.timestamp + cooldown; } function compare(uint8 player,uint computer) internal returns(uint8 result){ // input 0 => 布 1 => 剪刀 2 => 石頭 // output 0 => 輸 1 => 平手 2 => 贏 uint8 _result; if (player==0 && computer==2){ //布贏石頭 (玩家贏) _result = 2; } else if(player==2 && computer==0){ //石頭輸布(玩家輸) _result = 0; } else if(player == computer){ //平手 _result = 1; } else{ if (player > computer){ //玩家贏 (玩家贏) _result = 2; } else{ //玩家輸 _result = 0; } } return _result; } //判斷function function judge(uint8 orig) internal returns(uint8 result, uint8 play, uint8 comp){ uint8 _result = orig/9; uint8 _play = (orig%9)/3; uint8 _comp = orig%3; return(_result, _play, _comp); } function mora(uint8 orig) internal returns(string _mora){ // 0 => 布 1 => 剪刀 2 => 石頭 if (orig == 0){ return "paper"; } else if (orig == 1){ return "scissors"; } else if (orig == 2){ return "stone"; } else { return "error"; } } function win(uint8 _result) internal returns(string result){ // 0 => 輸 1 => 平手 2 => 贏 if (_result == 0){ return "lose!!"; } else if (_result == 1){ return "draw~~"; } else if (_result == 2){ return "win!!!"; } else { return "error"; } } function resolve(uint8 orig) internal returns(string result, string play, string comp){ (uint8 _result, uint8 _play, uint8 _comp) = judge(orig); return(win(_result), mora(_play), mora(_comp)); } //查詢 function view_last_result(address _address) view public returns(string result, string player, string computer){ return resolve(record[_address]); } function self_last_result() view public returns(string result, string player, string computer){ view_last_result(msg.sender); } function view_readyTime(address _address) view public returns(uint _readyTime){ if (block.timestamp >= readyTime[_address]){ return 0 ; } else{ return readyTime[_address] - block.timestamp ; } } function self_readyTime() view public returns(uint _readyTime){ view_readyTime(msg.sender); } }
0 => 輸 1 => 平手 2 => 贏
function win(uint8 _result) internal returns(string result){ if (_result == 0){ return "lose!!"; } else if (_result == 1){ return "draw~~"; } else if (_result == 2){ return "win!!!"; } else { return "error"; } }
2,157,129
/** *Submitted for verification at Etherscan.io on 2021-12-15 */ /** *Submitted for verification at Centurion invest. *Author : Aymen Haddaji */ // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.6.0; /** * ERC20 Interfacs */ abstract contract IERC20 { function totalSupply() virtual public view returns (uint); function balanceOf(address tokenOwner) virtual public view returns (uint); function allowance(address sender, address reciever) virtual public view returns (uint); function transfer(address to, uint tokens) virtual public returns (bool); function approve(address reciever, uint tokens) virtual public returns (bool); function transferFrom(address from, address to, uint tokens) virtual public returns (bool); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } contract SafeMath { function safeAdd(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function safeSub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } } contract CIC_COIN is IERC20, SafeMath { string public name; string public symbol; uint8 public decimals; uint256 public _totalSupply; address public owner; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; constructor() public payable { name = "Centurion Invest Coin"; symbol = "CIC"; decimals = 2; owner = msg.sender; _totalSupply = 2400000000 * 10 ** uint256(decimals); // n decimals balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); } modifier onlyOwner() { require(msg.sender == owner, "No permession"); _; } /** * @dev allowance : Check approved balance */ function allowance(address sender, address reciever) virtual override public view returns (uint remaining) { return allowed[sender][reciever]; } /** * @dev approve : Approve token for spender = reciever */ function approve(address reciever, uint tokens) virtual override public returns (bool success) { require(tokens >= 0, "Invalid value"); allowed[msg.sender][reciever] = tokens; emit Approval(msg.sender, reciever, tokens); return true; } /** * @dev transfer : Transfer token to another etherum address */ function transfer(address to, uint tokens) virtual override public returns (bool success) { require(to != address(0), "Null address"); require(tokens > 0, "Invalid Value"); balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } /** * @dev transferFrom : Transfer token after approval */ function transferFrom(address from, address to, uint tokens) virtual override public returns (bool success) { require(to != address(0), "Null address"); require(from != address(0), "Null address"); require(tokens > 0, "Invalid value"); require(tokens <= balances[from], "Insufficient balance"); require(tokens <= allowed[from][msg.sender], "Insufficient allowance"); balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } /** * @dev totalSupply : Display total supply of token */ function totalSupply() virtual override public view returns (uint) { return _totalSupply; } /** * @dev balanceOf : Displya token balance of given address */ function balanceOf(address tokenOwner) virtual override public view returns (uint balance) { return balances[tokenOwner]; } /** * @dev mint : To increase total supply of tokens */ function mint(uint256 _amount) public onlyOwner returns (bool) { require(_amount >= 0, "Invalid amount"); _totalSupply = safeAdd(_totalSupply, _amount); balances[owner] = safeAdd(balances[owner], _amount); return true; } /** * @dev burn : To decrease total supply of tokens */ function burn(uint256 _amount) public returns (bool) { require(_amount >= 0, "Invalid amount"); require(owner == msg.sender, "UnAuthorized"); require(_amount <= balances[msg.sender], "Insufficient Balance"); _totalSupply = safeSub(_totalSupply, _amount); balances[owner] = safeSub(balances[owner], _amount); emit Transfer(owner, address(0), _amount); return true; } /** *@dev send_bonus : set and send ammount of bonus. * */ function send_bonus(address to, uint bonus) virtual public returns (bool success) { transfer(to, bonus); return true; } /** *@dev send_bonus : set and send ammount of bonus. * */ function send_referral(address to, uint referamt) virtual public returns (bool success) { transfer(to, referamt); return true; } }
send_bonus : set and send ammount of bonus./
function send_referral(address to, uint referamt) virtual public returns (bool success) { transfer(to, referamt); return true; }
8,072,387
// SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; import "./utils/RLPReader.sol"; import "./utils/GsnUtils.sol"; import "./interfaces/IRelayHub.sol"; import "./interfaces/IPenalizer.sol"; /** * @title The Penalizer Implementation * * @notice This Penalizer supports parsing Legacy, Type 1 and Type 2 raw RLP Encoded transactions. */ contract Penalizer is IPenalizer { using ECDSA for bytes32; /// @inheritdoc IPenalizer string public override versionPenalizer = "2.2.3+opengsn.penalizer.ipenalizer"; uint256 internal immutable penalizeBlockDelay; uint256 internal immutable penalizeBlockExpiration; constructor( uint256 _penalizeBlockDelay, uint256 _penalizeBlockExpiration ) { penalizeBlockDelay = _penalizeBlockDelay; penalizeBlockExpiration = _penalizeBlockExpiration; } /// @inheritdoc IPenalizer function getPenalizeBlockDelay() external override view returns (uint256) { return penalizeBlockDelay; } /// @inheritdoc IPenalizer function getPenalizeBlockExpiration() external override view returns (uint256) { return penalizeBlockExpiration; } function isLegacyTransaction(bytes calldata rawTransaction) internal pure returns (bool) { uint8 transactionTypeByte = uint8(rawTransaction[0]); return (transactionTypeByte >= 0xc0 && transactionTypeByte <= 0xfe); } function isTransactionType1(bytes calldata rawTransaction) internal pure returns (bool) { return (uint8(rawTransaction[0]) == 1); } function isTransactionType2(bytes calldata rawTransaction) internal pure returns (bool) { return (uint8(rawTransaction[0]) == 2); } /// @return `true` if raw transaction is of types Legacy, 1 or 2. `false` otherwise. function isTransactionTypeValid(bytes calldata rawTransaction) public pure returns(bool) { return isLegacyTransaction(rawTransaction) || isTransactionType1(rawTransaction) || isTransactionType2(rawTransaction); } /// @return transaction The details that the `Penalizer` needs to decide if the transaction is penalizable. function decodeTransaction(bytes calldata rawTransaction) public pure returns (Transaction memory transaction) { if (isTransactionType1(rawTransaction)) { (transaction.nonce, transaction.gasLimit, transaction.to, transaction.value, transaction.data) = RLPReader.decodeTransactionType1(rawTransaction); } else if (isTransactionType2(rawTransaction)) { (transaction.nonce, transaction.gasLimit, transaction.to, transaction.value, transaction.data) = RLPReader.decodeTransactionType2(rawTransaction); } else { (transaction.nonce, transaction.gasLimit, transaction.to, transaction.value, transaction.data) = RLPReader.decodeLegacyTransaction(rawTransaction); } return transaction; } mapping(bytes32 => uint256) public commits; /// @inheritdoc IPenalizer function commit(bytes32 commitHash) external override { uint256 readyBlockNumber = block.number + penalizeBlockDelay; commits[commitHash] = readyBlockNumber; emit CommitAdded(msg.sender, commitHash, readyBlockNumber); } /// Modifier that verifies there was a `commit` operation before this call that has not expired yet. modifier commitRevealOnly() { bytes32 commitHash = keccak256(abi.encodePacked(keccak256(msg.data), msg.sender)); uint256 readyBlockNumber = commits[commitHash]; delete commits[commitHash]; // msg.sender can only be fake during off-chain view call, allowing Penalizer process to check transactions if(msg.sender != address(type(uint160).max)) { require(readyBlockNumber != 0, "no commit"); require(readyBlockNumber < block.number, "reveal penalize too soon"); require(readyBlockNumber + penalizeBlockExpiration > block.number, "reveal penalize too late"); } _; } /// @inheritdoc IPenalizer function penalizeRepeatedNonce( bytes calldata unsignedTx1, bytes calldata signature1, bytes calldata unsignedTx2, bytes calldata signature2, IRelayHub hub, uint256 randomValue ) public override commitRevealOnly { (randomValue); _penalizeRepeatedNonce(unsignedTx1, signature1, unsignedTx2, signature2, hub); } function _penalizeRepeatedNonce( bytes calldata unsignedTx1, bytes calldata signature1, bytes calldata unsignedTx2, bytes calldata signature2, IRelayHub hub ) private { address addr1 = keccak256(unsignedTx1).recover(signature1); address addr2 = keccak256(unsignedTx2).recover(signature2); require(addr1 == addr2, "Different signer"); require(addr1 != address(0), "ecrecover failed"); Transaction memory decodedTx1 = decodeTransaction(unsignedTx1); Transaction memory decodedTx2 = decodeTransaction(unsignedTx2); // checking that the same nonce is used in both transaction, with both signed by the same address // and the actual data is different // note: we compare the hash of the tx to save gas over iterating both byte arrays require(decodedTx1.nonce == decodedTx2.nonce, "Different nonce"); bytes memory dataToCheck1 = abi.encodePacked(decodedTx1.data, decodedTx1.gasLimit, decodedTx1.to, decodedTx1.value); bytes memory dataToCheck2 = abi.encodePacked(decodedTx2.data, decodedTx2.gasLimit, decodedTx2.to, decodedTx2.value); require(keccak256(dataToCheck1) != keccak256(dataToCheck2), "tx is equal"); penalize(addr1, hub); } /// @inheritdoc IPenalizer function penalizeIllegalTransaction( bytes calldata unsignedTx, bytes calldata signature, IRelayHub hub, uint256 randomValue ) public override commitRevealOnly { (randomValue); _penalizeIllegalTransaction(unsignedTx, signature, hub); } function _penalizeIllegalTransaction( bytes calldata unsignedTx, bytes calldata signature, IRelayHub hub ) private { if (isTransactionTypeValid(unsignedTx)) { Transaction memory decodedTx = decodeTransaction(unsignedTx); if (decodedTx.to == address(hub)) { bytes4 selector = GsnUtils.getMethodSig(decodedTx.data); bool isWrongMethodCall = selector != IRelayHub.relayCall.selector; require( isWrongMethodCall, "Legal relay transaction"); } } address relay = keccak256(unsignedTx).recover(signature); require(relay != address(0), "ecrecover failed"); penalize(relay, hub); } function penalize(address relayWorker, IRelayHub hub) private { hub.penalize(relayWorker, payable(msg.sender)); } }
checking that the same nonce is used in both transaction, with both signed by the same address and the actual data is different note: we compare the hash of the tx to save gas over iterating both byte arrays
function _penalizeRepeatedNonce( bytes calldata unsignedTx1, bytes calldata signature1, bytes calldata unsignedTx2, bytes calldata signature2, IRelayHub hub ) private { address addr1 = keccak256(unsignedTx1).recover(signature1); address addr2 = keccak256(unsignedTx2).recover(signature2); require(addr1 == addr2, "Different signer"); require(addr1 != address(0), "ecrecover failed"); Transaction memory decodedTx1 = decodeTransaction(unsignedTx1); Transaction memory decodedTx2 = decodeTransaction(unsignedTx2); require(decodedTx1.nonce == decodedTx2.nonce, "Different nonce"); bytes memory dataToCheck1 = abi.encodePacked(decodedTx1.data, decodedTx1.gasLimit, decodedTx1.to, decodedTx1.value); bytes memory dataToCheck2 = abi.encodePacked(decodedTx2.data, decodedTx2.gasLimit, decodedTx2.to, decodedTx2.value); require(keccak256(dataToCheck1) != keccak256(dataToCheck2), "tx is equal"); penalize(addr1, hub); }
977,962
./full_match/1/0x66d97FD4DefEcD79904B3D3587dC4f8ed66Cf4Ab/sources/src/LSSVMPairERC20.sol
@inheritdoc LSSVMPair/ Do nothing since we transferred the exact input amount
function _refundTokenToSender(uint256 inputAmount) internal override { }
8,298,009
./partial_match/56/0x5e9d18783B0Bcad3A9CA3c91A76f47A6aEa4B50D/sources/BIO.sol
Transfer `amount` tokens from `src` to `dst` src The address of the source account dst The address of the destination account rawAmount The number of tokens to transfer return Whether or not the transfer succeeded/
function transferFrom(address src, address dst, uint rawAmount) external validLock returns (bool) { address spender = msg.sender; uint96 spenderAllowance = allowances[src][spender]; uint96 amount = safe96(rawAmount, "BIO::approve: amount exceeds 96 bits"); if (spender != src && spenderAllowance != uint96(-1)) { uint96 newAllowance = sub96(spenderAllowance, amount, "XVS::transferFrom: transfer amount exceeds spender allowance"); allowances[src][spender] = newAllowance; emit Approval(src, spender, newAllowance); } _transferTokens(src, dst, amount); return true; }
11,283,497
pragma solidity >=0.4.21 <0.6.0; // It's important to avoid vulnerabilities due to numeric overflow bugs // OpenZeppelin's SafeMath library, when used correctly, protects agains such bugs // More info: https://www.nccgroup.trust/us/about-us/newsroom-and-events/blog/2018/november/smart-contract-insecurity-bad-arithmetic/ import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; contract FlightSuretyData { function registerAirline(address newAirline, address registrator) external; function isRegistered(address airlineAddress) external view returns(bool); function payFunding(address airlineAddress) external payable; function isAirlineOperational (address airlineAddress) external view returns(bool _valid); function operationalAirlinesCount() external view returns(uint); function registerFlight(address airline, string calldata flightNumber, uint flightTime) external; function buyInsurance(address insured, bytes32 flightKey, uint amount) external; function getFlightTime(bytes32 flightKey) public returns(uint flightTime); function getFlight(bytes32 _flightKey) public returns (bytes32 flightKey, address airline, string memory flightNumber, uint flightTime); function insurancesSize (bytes32 flightKey) public returns (uint size); function getInsuranceForIndex(bytes32 flightKey, uint index) external returns (address insured, uint amountPaid, uint balance); function setBalanceForInsurance(bytes32 flightKey, uint index, uint balance) external; function pay(bytes32 flightKey, address insuredClient) external; } /************************************************** */ /* FlightSurety Smart Contract */ /************************************************** */ contract FlightSuretyApp { using SafeMath for uint256; // Allow SafeMath functions to be called for all uint256 types (similar to "prototype" in Javascript) /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ FlightSuretyData flightSuretyData; // Flight status codees uint8 private constant STATUS_CODE_UNKNOWN = 0; uint8 private constant STATUS_CODE_ON_TIME = 10; uint8 private constant STATUS_CODE_LATE_AIRLINE = 20; uint8 private constant STATUS_CODE_LATE_WEATHER = 30; uint8 private constant STATUS_CODE_LATE_TECHNICAL = 40; uint8 private constant STATUS_CODE_LATE_OTHER = 50; bool public isOperational; address private contractOwner; // Account used to deploy contract struct Flight { bool isRegistered; uint8 statusCode; uint256 updatedTimestamp; address airline; } mapping(bytes32 => Flight) private flights; mapping(address => address[]) public votesOnNewRegistration; address[] public airlinesAwaitingVotes; event FlightRegistered(address airline, string flightNumber, uint flightTime); event InsuranceBought(address insured, bytes32 flightKey, uint amount); event OperationalAppStateChanged(bool operational); event AirlinePaidFunding(address airlineAddress); event FlightProcessed(string flight, uint8 statusCode); event FlightKey(bytes32 flightKey); event OracleRegistered(address oracleaddress, bool isRegistered); /********************************************************************************************/ /* FUNCTION MODIFIERS */ /********************************************************************************************/ // Modifiers help avoid duplication of code. They are typically used to validate something // before a function is allowed to be executed. /** * @dev Modifier that requires the "operational" boolean variable to be "true" * This is used on all state changing functions to pause the contract in * the event there is an issue that needs to be fixed */ modifier requireIsOperational() { // Modify to call data contract's status require(isOperational, "Contract is currently not operational"); _; // All modifiers require an "_" which indicates where the function body will be added } /** * @dev Modifier that requires the "ContractOwner" account to be the function caller */ modifier requireContractOwner() { require(msg.sender == contractOwner, "Caller is not contract owner"); _; } modifier registrationPaid() { require(flightSuretyData.isRegistered(msg.sender), "The registration fee has not been paid"); _; } modifier requireFlightExist(bytes32 _flightKey) { (bytes32 flightKey, address airline, string memory flightNumber, uint flightTime) = flightSuretyData.getFlight(_flightKey); require(flightKey == _flightKey, "The flightKey does not exist"); _; } modifier flightNotExpired(bytes32 _flightKey) { (bytes32 flightKey, address airline, string memory flightNumber, uint flightTime) = flightSuretyData.getFlight(_flightKey); // uint minimumTime = block.timestamp + 1000; // require(flightTime > minimumTime , "The flight is too old"); require(flightTime > (block.timestamp + 1000) , "The flight is too old"); _; } modifier checkValueForMaxAmount() { require(msg.value < (1 ether), "Maximum admitted value overstepped"); _; } modifier enoughFund() { require(msg.value > (10 ether), "You must pay minimum 10 ether for funding"); _; } modifier operationalAirline() { bool isOpAirline = flightSuretyData.isAirlineOperational(msg.sender); require(isOpAirline, "The Airline must be operational to perform these actions"); _; } /********************************************************************************************/ /* CONSTRUCTOR */ /********************************************************************************************/ /** * @dev Contract constructor * */ constructor ( address dataContract) public { isOperational = true; contractOwner = msg.sender; flightSuretyData = FlightSuretyData(dataContract); } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ function setOperational(bool operating) external requireContractOwner { isOperational = operating; emit OperationalAppStateChanged(isOperational); } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ function registerAirline (address newAirline) external requireIsOperational operationalAirline registrationPaid returns(bool/* success */, uint256/* votes */) { if(flightSuretyData.operationalAirlinesCount() < 4) { // if less than 4 the caller must be one of the operational airlines require(flightSuretyData.isAirlineOperational(msg.sender), "Only operational Airlines can register new airlines"); flightSuretyData.registerAirline(newAirline, msg.sender); } else { // we need to vote to give permission airlinesAwaitingVotes.push(newAirline); } } function voteAirline(address newAirline) external requireIsOperational // requireIsRegistered the address on which to vote has to be registered first { bool doubleVote = false; for (uint i = 0; i < votesOnNewRegistration[newAirline].length; i++) { if (votesOnNewRegistration[newAirline][i] == msg.sender) { doubleVote = true; break; } } if(!doubleVote) { votesOnNewRegistration[newAirline].push(msg.sender); } // if more than 50% of the airlines voted, the newAirline will be registered. if(votesOnNewRegistration[newAirline].length > flightSuretyData.operationalAirlinesCount().div(2)) { flightSuretyData.registerAirline(newAirline, msg.sender); } } function getAirlinesAwaitingVotes () external view requireIsOperational returns (address[] memory airlines) { airlines = airlinesAwaitingVotes; } function getVotesOnNewRegistration(address newAirline) external view requireIsOperational returns(address[] memory votes) { votes = votesOnNewRegistration[newAirline]; } function getVotesCount(address newAirline) public view returns (uint count) { count = votesOnNewRegistration[newAirline].length; } function payFunding() external // airlineRegistered enoughFund requireIsOperational payable { flightSuretyData.payFunding.value(msg.value)(msg.sender); emit AirlinePaidFunding(msg.sender); } function registerFlight(address airline, string calldata flightNumber, uint flightTime) external requireIsOperational operationalAirline { flightSuretyData.registerFlight(airline, flightNumber, flightTime); emit FlightRegistered(airline, flightNumber, flightTime); } function buyInsurance(bytes32 flightKey) external requireIsOperational requireFlightExist(flightKey) flightNotExpired(flightKey) checkValueForMaxAmount payable { flightSuretyData.buyInsurance(msg.sender, flightKey, msg.value); emit InsuranceBought(msg.sender, flightKey, msg.value); } /** * @dev Called after oracle has updated flight status * */ function processFlightStatus(address airline, string memory flight, uint256 timestamp, uint8 statusCode) internal requireIsOperational { if(statusCode == STATUS_CODE_LATE_AIRLINE) { // find all insurances for that flight bytes32 flightKey = keccak256(abi.encodePacked(airline, flight, timestamp)); emit FlightKey(flightKey); uint insurancesSize = flightSuretyData.insurancesSize(flightKey); // loop through them and multiply the amount with 1.5 for(uint i = 0; i < insurancesSize; i++){ (address insured, uint amountPaid, uint balance) = flightSuretyData.getInsuranceForIndex(flightKey, i); balance = amountPaid.mul(15).div(10); // newBalance = newBalance.div(10); // uint newBalance = (0.15 ether); flightSuretyData.setBalanceForInsurance(flightKey, i, balance); // flightSuretyData.setBalanceForInsurance(flightKey, i, 56789); } // credit their balance with the result } // bytes32 flightKey = keccak256(abi.encodePacked(airline, flight, timestamp)); // flightSuretyData.setBalanceForInsurance(flightKey, 0, 450); emit FlightProcessed(flight, statusCode); } // Generate a request for oracles to fetch flight information function fetchFlightStatus ( address airline, string calldata flight, uint256 timestamp ) external requireIsOperational { uint8 index = getRandomIndex(msg.sender); // Generate a unique key for storing the request // bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp)); bytes32 key = keccak256(abi.encodePacked(airline, flight, timestamp)); oracleResponses[key] = ResponseInfo({ requester: msg.sender, isOpen: true }); emit OracleRequest(index, airline, flight, timestamp); } // region ORACLE MANAGEMENT // Incremented to add pseudo-randomness at various points uint8 private nonce = 0; // Fee to be paid when registering oracle uint256 public constant REGISTRATION_FEE = 1 ether; // Number of oracles that must respond for valid status uint256 private constant MIN_RESPONSES = 3; struct Oracle { bool isRegistered; uint8[3] indexes; } // Track all registered oracles mapping(address => Oracle) private oracles; // Model for responses from oracles struct ResponseInfo { address requester; // Account that requested status bool isOpen; // If open, oracle responses are accepted mapping(uint8 => address[]) responses; // Mapping key is the status code reported // This lets us group responses and identify // the response that majority of the oracles } // Track all oracle responses // Key = hash(index, flight, timestamp) mapping(bytes32 => ResponseInfo) private oracleResponses; // Event fired each time an oracle submits a response event FlightStatusInfo(address airline, string flight, uint256 timestamp, uint8 status); event OracleReport(address airline, string flight, uint256 timestamp, uint8 status); // Event fired when flight status request is submitted // Oracles track this and if they have a matching index // they fetch data and submit a response event OracleRequest(uint8 index, address airline, string flight, uint256 timestamp); event WithdrawRequested(bytes32 flightKey, address insuredCLient ); // Register an oracle with the contract function registerOracle ( ) external payable { // Require registration fee require(msg.value >= REGISTRATION_FEE, "Registration fee is required"); uint8[3] memory indexes = generateIndexes(msg.sender); oracles[msg.sender] = Oracle({ isRegistered: true, indexes: indexes }); emit OracleRegistered(msg.sender, oracles[msg.sender].isRegistered); } function getMyIndexes ( ) public view returns(uint8[3] memory) { require(oracles[msg.sender].isRegistered, "Not registered as an oracle"); return oracles[msg.sender].indexes; } function withdraw(bytes32 flightKey) external requireIsOperational { flightSuretyData.pay(flightKey, msg.sender); emit WithdrawRequested(flightKey, msg.sender); } // Called by oracle when a response is available to an outstanding request // For the response to be accepted, there must be a pending request that is open // and matches one of the three Indexes randomly assigned to the oracle at the // time of registration (i.e. uninvited oracles are not welcome) function submitOracleResponse ( uint8 index, address airline, string calldata flight, uint256 timestamp, uint8 statusCode ) external { require((oracles[msg.sender].indexes[0] == index) || (oracles[msg.sender].indexes[1] == index) || (oracles[msg.sender].indexes[2] == index), "Index does not match oracle request"); // bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp)); bytes32 key = keccak256(abi.encodePacked(airline, flight, timestamp)); require(oracleResponses[key].isOpen, "Flight or timestamp do not match oracle request"); oracleResponses[key].responses[statusCode].push(msg.sender); // Information isn't considered verified until at least MIN_RESPONSES // oracles respond with the *** same *** information emit OracleReport(airline, flight, timestamp, statusCode); if (oracleResponses[key].responses[statusCode].length >= MIN_RESPONSES) { // Handle flight status as appropriate processFlightStatus(airline, flight, timestamp, statusCode); emit FlightStatusInfo(airline, flight, timestamp, statusCode); } } function getFlightKey ( address airline, string memory flight, uint256 timestamp ) internal pure returns(bytes32) { return keccak256(abi.encodePacked(airline, flight, timestamp)); } // Returns array of three non-duplicating integers from 0-9 function generateIndexes ( address account ) internal returns(uint8[3] memory) { uint8[3] memory indexes; indexes[0] = getRandomIndex(account); indexes[1] = indexes[0]; while(indexes[1] == indexes[0]) { indexes[1] = getRandomIndex(account); } indexes[2] = indexes[1]; while((indexes[2] == indexes[0]) || (indexes[2] == indexes[1])) { indexes[2] = getRandomIndex(account); } return indexes; } // Returns array of three non-duplicating integers from 0-9 function getRandomIndex ( address account ) internal returns (uint8) { uint8 maxValue = 10; // Pseudo random number...the incrementing nonce adds variation uint8 random = uint8(uint256(keccak256(abi.encodePacked(blockhash(block.number - nonce++), account))) % maxValue); if (nonce > 250) { nonce = 0; // Can only fetch blockhashes for last 256 blocks so we adapt } return random; } // endregion }
if less than 4 the caller must be one of the operational airlines we need to vote to give permission
function registerAirline (address newAirline) external requireIsOperational operationalAirline registrationPaid returns(bool/* success */, uint256/* votes */) { if(flightSuretyData.operationalAirlinesCount() < 4) { require(flightSuretyData.isAirlineOperational(msg.sender), "Only operational Airlines can register new airlines"); flightSuretyData.registerAirline(newAirline, msg.sender); airlinesAwaitingVotes.push(newAirline); } }
6,350,851
pragma solidity ^0.4.23; 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; require(c / a == b, "Overflow - Multiplication"); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { 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) { require(b <= a, "Underflow - Subtraction"); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "Overflow - Addition"); return c; } } library Contract { using SafeMath for uint; // Modifiers: // // Runs two functions before and after a function - modifier conditions(function () pure first, function () pure last) { first(); _; last(); } bytes32 internal constant EXEC_PERMISSIONS = keccak256('script_exec_permissions'); // Sets up contract execution - reads execution id and sender from storage and // places in memory, creating getters. Calling this function should be the first // action an application does as part of execution, as it sets up memory for // execution. Additionally, application functions in the main file should be // external, so that memory is not touched prior to calling this function. // The 3rd slot allocated will hold a pointer to a storage buffer, which will // be reverted to abstract storage to store data, emit events, and forward // wei on behalf of the application. function authorize(address _script_exec) internal view { // Initialize memory initialize(); // Check that the sender is authorized as a script exec contract for this exec id bytes32 perms = EXEC_PERMISSIONS; bool authorized; assembly { // Place the script exec address at 0, and the exec permissions seed after it mstore(0, _script_exec) mstore(0x20, perms) // Hash the resulting 0x34 bytes, and place back into memory at 0 mstore(0, keccak256(0x0c, 0x34)) // Place the exec id after the hash - mstore(0x20, mload(0x80)) // Hash the previous hash with the execution id, and check the result authorized := sload(keccak256(0, 0x40)) } if (!authorized) revert("Sender is not authorized as a script exec address"); } // Sets up contract execution when initializing an instance of the application // First, reads execution id and sender from storage (execution id should be 0xDEAD), // then places them in memory, creating getters. Calling this function should be the first // action an application does as part of execution, as it sets up memory for // execution. Additionally, application functions in the main file should be // external, so that memory is not touched prior to calling this function. // The 3rd slot allocated will hold a pointer to a storage buffer, which will // be reverted to abstract storage to store data, emit events, and forward // wei on behalf of the application. function initialize() internal view { // No memory should have been allocated yet - expect the free memory pointer // to point to 0x80 - and throw if it does not require(freeMem() == 0x80, "Memory allocated prior to execution"); // Next, set up memory for execution assembly { mstore(0x80, sload(0)) // Execution id, read from storage mstore(0xa0, sload(1)) // Original sender address, read from storage mstore(0xc0, 0) // Pointer to storage buffer mstore(0xe0, 0) // Bytes4 value of the current action requestor being used mstore(0x100, 0) // Enum representing the next type of function to be called (when pushing to buffer) mstore(0x120, 0) // Number of storage slots written to in buffer mstore(0x140, 0) // Number of events pushed to buffer mstore(0x160, 0) // Number of payment destinations pushed to buffer // Update free memory pointer - mstore(0x40, 0x180) } // Ensure that the sender and execution id returned from storage are expected values - assert(execID() != bytes32(0) && sender() != address(0)); } // Calls the passed-in function, performing a memory state check before and after the check // is executed. function checks(function () view _check) conditions(validState, validState) internal view { _check(); } // Calls the passed-in function, performing a memory state check before and after the check // is executed. function checks(function () pure _check) conditions(validState, validState) internal pure { _check(); } // Ensures execution completed successfully, and reverts the created storage buffer // back to the sender. function commit() conditions(validState, none) internal pure { // Check value of storage buffer pointer - should be at least 0x180 bytes32 ptr = buffPtr(); require(ptr >= 0x180, "Invalid buffer pointer"); assembly { // Get the size of the buffer let size := mload(add(0x20, ptr)) mstore(ptr, 0x20) // Place dynamic data offset before buffer // Revert to storage revert(ptr, add(0x40, size)) } } // Helpers: // // Checks to ensure the application was correctly executed - function validState() private pure { if (freeMem() < 0x180) revert('Expected Contract.execute()'); if (buffPtr() != 0 && buffPtr() < 0x180) revert('Invalid buffer pointer'); assert(execID() != bytes32(0) && sender() != address(0)); } // Returns a pointer to the execution storage buffer - function buffPtr() private pure returns (bytes32 ptr) { assembly { ptr := mload(0xc0) } } // Returns the location pointed to by the free memory pointer - function freeMem() private pure returns (bytes32 ptr) { assembly { ptr := mload(0x40) } } // Returns the current storage action function currentAction() private pure returns (bytes4 action) { if (buffPtr() == bytes32(0)) return bytes4(0); assembly { action := mload(0xe0) } } // If the current action is not storing, reverts function isStoring() private pure { if (currentAction() != STORES) revert('Invalid current action - expected STORES'); } // If the current action is not emitting, reverts function isEmitting() private pure { if (currentAction() != EMITS) revert('Invalid current action - expected EMITS'); } // If the current action is not paying, reverts function isPaying() private pure { if (currentAction() != PAYS) revert('Invalid current action - expected PAYS'); } // Initializes a storage buffer in memory - function startBuffer() private pure { assembly { // Get a pointer to free memory, and place at 0xc0 (storage buffer pointer) let ptr := msize() mstore(0xc0, ptr) // Clear bytes at pointer - mstore(ptr, 0) // temp ptr mstore(add(0x20, ptr), 0) // buffer length // Update free memory pointer - mstore(0x40, add(0x40, ptr)) // Set expected next function to 'NONE' - mstore(0x100, 1) } } // Checks whether or not it is valid to create a STORES action request - function validStoreBuff() private pure { // Get pointer to current buffer - if zero, create a new buffer - if (buffPtr() == bytes32(0)) startBuffer(); // Ensure that the current action is not 'storing', and that the buffer has not already // completed a STORES action - if (stored() != 0 || currentAction() == STORES) revert('Duplicate request - stores'); } // Checks whether or not it is valid to create an EMITS action request - function validEmitBuff() private pure { // Get pointer to current buffer - if zero, create a new buffer - if (buffPtr() == bytes32(0)) startBuffer(); // Ensure that the current action is not 'emitting', and that the buffer has not already // completed an EMITS action - if (emitted() != 0 || currentAction() == EMITS) revert('Duplicate request - emits'); } // Checks whether or not it is valid to create a PAYS action request - function validPayBuff() private pure { // Get pointer to current buffer - if zero, create a new buffer - if (buffPtr() == bytes32(0)) startBuffer(); // Ensure that the current action is not 'paying', and that the buffer has not already // completed an PAYS action - if (paid() != 0 || currentAction() == PAYS) revert('Duplicate request - pays'); } // Placeholder function when no pre or post condition for a function is needed function none() private pure { } // Runtime getters: // // Returns the execution id from memory - function execID() internal pure returns (bytes32 exec_id) { assembly { exec_id := mload(0x80) } require(exec_id != bytes32(0), "Execution id overwritten, or not read"); } // Returns the original sender from memory - function sender() internal pure returns (address addr) { assembly { addr := mload(0xa0) } require(addr != address(0), "Sender address overwritten, or not read"); } // Reading from storage: // // Reads from storage, resolving the passed-in location to its true location in storage // by hashing with the exec id. Returns the data read from that location function read(bytes32 _location) internal view returns (bytes32 data) { data = keccak256(_location, execID()); assembly { data := sload(data) } } // Storing data, emitting events, and forwarding payments: // bytes4 internal constant EMITS = bytes4(keccak256('Emit((bytes32[],bytes)[])')); bytes4 internal constant STORES = bytes4(keccak256('Store(bytes32[])')); bytes4 internal constant PAYS = bytes4(keccak256('Pay(bytes32[])')); bytes4 internal constant THROWS = bytes4(keccak256('Error(string)')); // Function enums - enum NextFunction { INVALID, NONE, STORE_DEST, VAL_SET, VAL_INC, VAL_DEC, EMIT_LOG, PAY_DEST, PAY_AMT } // Checks that a call pushing a storage destination to the buffer is expected and valid function validStoreDest() private pure { // Ensure that the next function expected pushes a storage destination - if (expected() != NextFunction.STORE_DEST) revert('Unexpected function order - expected storage destination to be pushed'); // Ensure that the current buffer is pushing STORES actions - isStoring(); } // Checks that a call pushing a storage value to the buffer is expected and valid function validStoreVal() private pure { // Ensure that the next function expected pushes a storage value - if ( expected() != NextFunction.VAL_SET && expected() != NextFunction.VAL_INC && expected() != NextFunction.VAL_DEC ) revert('Unexpected function order - expected storage value to be pushed'); // Ensure that the current buffer is pushing STORES actions - isStoring(); } // Checks that a call pushing a payment destination to the buffer is expected and valid function validPayDest() private pure { // Ensure that the next function expected pushes a payment destination - if (expected() != NextFunction.PAY_DEST) revert('Unexpected function order - expected payment destination to be pushed'); // Ensure that the current buffer is pushing PAYS actions - isPaying(); } // Checks that a call pushing a payment amount to the buffer is expected and valid function validPayAmt() private pure { // Ensure that the next function expected pushes a payment amount - if (expected() != NextFunction.PAY_AMT) revert('Unexpected function order - expected payment amount to be pushed'); // Ensure that the current buffer is pushing PAYS actions - isPaying(); } // Checks that a call pushing an event to the buffer is expected and valid function validEvent() private pure { // Ensure that the next function expected pushes an event - if (expected() != NextFunction.EMIT_LOG) revert('Unexpected function order - expected event to be pushed'); // Ensure that the current buffer is pushing EMITS actions - isEmitting(); } // Begins creating a storage buffer - values and locations pushed will be committed // to storage at the end of execution function storing() conditions(validStoreBuff, isStoring) internal pure { bytes4 action_req = STORES; assembly { // Get pointer to buffer length - let ptr := add(0x20, mload(0xc0)) // Push requestor to the end of buffer, as well as to the 'current action' slot - mstore(add(0x20, add(ptr, mload(ptr))), action_req) // Push '0' to the end of the 4 bytes just pushed - this will be the length of the STORES action mstore(add(0x24, add(ptr, mload(ptr))), 0) // Increment buffer length - 0x24 plus the previous length mstore(ptr, add(0x24, mload(ptr))) // Set the current action being executed (STORES) - mstore(0xe0, action_req) // Set the expected next function - STORE_DEST mstore(0x100, 2) // Set a pointer to the length of the current request within the buffer mstore(sub(ptr, 0x20), add(ptr, mload(ptr))) } // Update free memory pointer setFreeMem(); } // Sets a passed in location to a value passed in via 'to' function set(bytes32 _field) conditions(validStoreDest, validStoreVal) internal pure returns (bytes32) { assembly { // Get pointer to buffer length - let ptr := add(0x20, mload(0xc0)) // Push storage destination to the end of the buffer - mstore(add(0x20, add(ptr, mload(ptr))), _field) // Increment buffer length - 0x20 plus the previous length mstore(ptr, add(0x20, mload(ptr))) // Set the expected next function - VAL_SET mstore(0x100, 3) // Increment STORES action length - mstore( mload(sub(ptr, 0x20)), add(1, mload(mload(sub(ptr, 0x20)))) ) // Update number of storage slots pushed to - mstore(0x120, add(1, mload(0x120))) } // Update free memory pointer setFreeMem(); return _field; } // Sets a previously-passed-in destination in storage to the value function to(bytes32, bytes32 _val) conditions(validStoreVal, validStoreDest) internal pure { assembly { // Get pointer to buffer length - let ptr := add(0x20, mload(0xc0)) // Push storage value to the end of the buffer - mstore(add(0x20, add(ptr, mload(ptr))), _val) // Increment buffer length - 0x20 plus the previous length mstore(ptr, add(0x20, mload(ptr))) // Set the expected next function - STORE_DEST mstore(0x100, 2) } // Update free memory pointer setFreeMem(); } // Sets a previously-passed-in destination in storage to the value function to(bytes32 _field, uint _val) internal pure { to(_field, bytes32(_val)); } // Sets a previously-passed-in destination in storage to the value function to(bytes32 _field, address _val) internal pure { to(_field, bytes32(_val)); } // Sets a previously-passed-in destination in storage to the value function to(bytes32 _field, bool _val) internal pure { to( _field, _val ? bytes32(1) : bytes32(0) ); } function increase(bytes32 _field) conditions(validStoreDest, validStoreVal) internal view returns (bytes32 val) { // Read value stored at the location in storage - val = keccak256(_field, execID()); assembly { val := sload(val) // Get pointer to buffer length - let ptr := add(0x20, mload(0xc0)) // Push storage destination to the end of the buffer - mstore(add(0x20, add(ptr, mload(ptr))), _field) // Increment buffer length - 0x20 plus the previous length mstore(ptr, add(0x20, mload(ptr))) // Set the expected next function - VAL_INC mstore(0x100, 4) // Increment STORES action length - mstore( mload(sub(ptr, 0x20)), add(1, mload(mload(sub(ptr, 0x20)))) ) // Update number of storage slots pushed to - mstore(0x120, add(1, mload(0x120))) } // Update free memory pointer setFreeMem(); return val; } function decrease(bytes32 _field) conditions(validStoreDest, validStoreVal) internal view returns (bytes32 val) { // Read value stored at the location in storage - val = keccak256(_field, execID()); assembly { val := sload(val) // Get pointer to buffer length - let ptr := add(0x20, mload(0xc0)) // Push storage destination to the end of the buffer - mstore(add(0x20, add(ptr, mload(ptr))), _field) // Increment buffer length - 0x20 plus the previous length mstore(ptr, add(0x20, mload(ptr))) // Set the expected next function - VAL_DEC mstore(0x100, 5) // Increment STORES action length - mstore( mload(sub(ptr, 0x20)), add(1, mload(mload(sub(ptr, 0x20)))) ) // Update number of storage slots pushed to - mstore(0x120, add(1, mload(0x120))) } // Update free memory pointer setFreeMem(); return val; } function by(bytes32 _val, uint _amt) conditions(validStoreVal, validStoreDest) internal pure { // Check the expected function type - if it is VAL_INC, perform safe-add on the value // If it is VAL_DEC, perform safe-sub on the value if (expected() == NextFunction.VAL_INC) _amt = _amt.add(uint(_val)); else if (expected() == NextFunction.VAL_DEC) _amt = uint(_val).sub(_amt); else revert('Expected VAL_INC or VAL_DEC'); assembly { // Get pointer to buffer length - let ptr := add(0x20, mload(0xc0)) // Push storage value to the end of the buffer - mstore(add(0x20, add(ptr, mload(ptr))), _amt) // Increment buffer length - 0x20 plus the previous length mstore(ptr, add(0x20, mload(ptr))) // Set the expected next function - STORE_DEST mstore(0x100, 2) } // Update free memory pointer setFreeMem(); } // Decreases the value at some field by a maximum amount, and sets it to 0 if there will be underflow function byMaximum(bytes32 _val, uint _amt) conditions(validStoreVal, validStoreDest) internal pure { // Check the expected function type - if it is VAL_DEC, set the new amount to the difference of // _val and _amt, to a minimum of 0 if (expected() == NextFunction.VAL_DEC) { if (_amt >= uint(_val)) _amt = 0; else _amt = uint(_val).sub(_amt); } else { revert('Expected VAL_DEC'); } assembly { // Get pointer to buffer length - let ptr := add(0x20, mload(0xc0)) // Push storage value to the end of the buffer - mstore(add(0x20, add(ptr, mload(ptr))), _amt) // Increment buffer length - 0x20 plus the previous length mstore(ptr, add(0x20, mload(ptr))) // Set the expected next function - STORE_DEST mstore(0x100, 2) } // Update free memory pointer setFreeMem(); } // Begins creating an event log buffer - topics and data pushed will be emitted by // storage at the end of execution function emitting() conditions(validEmitBuff, isEmitting) internal pure { bytes4 action_req = EMITS; assembly { // Get pointer to buffer length - let ptr := add(0x20, mload(0xc0)) // Push requestor to the end of buffer, as well as to the 'current action' slot - mstore(add(0x20, add(ptr, mload(ptr))), action_req) // Push '0' to the end of the 4 bytes just pushed - this will be the length of the EMITS action mstore(add(0x24, add(ptr, mload(ptr))), 0) // Increment buffer length - 0x24 plus the previous length mstore(ptr, add(0x24, mload(ptr))) // Set the current action being executed (EMITS) - mstore(0xe0, action_req) // Set the expected next function - EMIT_LOG mstore(0x100, 6) // Set a pointer to the length of the current request within the buffer mstore(sub(ptr, 0x20), add(ptr, mload(ptr))) } // Update free memory pointer setFreeMem(); } function log(bytes32 _data) conditions(validEvent, validEvent) internal pure { assembly { // Get pointer to buffer length - let ptr := add(0x20, mload(0xc0)) // Push 0 to the end of the buffer - event will have 0 topics mstore(add(0x20, add(ptr, mload(ptr))), 0) // If _data is zero, set data size to 0 in buffer and push - if eq(_data, 0) { mstore(add(0x40, add(ptr, mload(ptr))), 0) // Increment buffer length - 0x40 plus the original length mstore(ptr, add(0x40, mload(ptr))) } // If _data is not zero, set size to 0x20 and push to buffer - if iszero(eq(_data, 0)) { // Push data size (0x20) to the end of the buffer mstore(add(0x40, add(ptr, mload(ptr))), 0x20) // Push data to the end of the buffer mstore(add(0x60, add(ptr, mload(ptr))), _data) // Increment buffer length - 0x60 plus the original length mstore(ptr, add(0x60, mload(ptr))) } // Increment EMITS action length - mstore( mload(sub(ptr, 0x20)), add(1, mload(mload(sub(ptr, 0x20)))) ) // Update number of events pushed to buffer - mstore(0x140, add(1, mload(0x140))) } // Update free memory pointer setFreeMem(); } function log(bytes32[1] memory _topics, bytes32 _data) conditions(validEvent, validEvent) internal pure { assembly { // Get pointer to buffer length - let ptr := add(0x20, mload(0xc0)) // Push 1 to the end of the buffer - event will have 1 topic mstore(add(0x20, add(ptr, mload(ptr))), 1) // Push topic to end of buffer mstore(add(0x40, add(ptr, mload(ptr))), mload(_topics)) // If _data is zero, set data size to 0 in buffer and push - if eq(_data, 0) { mstore(add(0x60, add(ptr, mload(ptr))), 0) // Increment buffer length - 0x60 plus the original length mstore(ptr, add(0x60, mload(ptr))) } // If _data is not zero, set size to 0x20 and push to buffer - if iszero(eq(_data, 0)) { // Push data size (0x20) to the end of the buffer mstore(add(0x60, add(ptr, mload(ptr))), 0x20) // Push data to the end of the buffer mstore(add(0x80, add(ptr, mload(ptr))), _data) // Increment buffer length - 0x80 plus the original length mstore(ptr, add(0x80, mload(ptr))) } // Increment EMITS action length - mstore( mload(sub(ptr, 0x20)), add(1, mload(mload(sub(ptr, 0x20)))) ) // Update number of events pushed to buffer - mstore(0x140, add(1, mload(0x140))) } // Update free memory pointer setFreeMem(); } function log(bytes32[2] memory _topics, bytes32 _data) conditions(validEvent, validEvent) internal pure { assembly { // Get pointer to buffer length - let ptr := add(0x20, mload(0xc0)) // Push 2 to the end of the buffer - event will have 2 topics mstore(add(0x20, add(ptr, mload(ptr))), 2) // Push topics to end of buffer mstore(add(0x40, add(ptr, mload(ptr))), mload(_topics)) mstore(add(0x60, add(ptr, mload(ptr))), mload(add(0x20, _topics))) // If _data is zero, set data size to 0 in buffer and push - if eq(_data, 0) { mstore(add(0x80, add(ptr, mload(ptr))), 0) // Increment buffer length - 0x80 plus the original length mstore(ptr, add(0x80, mload(ptr))) } // If _data is not zero, set size to 0x20 and push to buffer - if iszero(eq(_data, 0)) { // Push data size (0x20) to the end of the buffer mstore(add(0x80, add(ptr, mload(ptr))), 0x20) // Push data to the end of the buffer mstore(add(0xa0, add(ptr, mload(ptr))), _data) // Increment buffer length - 0xa0 plus the original length mstore(ptr, add(0xa0, mload(ptr))) } // Increment EMITS action length - mstore( mload(sub(ptr, 0x20)), add(1, mload(mload(sub(ptr, 0x20)))) ) // Update number of events pushed to buffer - mstore(0x140, add(1, mload(0x140))) } // Update free memory pointer setFreeMem(); } function log(bytes32[3] memory _topics, bytes32 _data) conditions(validEvent, validEvent) internal pure { assembly { // Get pointer to buffer length - let ptr := add(0x20, mload(0xc0)) // Push 3 to the end of the buffer - event will have 3 topics mstore(add(0x20, add(ptr, mload(ptr))), 3) // Push topics to end of buffer mstore(add(0x40, add(ptr, mload(ptr))), mload(_topics)) mstore(add(0x60, add(ptr, mload(ptr))), mload(add(0x20, _topics))) mstore(add(0x80, add(ptr, mload(ptr))), mload(add(0x40, _topics))) // If _data is zero, set data size to 0 in buffer and push - if eq(_data, 0) { mstore(add(0xa0, add(ptr, mload(ptr))), 0) // Increment buffer length - 0xa0 plus the original length mstore(ptr, add(0xa0, mload(ptr))) } // If _data is not zero, set size to 0x20 and push to buffer - if iszero(eq(_data, 0)) { // Push data size (0x20) to the end of the buffer mstore(add(0xa0, add(ptr, mload(ptr))), 0x20) // Push data to the end of the buffer mstore(add(0xc0, add(ptr, mload(ptr))), _data) // Increment buffer length - 0xc0 plus the original length mstore(ptr, add(0xc0, mload(ptr))) } // Increment EMITS action length - mstore( mload(sub(ptr, 0x20)), add(1, mload(mload(sub(ptr, 0x20)))) ) // Update number of events pushed to buffer - mstore(0x140, add(1, mload(0x140))) } // Update free memory pointer setFreeMem(); } function log(bytes32[4] memory _topics, bytes32 _data) conditions(validEvent, validEvent) internal pure { assembly { // Get pointer to buffer length - let ptr := add(0x20, mload(0xc0)) // Push 4 to the end of the buffer - event will have 4 topics mstore(add(0x20, add(ptr, mload(ptr))), 4) // Push topics to end of buffer mstore(add(0x40, add(ptr, mload(ptr))), mload(_topics)) mstore(add(0x60, add(ptr, mload(ptr))), mload(add(0x20, _topics))) mstore(add(0x80, add(ptr, mload(ptr))), mload(add(0x40, _topics))) mstore(add(0xa0, add(ptr, mload(ptr))), mload(add(0x60, _topics))) // If _data is zero, set data size to 0 in buffer and push - if eq(_data, 0) { mstore(add(0xc0, add(ptr, mload(ptr))), 0) // Increment buffer length - 0xc0 plus the original length mstore(ptr, add(0xc0, mload(ptr))) } // If _data is not zero, set size to 0x20 and push to buffer - if iszero(eq(_data, 0)) { // Push data size (0x20) to the end of the buffer mstore(add(0xc0, add(ptr, mload(ptr))), 0x20) // Push data to the end of the buffer mstore(add(0xe0, add(ptr, mload(ptr))), _data) // Increment buffer length - 0xe0 plus the original length mstore(ptr, add(0xe0, mload(ptr))) } // Increment EMITS action length - mstore( mload(sub(ptr, 0x20)), add(1, mload(mload(sub(ptr, 0x20)))) ) // Update number of events pushed to buffer - mstore(0x140, add(1, mload(0x140))) } // Update free memory pointer setFreeMem(); } // Begins creating a storage buffer - destinations entered will be forwarded wei // before the end of execution function paying() conditions(validPayBuff, isPaying) internal pure { bytes4 action_req = PAYS; assembly { // Get pointer to buffer length - let ptr := add(0x20, mload(0xc0)) // Push requestor to the end of buffer, as well as to the 'current action' slot - mstore(add(0x20, add(ptr, mload(ptr))), action_req) // Push '0' to the end of the 4 bytes just pushed - this will be the length of the PAYS action mstore(add(0x24, add(ptr, mload(ptr))), 0) // Increment buffer length - 0x24 plus the previous length mstore(ptr, add(0x24, mload(ptr))) // Set the current action being executed (PAYS) - mstore(0xe0, action_req) // Set the expected next function - PAY_AMT mstore(0x100, 8) // Set a pointer to the length of the current request within the buffer mstore(sub(ptr, 0x20), add(ptr, mload(ptr))) } // Update free memory pointer setFreeMem(); } // Pushes an amount of wei to forward to the buffer function pay(uint _amount) conditions(validPayAmt, validPayDest) internal pure returns (uint) { assembly { // Get pointer to buffer length - let ptr := add(0x20, mload(0xc0)) // Push payment amount to the end of the buffer - mstore(add(0x20, add(ptr, mload(ptr))), _amount) // Increment buffer length - 0x20 plus the previous length mstore(ptr, add(0x20, mload(ptr))) // Set the expected next function - PAY_DEST mstore(0x100, 7) // Increment PAYS action length - mstore( mload(sub(ptr, 0x20)), add(1, mload(mload(sub(ptr, 0x20)))) ) // Update number of payment destinations to be pushed to - mstore(0x160, add(1, mload(0x160))) } // Update free memory pointer setFreeMem(); return _amount; } // Push an address to forward wei to, to the buffer function toAcc(uint, address _dest) conditions(validPayDest, validPayAmt) internal pure { assembly { // Get pointer to buffer length - let ptr := add(0x20, mload(0xc0)) // Push payment destination to the end of the buffer - mstore(add(0x20, add(ptr, mload(ptr))), _dest) // Increment buffer length - 0x20 plus the previous length mstore(ptr, add(0x20, mload(ptr))) // Set the expected next function - PAY_AMT mstore(0x100, 8) } // Update free memory pointer setFreeMem(); } // Sets the free memory pointer to point beyond all accessed memory function setFreeMem() private pure { assembly { mstore(0x40, msize) } } // Returns the enum representing the next expected function to be called - function expected() private pure returns (NextFunction next) { assembly { next := mload(0x100) } } // Returns the number of events pushed to the storage buffer - function emitted() internal pure returns (uint num_emitted) { if (buffPtr() == bytes32(0)) return 0; // Load number emitted from buffer - assembly { num_emitted := mload(0x140) } } // Returns the number of storage slots pushed to the storage buffer - function stored() internal pure returns (uint num_stored) { if (buffPtr() == bytes32(0)) return 0; // Load number stored from buffer - assembly { num_stored := mload(0x120) } } // Returns the number of payment destinations and amounts pushed to the storage buffer - function paid() internal pure returns (uint num_paid) { if (buffPtr() == bytes32(0)) return 0; // Load number paid from buffer - assembly { num_paid := mload(0x160) } } } library Transfer { using Contract for *; // 'Transfer' event topic signature bytes32 private constant TRANSFER_SIG = keccak256('Transfer(address,address,uint256)'); // Returns the topics for a Transfer event - function TRANSFER (address _owner, address _dest) private pure returns (bytes32[3] memory) { return [TRANSFER_SIG, bytes32(_owner), bytes32(_dest)]; } // Ensures the sender is a transfer agent, or that the tokens are unlocked function canTransfer() internal view { if ( Contract.read(Token.transferAgents(Contract.sender())) == 0 && Contract.read(Token.isFinished()) == 0 ) revert('transfers are locked'); } // Implements the logic for a token transfer - function transfer(address _dest, uint _amt) internal view { // Ensure valid input - if (_dest == 0 || _dest == Contract.sender()) revert('invalid recipient'); // Ensure the sender can currently transfer tokens Contract.checks(canTransfer); // Begin updating balances - Contract.storing(); // Update sender token balance - reverts in case of underflow Contract.decrease(Token.balances(Contract.sender())).by(_amt); // Update recipient token balance - reverts in case of overflow Contract.increase(Token.balances(_dest)).by(_amt); // Finish updating balances: log event - Contract.emitting(); // Log 'Transfer' event Contract.log( TRANSFER(Contract.sender(), _dest), bytes32(_amt) ); } // Implements the logic for a token transferFrom - function transferFrom(address _owner, address _dest, uint _amt) internal view { // Ensure valid input - if (_dest == 0 || _dest == _owner) revert('invalid recipient'); if (_owner == 0) revert('invalid owner'); // Owner must be able to transfer tokens - if ( Contract.read(Token.transferAgents(_owner)) == 0 && Contract.read(Token.isFinished()) == 0 ) revert('transfers are locked'); // Begin updating balances - Contract.storing(); // Update spender token allowance - reverts in case of underflow Contract.decrease(Token.allowed(_owner, Contract.sender())).by(_amt); // Update owner token balance - reverts in case of underflow Contract.decrease(Token.balances(_owner)).by(_amt); // Update recipient token balance - reverts in case of overflow Contract.increase(Token.balances(_dest)).by(_amt); // Finish updating balances: log event - Contract.emitting(); // Log 'Transfer' event Contract.log( TRANSFER(_owner, _dest), bytes32(_amt) ); } } library Approve { using Contract for *; // event Approval(address indexed owner, address indexed spender, uint tokens) bytes32 internal constant APPROVAL_SIG = keccak256('Approval(address,address,uint256)'); // Returns the events and data for an 'Approval' event - function APPROVAL (address _owner, address _spender) private pure returns (bytes32[3] memory) { return [APPROVAL_SIG, bytes32(_owner), bytes32(_spender)]; } // Implements the logic to create the storage buffer for a Token Approval function approve(address _spender, uint _amt) internal pure { // Begin storing values - Contract.storing(); // Store the approved amount at the sender's allowance location for the _spender Contract.set(Token.allowed(Contract.sender(), _spender)).to(_amt); // Finish storing, and begin logging events - Contract.emitting(); // Log 'Approval' event - Contract.log( APPROVAL(Contract.sender(), _spender), bytes32(_amt) ); } // Implements the logic to create the storage buffer for a Token Approval function increaseApproval(address _spender, uint _amt) internal view { // Begin storing values - Contract.storing(); // Store the approved amount at the sender's allowance location for the _spender Contract.increase(Token.allowed(Contract.sender(), _spender)).by(_amt); // Finish storing, and begin logging events - Contract.emitting(); // Log 'Approval' event - Contract.log( APPROVAL(Contract.sender(), _spender), bytes32(_amt) ); } // Implements the logic to create the storage buffer for a Token Approval function decreaseApproval(address _spender, uint _amt) internal view { // Begin storing values - Contract.storing(); // Decrease the spender's approval by _amt to a minimum of 0 - Contract.decrease(Token.allowed(Contract.sender(), _spender)).byMaximum(_amt); // Finish storing, and begin logging events - Contract.emitting(); // Log 'Approval' event - Contract.log( APPROVAL(Contract.sender(), _spender), bytes32(_amt) ); } } library Token { using Contract for *; /// SALE /// // Whether or not the crowdsale is post-purchase function isFinished() internal pure returns (bytes32) { return keccak256("sale_is_completed"); } /// TOKEN /// // Storage location for token name function tokenName() internal pure returns (bytes32) { return keccak256("token_name"); } // Storage seed for user balances mapping bytes32 internal constant TOKEN_BALANCES = keccak256("token_balances"); function balances(address _owner) internal pure returns (bytes32) { return keccak256(_owner, TOKEN_BALANCES); } // Storage seed for user allowances mapping bytes32 internal constant TOKEN_ALLOWANCES = keccak256("token_allowances"); function allowed(address _owner, address _spender) internal pure returns (bytes32) { return keccak256(_spender, keccak256(_owner, TOKEN_ALLOWANCES)); } // Storage seed for token 'transfer agent' status for any address // Transfer agents can transfer tokens, even if the crowdsale has not yet been finalized bytes32 internal constant TOKEN_TRANSFER_AGENTS = keccak256("token_transfer_agents"); function transferAgents(address _agent) internal pure returns (bytes32) { return keccak256(_agent, TOKEN_TRANSFER_AGENTS); } /// CHECKS /// // Ensures the sale's token has been initialized function tokenInit() internal view { if (Contract.read(tokenName()) == 0) revert('token not initialized'); } // Ensures both storage and events have been pushed to the buffer function emitAndStore() internal pure { if (Contract.emitted() == 0 || Contract.stored() == 0) revert('invalid state change'); } /// FUNCTIONS /// /* Allows a token holder to transfer tokens to another address @param _to: The destination that will recieve tokens @param _amount: The number of tokens to transfer */ function transfer(address _to, uint _amount) external view { // Begin execution - reads execution id and original sender address from storage Contract.authorize(msg.sender); // Check that the token is initialized - Contract.checks(tokenInit); // Execute transfer function - Transfer.transfer(_to, _amount); // Ensures state change will affect storage and events - Contract.checks(emitAndStore); // Commit state changes to storage - Contract.commit(); } /* Allows an approved spender to transfer tokens to another address on an owner's behalf @param _owner: The address from which tokens will be sent @param _recipient: The destination to which tokens will be sent @param _amount: The number of tokens to transfer */ function transferFrom(address _owner, address _recipient, uint _amount) external view { // Begin execution - reads execution id and original sender address from storage Contract.authorize(msg.sender); // Check that the token is initialized - Contract.checks(tokenInit); // Execute transfer function - Transfer.transferFrom(_owner, _recipient, _amount); // Ensures state change will affect storage and events - Contract.checks(emitAndStore); // Commit state changes to storage - Contract.commit(); } /* Approves a spender to spend an amount of your tokens on your behalf @param _spender: The address allowed to spend your tokens @param _amount: The number of tokens that will be approved */ function approve(address _spender, uint _amount) external view { // Begin execution - reads execution id and original sender address from storage Contract.authorize(msg.sender); // Check that the token is initialized - Contract.checks(tokenInit); // Execute approval function - Approve.approve(_spender, _amount); // Ensures state change will affect storage and events - Contract.checks(emitAndStore); // Commit state changes to storage - Contract.commit(); } /* Increases a spender's approval amount @param _spender: The address allowed to spend your tokens @param _amount: The amount by which the spender's allowance will be increased */ function increaseApproval(address _spender, uint _amount) external view { // Begin execution - reads execution id and original sender address from storage Contract.authorize(msg.sender); // Check that the token is initialized - Contract.checks(tokenInit); // Execute approval function - Approve.increaseApproval(_spender, _amount); // Ensures state change will affect storage and events - Contract.checks(emitAndStore); // Commit state changes to storage - Contract.commit(); } /* Decreases a spender's approval amount @param _spender: The address allowed to spend your tokens @param _amount: The amount by which the spender's allowance will be decreased */ function decreaseApproval(address _spender, uint _amount) external view { // Begin execution - reads execution id and original sender address from storage Contract.authorize(msg.sender); // Check that the token is initialized - Contract.checks(tokenInit); // Execute approval function - Approve.decreaseApproval(_spender, _amount); // Ensures state change will affect storage and events - Contract.checks(emitAndStore); // Commit state changes to storage - Contract.commit(); } }
Returns the number of events pushed to the storage buffer - Load number emitted from buffer -
function emitted() internal pure returns (uint num_emitted) { if (buffPtr() == bytes32(0)) return 0; }
1,484,933