file_name
stringlengths
71
779k
comments
stringlengths
20
182k
code_string
stringlengths
20
36.9M
__index_level_0__
int64
0
17.2M
input_ids
sequence
attention_mask
sequence
labels
sequence
/** *Submitted for verification at Etherscan.io on 2021-03-12 */ // File: @openzeppelin/contracts/utils/Context.sol // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: @openzeppelin/contracts/introspection/IERC165.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol pragma solidity >=0.6.2 <0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // File: @openzeppelin/contracts/token/ERC721/IERC721Metadata.sol pragma solidity >=0.6.2 <0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol pragma solidity >=0.6.2 <0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol pragma solidity >=0.6.0 <0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // File: @openzeppelin/contracts/introspection/ERC165.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/utils/EnumerableSet.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File: @openzeppelin/contracts/utils/EnumerableMap.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key) return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); } } // File: @openzeppelin/contracts/utils/Strings.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev String operations. */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol pragma solidity >=0.6.0 <0.8.0; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(base, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view virtual returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _tokenOwners.contains(tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); // internal owner _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } function _approve(address to, uint256 tokenId) private { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } // File: @openzeppelin/contracts/utils/Counters.sol pragma solidity >=0.6.0 <0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. 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;` * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath} * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using SafeMath for uint256; 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 { // The {SafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } // File: contracts/DeekHash.sol pragma solidity >=0.7.0 <0.8.0; contract DeekHash is ERC721, Ownable { using Counters for Counters.Counter; using SafeMath for uint256; Counters.Counter private _tokenIds; uint256 public constant INITIAL_REG_DEEKS_CAP = 10000; uint256 private _saleBeginTime = 1615561200; // 12 March 2021, 10:00 GMT-5 (NY time) uint256 private _regularDeeksCap = INITIAL_REG_DEEKS_CAP; uint256 private _superDeeksBorn = 0; address private safeAddress; struct Deek { string name; string dna; } Deek[] private Deeks; /* * Mapping for passphrases hashes for superDeeks * True means active , not redeemed yet * False would mean promocode is invalid or already redeemed */ mapping (bytes32 => bool) private superHashToRedeemStatus; constructor(address _safeAddress, string memory myBase) ERC721("DEEKHASH", "DKHSH") { _setBaseURI(myBase); safeAddress = _safeAddress; } /** * @dev Sets new maximum for the Regular Deeks to be born. It can't be more than INITIAL_REG_DEEKS_CAP */ function setNewRegularDeeksCap(uint256 _newRegularDeeksCap) public onlyOwner { require(_newRegularDeeksCap <= INITIAL_REG_DEEKS_CAP, "Regular Deeks capacity cant be higher than INITIAL_REG_DEEKS_CAP"); _regularDeeksCap = _newRegularDeeksCap; } /************************************************************************* * REGULAR DEEKS GENESIS BLOCK *************************************************************************/ /** * @dev Gets current Deek price. Hard borders are incremented by superHeroesBorn * in case some superheroes will born before sale ends */ function getDeekPrice() public view returns (uint256) { require(block.timestamp >= _saleBeginTime, "Too early, guys"); require(totalSupply() < getTotalCurrCapacity(), "All Deeks were born"); uint currentSupply = totalSupply(); if (currentSupply >= 8400 + getSuperDeeksBorn()) { return 500000000000000000; // 8400 - 9999 0.5 ETH } else if (currentSupply >= 5000 + getSuperDeeksBorn()) { return 400000000000000000; // 5000 - 8399 0.4 ETH } else if (currentSupply >= 1600 + getSuperDeeksBorn()) { return 300000000000000000; // 1600 - 4999 0.3 ETH } else if (currentSupply >= 250 + getSuperDeeksBorn()) { return 200000000000000000; // 250 - 1599 0.2 ETH } else { return 100000000000000000; // 0 - 249 0.1 ETH } } /** * @dev Mints a token * @param _name = string to hash by user from frontend * @param _dna = Deek's dna generated by frontend from _name hash */ function createDeek(string memory _name, string memory _dna) public payable returns (uint256) { require(totalSupply() < getTotalCurrCapacity(), "All Deeks were born"); require(msg.value == getDeekPrice(), "Ether value sent is not correct"); // set the tokenId for token we are going to mint uint256 newItemId = _tokenIds.current(); _safeMint(msg.sender, newItemId); // we fill Deek name and dna which are going to be stored on-chain Deeks.push(Deek(_name, _dna)); // increment counter. _tokenIds.increment(); return newItemId; } /************************************************************************* * SUPERDEEKS GENESIS BLOCK *************************************************************************/ /** * @dev Adds a hash of a promocode to get the SuperDeek */ function addSuperHash(string memory _promoCode) external onlyOwner { superHashToRedeemStatus[keccak256(abi.encodePacked(_promoCode))] = true; } function removeSuperHash(string memory _promoCode) external onlyOwner { superHashToRedeemStatus[keccak256(abi.encodePacked(_promoCode))] = false; } /** * @dev Checks if there is a hash corresponding to a user entered promocode in * the array of the correct promocode hashes */ function isPromoCodeValid(string memory _userPromoCode) internal view returns(bool) { bool _superDeekValid = superHashToRedeemStatus[keccak256(abi.encodePacked(_userPromoCode))]; return (_superDeekValid); } /** * @dev Mints a superDeek */ function createSuperDeek (string memory _name, string memory _dna, string memory _userPromoCode) public returns (uint256) { require(block.timestamp >= _saleBeginTime, "Too early, guys"); require(isPromoCodeValid(_userPromoCode), "Your spell is not valid or already used"); // set the tokenId for token we are going to mint uint256 newItemId = _tokenIds.current(); _safeMint(msg.sender, newItemId); // we fill Deek name and dna which are going to be stored on-chain Deeks.push(Deek(_name, _dna)); // increment counter and _superDeeksBorn value _tokenIds.increment(); _superDeeksBorn = _superDeeksBorn.add(1); // mark Promocode as not active superHashToRedeemStatus[keccak256(abi.encodePacked(_userPromoCode))] = false; return newItemId; } /************************************************************************** * Working with URIs **************************************************************************/ /** * @dev sets new base URI in case old is broken * baseURI is an URI for the json with the metadata for a token */ function _setNewBaseURI(string memory _newBaseURI) external onlyOwner { _setBaseURI(_newBaseURI); } /* * baseURI() function which returns private _baseURI variable is defined in ERC721 */ /*************************************************************************** * Views block ***************************************************************************/ function getRegularDeeksCap() public view returns(uint256) { return _regularDeeksCap; } function getSuperDeeksBorn() public view returns(uint256) { return _superDeeksBorn; } function getTotalCurrCapacity() public view returns (uint256) { return (getRegularDeeksCap()).add(getSuperDeeksBorn()); } /** * @dev get name by tokenId */ function nameByTokenId(uint256 _tokenId) public view returns(string memory) { return Deeks[_tokenId].name; } /** * @dev get dna by tokenId */ function dnaByTokenId(uint256 _tokenId) public view returns(string memory) { return Deeks[_tokenId].dna; } /** * @dev returns tokenId for the NEXT token to be minted */ function getNextTokenId() public view returns(uint256) { return _tokenIds.current(); } /** * @dev returns safeAccount address */ function getSafeAccountAddress() onlyOwner public view returns(address) { return safeAddress; } /*************************************************************************** * Finances block ***************************************************************************/ /** * @dev Check contract balance */ function getContractBalance() onlyOwner public view returns(uint256) { uint256 balance = address(this).balance; return balance; } /** * @dev Withdraw ether from this contract */ function withdraw() onlyOwner public { uint256 balance = address(this).balance; msg.sender.transfer(balance); } /** * @dev Withdraw to the SafeAddress */ function withdrawToSafeAddress() onlyOwner public { uint256 balance = address(this).balance; payable(safeAddress).transfer(balance); } /*************************************************************************** * Sale start time management block ***************************************************************************/ /** * @dev Check sale start time */ function getSaleStartTime() public view returns(uint256) { return _saleBeginTime; } /** * @dev Set sale start time */ function setSaleStartTime(uint256 _newSaleStartTime) onlyOwner public { _saleBeginTime = _newSaleStartTime; } }
* @dev Mints a token @param _name = string to hash by user from frontend @param _dna = Deek's dna generated by frontend from _name hash/ set the tokenId for token we are going to mint we fill Deek name and dna which are going to be stored on-chain increment counter.
function createDeek(string memory _name, string memory _dna) public payable returns (uint256) { require(totalSupply() < getTotalCurrCapacity(), "All Deeks were born"); require(msg.value == getDeekPrice(), "Ether value sent is not correct"); uint256 newItemId = _tokenIds.current(); _safeMint(msg.sender, newItemId); Deeks.push(Deek(_name, _dna)); _tokenIds.increment(); return newItemId; }
6,796,373
[ 1, 49, 28142, 279, 1147, 225, 389, 529, 273, 533, 358, 1651, 635, 729, 628, 15442, 225, 389, 5176, 69, 273, 463, 3317, 1807, 31702, 4374, 635, 15442, 628, 389, 529, 1651, 19, 444, 326, 1147, 548, 364, 1147, 732, 854, 8554, 358, 312, 474, 732, 3636, 463, 3317, 508, 471, 31702, 1492, 854, 8554, 358, 506, 4041, 603, 17, 5639, 5504, 3895, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 752, 758, 3839, 12, 1080, 3778, 389, 529, 16, 533, 3778, 389, 5176, 69, 13, 7010, 202, 482, 7010, 202, 10239, 429, 7010, 202, 6154, 261, 11890, 5034, 13, 203, 565, 288, 203, 3639, 2583, 12, 4963, 3088, 1283, 1435, 411, 12831, 20143, 7437, 9334, 315, 1595, 463, 3317, 87, 4591, 324, 14245, 8863, 203, 3639, 2583, 12, 3576, 18, 1132, 422, 336, 758, 3839, 5147, 9334, 315, 41, 1136, 460, 3271, 353, 486, 3434, 8863, 203, 203, 3639, 2254, 5034, 394, 17673, 273, 389, 2316, 2673, 18, 2972, 5621, 203, 540, 203, 3639, 389, 4626, 49, 474, 12, 3576, 18, 15330, 16, 394, 17673, 1769, 203, 540, 203, 3639, 463, 3317, 87, 18, 6206, 12, 758, 3839, 24899, 529, 16, 389, 5176, 69, 10019, 203, 540, 203, 3639, 389, 2316, 2673, 18, 15016, 5621, 203, 1171, 203, 3639, 327, 394, 17673, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/42/0x7fD32F4e82Cf4369586Ee12f8333c656cC1965B6/sources/ArtToken.sol
Check if this piece name & description is uniquecreate an art token
function createUniqueArt(bytes32 _title, string calldata _description, string calldata _tokenURI) external returns (uint) { bytes32 hash = keccak256(abi.encodePacked(_title)); require(userArt[hash].creator == address(0)); userArt[hash] = Art(_title, _description, msg.sender); index += 1; _safeMint(msg.sender, index); _setTokenURI(index, _tokenURI); return index; }
9,089,653
[ 1, 1564, 309, 333, 11151, 508, 473, 2477, 353, 3089, 2640, 392, 3688, 1147, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 445, 752, 6303, 4411, 12, 3890, 1578, 389, 2649, 16, 533, 745, 892, 389, 3384, 16, 533, 745, 892, 389, 2316, 3098, 13, 3903, 1135, 261, 11890, 13, 288, 203, 203, 225, 1731, 1578, 1651, 273, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 24899, 2649, 10019, 203, 225, 2583, 12, 1355, 4411, 63, 2816, 8009, 20394, 422, 1758, 12, 20, 10019, 203, 225, 729, 4411, 63, 2816, 65, 273, 9042, 24899, 2649, 16, 389, 3384, 16, 1234, 18, 15330, 1769, 203, 203, 565, 770, 1011, 404, 31, 203, 565, 389, 4626, 49, 474, 12, 3576, 18, 15330, 16, 770, 1769, 203, 565, 389, 542, 1345, 3098, 12, 1615, 16, 389, 2316, 3098, 1769, 203, 377, 203, 565, 327, 770, 31, 203, 225, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.6.12; /** * @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); } interface ITokensTypeStorage { function isRegistred(address _address) external view returns(bool); function getType(address _address) external view returns(bytes32); function isPermittedAddress(address _address) external view returns(bool); function owner() external view returns(address); function addNewTokenType(address _token, string calldata _type) external; function setTokenTypeAsOwner(address _token, string calldata _type) external; } interface IBalancerPool { function joinPool(uint poolAmountOut, uint[] calldata maxAmountsIn) external; function exitPool(uint poolAmountIn, uint[] calldata minAmountsOut) external; function getCurrentTokens() external view returns (address[] memory tokens); } interface IUniswapV2Pair { function token0() external view returns (address); function token1() external view returns (address); } interface IUniswapV2Router { 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 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 UniswapFactoryInterfaceV1 { // Create Exchange function createExchange(address token) external returns (address exchange); // Get Exchange and Token Info function getExchange(address token) external view returns (address exchange); function getToken(address exchange) external view returns (address token); function getTokenWithId(uint256 tokenId) external view returns (address token); // Never use function initializeFactory(address template) external; } interface UniswapExchangeInterface { // Address of ERC20 token sold on this exchange function tokenAddress() external view returns (address token); // Address of Uniswap Factory function factoryAddress() external view returns (address factory); // Provide Liquidity function addLiquidity(uint256 min_liquidity, uint256 max_tokens, uint256 deadline) external payable returns (uint256); function removeLiquidity(uint256 amount, uint256 min_eth, uint256 min_tokens, uint256 deadline) external returns (uint256, uint256); // Get Prices function getEthToTokenInputPrice(uint256 eth_sold) external view returns (uint256 tokens_bought); function getEthToTokenOutputPrice(uint256 tokens_bought) external view returns (uint256 eth_sold); function getTokenToEthInputPrice(uint256 tokens_sold) external view returns (uint256 eth_bought); function getTokenToEthOutputPrice(uint256 eth_bought) external view returns (uint256 tokens_sold); // Trade ETH to ERC20 function ethToTokenSwapInput(uint256 min_tokens, uint256 deadline) external payable returns (uint256 tokens_bought); function ethToTokenTransferInput(uint256 min_tokens, uint256 deadline, address recipient) external payable returns (uint256 tokens_bought); function ethToTokenSwapOutput(uint256 tokens_bought, uint256 deadline) external payable returns (uint256 eth_sold); function ethToTokenTransferOutput(uint256 tokens_bought, uint256 deadline, address recipient) external payable returns (uint256 eth_sold); // Trade ERC20 to ETH function tokenToEthSwapInput(uint256 tokens_sold, uint256 min_eth, uint256 deadline) external returns (uint256 eth_bought); function tokenToEthTransferInput(uint256 tokens_sold, uint256 min_eth, uint256 deadline, address recipient) external returns (uint256 eth_bought); function tokenToEthSwapOutput(uint256 eth_bought, uint256 max_tokens, uint256 deadline) external returns (uint256 tokens_sold); function tokenToEthTransferOutput(uint256 eth_bought, uint256 max_tokens, uint256 deadline, address recipient) external returns (uint256 tokens_sold); // Trade ERC20 to ERC20 function tokenToTokenSwapInput(uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address token_addr) external returns (uint256 tokens_bought); function tokenToTokenTransferInput(uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address recipient, address token_addr) external returns (uint256 tokens_bought); function tokenToTokenSwapOutput(uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address token_addr) external returns (uint256 tokens_sold); function tokenToTokenTransferOutput(uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address recipient, address token_addr) external returns (uint256 tokens_sold); // Trade ERC20 to Custom Pool function tokenToExchangeSwapInput(uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address exchange_addr) external returns (uint256 tokens_bought); function tokenToExchangeTransferInput(uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address recipient, address exchange_addr) external returns (uint256 tokens_bought); function tokenToExchangeSwapOutput(uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address exchange_addr) external returns (uint256 tokens_sold); function tokenToExchangeTransferOutput(uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address recipient, address exchange_addr) external returns (uint256 tokens_sold); // ERC20 comaptibility for liquidity tokens function name() external view returns(bytes32); function symbol() external view returns(bytes32); function decimals() external view returns(uint256); function transfer(address _to, uint256 _value) external returns (bool); function transferFrom(address _from, address _to, uint256 value) external returns (bool); function approve(address _spender, uint256 _value) external returns (bool); function allowance(address _owner, address _spender) external view returns (uint256); function balanceOf(address _owner) external view returns (uint256); function totalSupply() external view returns (uint256); // Never use function setup(address token_addr) external; } interface IBancorFormula { function calculatePurchaseReturn(uint256 _supply, uint256 _reserveBalance, uint32 _reserveRatio, uint256 _depositAmount) external view returns (uint256); function calculateSaleReturn(uint256 _supply, uint256 _reserveBalance, uint32 _reserveRatio, uint256 _sellAmount) external view returns (uint256); function calculateCrossReserveReturn(uint256 _fromReserveBalance, uint32 _fromReserveRatio, uint256 _toReserveBalance, uint32 _toReserveRatio, uint256 _amount) external view returns (uint256); function calculateFundCost(uint256 _supply, uint256 _reserveBalance, uint32 _totalRatio, uint256 _amount) external view returns (uint256); function calculateLiquidateReturn(uint256 _supply, uint256 _reserveBalance, uint32 _totalRatio, uint256 _amount) external view returns (uint256); } interface SmartTokenInterface { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); function disableTransfers(bool _disable) external; function issue(address _to, uint256 _amount) external; function destroy(address _from, uint256 _amount) external; function owner() external view returns (address); } interface IGetBancorData { function getBancorContractAddresByName(string calldata _name) external view returns (address result); function getBancorRatioForAssets(IERC20 _from, IERC20 _to, uint256 _amount) external view returns(uint256 result); function getBancorPathForAssets(IERC20 _from, IERC20 _to) external view returns(address[] memory); } interface BancorConverterInterfaceV2 { function addLiquidity(address _reserveToken, uint256 _amount, uint256 _minReturn) external payable; function removeLiquidity(address _poolToken, uint256 _amount, uint256 _minReturn) external; function poolToken(address _reserveToken) external view returns(address); function connectorTokenCount() external view returns (uint16); function connectorTokens(uint index) external view returns(IERC20); } interface BancorConverterInterfaceV1 { function addLiquidity( address[] calldata _reserveTokens, uint256[] calldata _reserveAmounts, uint256 _minReturn) external payable; function removeLiquidity( uint256 _amount, address[] calldata _reserveTokens, uint256[] calldata _reserveMinReturnAmounts) external; } interface BancorConverterInterface { function connectorTokens(uint index) external view returns(IERC20); function fund(uint256 _amount) external payable; function liquidate(uint256 _amount) external; function getConnectorBalance(IERC20 _connectorToken) external view returns (uint256); function connectorTokenCount() external view returns (uint16); } /* * This contract allow buy/sell pool for Bancor and Uniswap assets * and provide ratio and addition info for pool assets */ /* * @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 { } 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; } } /** * @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; } } /** * @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; } } contract PoolPortal is Ownable{ using SafeMath for uint256; uint public version = 4; IGetBancorData public bancorData; UniswapFactoryInterfaceV1 public uniswapFactoryV1; IUniswapV2Router public uniswapV2Router; // CoTrader platform recognize ETH by this address IERC20 constant private ETH_TOKEN_ADDRESS = IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); // Enum // NOTE: You can add a new type at the end, but do not change this order enum PortalType { Bancor, Uniswap, Balancer } // events event BuyPool(address poolToken, uint256 amount, address trader); event SellPool(address poolToken, uint256 amount, address trader); // Contract for handle tokens types ITokensTypeStorage public tokensTypes; /** * @dev contructor * * @param _bancorData address of helper contract GetBancorData * @param _uniswapFactoryV1 address of Uniswap V1 factory contract * @param _uniswapV2Router address of Uniswap V2 router * @param _tokensTypes address of the ITokensTypeStorage */ constructor( address _bancorData, address _uniswapFactoryV1, address _uniswapV2Router, address _tokensTypes ) public { bancorData = IGetBancorData(_bancorData); uniswapFactoryV1 = UniswapFactoryInterfaceV1(_uniswapFactoryV1); uniswapV2Router = IUniswapV2Router(_uniswapV2Router); tokensTypes = ITokensTypeStorage(_tokensTypes); } /** * @dev this function provide necessary data for buy a old BNT and UNI v1 pools by input amount * * @param _amount amount of pool token (NOTE: amount of ETH for Uniswap) * @param _type pool type * @param _poolToken pool token address */ function getDataForBuyingPool(IERC20 _poolToken, uint _type, uint256 _amount) public view returns( address[] memory connectorsAddress, uint256[] memory connectorsAmount ) { // Buy Bancor pool if(_type == uint(PortalType.Bancor)){ // get Bancor converter address converterAddress = getBacorConverterAddressByRelay(address(_poolToken), 0); // get converter as contract BancorConverterInterface converter = BancorConverterInterface(converterAddress); uint256 connectorsCount = converter.connectorTokenCount(); // create arrays for data connectorsAddress = new address[](connectorsCount); connectorsAmount = new uint256[](connectorsCount); // push data for(uint8 i = 0; i < connectorsCount; i++){ // get current connector address IERC20 currentConnector = converter.connectorTokens(i); // push address of current connector connectorsAddress[i] = address(currentConnector); // push amount for current connector connectorsAmount[i] = getBancorConnectorsAmountByRelayAmount( _amount, _poolToken, address(currentConnector)); } } // Buy Uniswap pool else if(_type == uint(PortalType.Uniswap)){ // get token address address tokenAddress = uniswapFactoryV1.getToken(address(_poolToken)); // get tokens amd approve to exchange uint256 erc20Amount = getUniswapTokenAmountByETH(tokenAddress, _amount); // return data connectorsAddress = new address[](2); connectorsAmount = new uint256[](2); connectorsAddress[0] = address(ETH_TOKEN_ADDRESS); connectorsAddress[1] = tokenAddress; connectorsAmount[0] = _amount; connectorsAmount[1] = erc20Amount; } else { revert("Unknown pool type"); } } /** * @dev buy Bancor or Uniswap pool * * @param _amount amount of pool token * @param _type pool type * @param _poolToken pool token address (NOTE: for Bancor type 2 don't forget extract pool address from container) * @param _connectorsAddress address of pool connectors (NOTE: for Uniswap ETH should be pass in [0], ERC20 in [1]) * @param _connectorsAmount amount of pool connectors (NOTE: for Uniswap ETH amount should be pass in [0], ERC20 in [1]) * @param _additionalArgs bytes32 array for case if need pass some extra params, can be empty * @param _additionalData for provide any additional data, if not used just set "0x", * for Bancor _additionalData[0] should be converterVersion and _additionalData[1] should be converterType * */ function buyPool ( uint256 _amount, uint _type, address _poolToken, address[] calldata _connectorsAddress, uint256[] calldata _connectorsAmount, bytes32[] calldata _additionalArgs, bytes calldata _additionalData ) external payable returns(uint256 poolAmountReceive, uint256[] memory connectorsSpended) { // Buy Bancor pool if(_type == uint(PortalType.Bancor)){ (poolAmountReceive) = buyBancorPool( _amount, _poolToken, _connectorsAddress, _connectorsAmount, _additionalArgs, _additionalData ); } // Buy Uniswap pool else if (_type == uint(PortalType.Uniswap)){ (poolAmountReceive) = buyUniswapPool( _amount, _poolToken, _connectorsAddress, _connectorsAmount, _additionalArgs, _additionalData ); } // Buy Balancer pool else if (_type == uint(PortalType.Balancer)){ (poolAmountReceive) = buyBalancerPool( _amount, _poolToken, _connectorsAddress, _connectorsAmount ); } else{ // unknown portal type revert("Unknown portal type"); } // transfer pool token to fund IERC20(_poolToken).transfer(msg.sender, poolAmountReceive); // transfer connectors remains to fund // and calculate how much connectors was spended (current - remains) connectorsSpended = _transferPoolConnectorsRemains( _connectorsAddress, _connectorsAmount); // trigger event emit BuyPool(address(_poolToken), poolAmountReceive, msg.sender); } /** * @dev helper for buying Bancor pool token by a certain converter version and converter type * Bancor has 3 cases for different converter version and type */ function buyBancorPool( uint256 _amount, address _poolToken, address[] calldata _connectorsAddress, uint256[] calldata _connectorsAmount, bytes32[] calldata _additionalArgs, bytes calldata _additionalData ) private returns(uint256 poolAmountReceive) { // get Bancor converter address by pool token and pool type address converterAddress = getBacorConverterAddressByRelay( _poolToken, uint256(_additionalArgs[1]) ); // transfer from sender and approve to converter // for detect if there are ETH in connectors or not we use etherAmount uint256 etherAmount = _approvePoolConnectors( _connectorsAddress, _connectorsAmount, converterAddress ); // Buy Bancor pool according converter version and type // encode and compare converter version if(uint256(_additionalArgs[0]) >= 28) { // encode and compare converter type if(uint256(_additionalArgs[1]) == 2) { // buy Bancor v2 case _buyBancorPoolV2( converterAddress, etherAmount, _connectorsAddress, _connectorsAmount, _additionalData ); } else{ // buy Bancor v1 case _buyBancorPoolV1( converterAddress, etherAmount, _connectorsAddress, _connectorsAmount, _additionalData ); } } else { // buy Bancor old v0 case _buyBancorPoolOldV( converterAddress, etherAmount, _amount ); } // get recieved pool amount poolAmountReceive = IERC20(_poolToken).balanceOf(address(this)); // make sure we recieved pool require(poolAmountReceive > 0, "ERR BNT pool received 0"); // set token type for this asset tokensTypes.addNewTokenType(_poolToken, "BANCOR_ASSET"); } /** * @dev helper for buy pool in Bancor network for old converter version */ function _buyBancorPoolOldV( address converterAddress, uint256 etherAmount, uint256 _amount) private { // get converter as contract BancorConverterInterface converter = BancorConverterInterface(converterAddress); // buy relay from converter if(etherAmount > 0){ // payable converter.fund.value(etherAmount)(_amount); }else{ // non payable converter.fund(_amount); } } /** * @dev helper for buy pool in Bancor network for new converter type 1 */ function _buyBancorPoolV1( address converterAddress, uint256 etherAmount, address[] calldata _connectorsAddress, uint256[] calldata _connectorsAmount, bytes memory _additionalData ) private { BancorConverterInterfaceV1 converter = BancorConverterInterfaceV1(converterAddress); // get additional data (uint256 minReturn) = abi.decode(_additionalData, (uint256)); // buy relay from converter if(etherAmount > 0){ // payable converter.addLiquidity.value(etherAmount)(_connectorsAddress, _connectorsAmount, minReturn); }else{ // non payable converter.addLiquidity(_connectorsAddress, _connectorsAmount, minReturn); } } /** * @dev helper for buy pool in Bancor network for new converter type 2 */ function _buyBancorPoolV2( address converterAddress, uint256 etherAmount, address[] calldata _connectorsAddress, uint256[] calldata _connectorsAmount, bytes memory _additionalData ) private { // get converter as contract BancorConverterInterfaceV2 converter = BancorConverterInterfaceV2(converterAddress); // get additional data (uint256 minReturn) = abi.decode(_additionalData, (uint256)); // buy relay from converter if(etherAmount > 0){ // payable converter.addLiquidity.value(etherAmount)(_connectorsAddress[0], _connectorsAmount[0], minReturn); }else{ // non payable converter.addLiquidity(_connectorsAddress[0], _connectorsAmount[0], minReturn); } } /** * @dev helper for buying Uniswap v1 or v2 pool */ function buyUniswapPool( uint256 _amount, address _poolToken, address[] calldata _connectorsAddress, uint256[] calldata _connectorsAmount, bytes32[] calldata _additionalArgs, bytes calldata _additionalData ) private returns(uint256 poolAmountReceive) { // define spender dependse of UNI pool version address spender = uint256(_additionalArgs[0]) == 1 ? _poolToken : address(uniswapV2Router); // approve pool tokens to Uni pool exchange _approvePoolConnectors( _connectorsAddress, _connectorsAmount, spender); // Buy Uni pool dependse of version if(uint256(_additionalArgs[0]) == 1){ _buyUniswapPoolV1( _poolToken, _connectorsAddress[1], // connector ERC20 token address _connectorsAmount[1], // connector ERC20 token amount _amount); }else{ _buyUniswapPoolV2( _poolToken, _connectorsAddress, _connectorsAmount, _additionalData ); } // get pool amount poolAmountReceive = IERC20(_poolToken).balanceOf(address(this)); // check if we recieved pool token require(poolAmountReceive > 0, "ERR UNI pool received 0"); } /** * @dev helper for buy pool in Uniswap network v1 * * @param _poolToken address of Uniswap exchange * @param _tokenAddress address of ERC20 conenctor * @param _erc20Amount amount of ERC20 connector * @param _ethAmount ETH amount (in wei) */ function _buyUniswapPoolV1( address _poolToken, address _tokenAddress, uint256 _erc20Amount, uint256 _ethAmount ) private { require(_ethAmount == msg.value, "Not enough ETH"); // get exchange contract UniswapExchangeInterface exchange = UniswapExchangeInterface(_poolToken); // set deadline uint256 deadline = now + 15 minutes; // buy pool exchange.addLiquidity.value(_ethAmount)( 1, _erc20Amount, deadline ); // Set token type tokensTypes.addNewTokenType(_poolToken, "UNISWAP_POOL"); } /** * @dev helper for buy pool in Uniswap network v2 */ function _buyUniswapPoolV2( address _poolToken, address[] calldata _connectorsAddress, uint256[] calldata _connectorsAmount, bytes calldata _additionalData ) private { // set deadline uint256 deadline = now + 15 minutes; // get additional data (uint256 amountAMinReturn, uint256 amountBMinReturn) = abi.decode(_additionalData, (uint256, uint256)); // Buy UNI V2 pool // ETH connector case if(_connectorsAddress[0] == address(ETH_TOKEN_ADDRESS)){ uniswapV2Router.addLiquidityETH.value(_connectorsAmount[0])( _connectorsAddress[1], _connectorsAmount[1], amountBMinReturn, amountAMinReturn, address(this), deadline ); } // ERC20 connector case else{ uniswapV2Router.addLiquidity( _connectorsAddress[0], _connectorsAddress[1], _connectorsAmount[0], _connectorsAmount[1], amountAMinReturn, amountBMinReturn, address(this), deadline ); } // Set token type tokensTypes.addNewTokenType(_poolToken, "UNISWAP_POOL_V2"); } /** * @dev helper for buying Balancer pool */ function buyBalancerPool( uint256 _amount, address _poolToken, address[] calldata _connectorsAddress, uint256[] calldata _connectorsAmount ) private returns(uint256 poolAmountReceive) { // approve pool tokens to Balancer pool exchange _approvePoolConnectors( _connectorsAddress, _connectorsAmount, _poolToken); // buy pool IBalancerPool(_poolToken).joinPool(_amount, _connectorsAmount); // get balance poolAmountReceive = IERC20(_poolToken).balanceOf(address(this)); // check require(poolAmountReceive > 0, "ERR BALANCER pool received 0"); // update type tokensTypes.addNewTokenType(_poolToken, "BALANCER_POOL"); } /** * @dev helper for buying BNT or UNI pools, approve connectors from msg.sender to spender address * return ETH amount if connectorsAddress contains ETH address */ function _approvePoolConnectors( address[] memory connectorsAddress, uint256[] memory connectorsAmount, address spender ) private returns(uint256 etherAmount) { // approve from portal to spender for(uint8 i = 0; i < connectorsAddress.length; i++){ if(connectorsAddress[i] != address(ETH_TOKEN_ADDRESS)){ // transfer from msg.sender and approve to _transferFromSenderAndApproveTo( IERC20(connectorsAddress[i]), connectorsAmount[i], spender); }else{ etherAmount = connectorsAmount[i]; } } } /** * @dev helper for buying BNT or UNI pools, transfer ERC20 tokens and ETH remains after bying pool, * if the balance is positive on this contract, and calculate how many assets was spent. */ function _transferPoolConnectorsRemains( address[] memory connectorsAddress, uint256[] memory currentConnectorsAmount ) private returns (uint256[] memory connectorsSpended) { // set length for connectorsSpended connectorsSpended = new uint256[](currentConnectorsAmount.length); // transfer connectors back to fund if some amount remains uint256 remains = 0; for(uint8 i = 0; i < connectorsAddress.length; i++){ // ERC20 case if(connectorsAddress[i] != address(ETH_TOKEN_ADDRESS)){ // check balance remains = IERC20(connectorsAddress[i]).balanceOf(address(this)); // transfer ERC20 if(remains > 0) IERC20(connectorsAddress[i]).transfer(msg.sender, remains); } // ETH case else { remains = address(this).balance; // transfer ETH if(remains > 0) (msg.sender).transfer(remains); } // calculate how many assets was spent connectorsSpended[i] = currentConnectorsAmount[i].sub(remains); } } /** * @dev return token ration in ETH in Uniswap network * * @param _token address of ERC20 token * @param _amount ETH amount */ function getUniswapTokenAmountByETH(address _token, uint256 _amount) public view returns(uint256) { UniswapExchangeInterface exchange = UniswapExchangeInterface( uniswapFactoryV1.getExchange(_token)); return exchange.getTokenToEthOutputPrice(_amount); } /** * @dev sell Bancor or Uniswap pool * * @param _amount amount of pool token * @param _type pool type * @param _poolToken pool token address * @param _additionalArgs bytes32 array for case if need pass some extra params, can be empty * @param _additionalData for provide any additional data, if not used just set "0x" */ function sellPool ( uint256 _amount, uint _type, IERC20 _poolToken, bytes32[] calldata _additionalArgs, bytes calldata _additionalData ) external returns( address[] memory connectorsAddress, uint256[] memory connectorsAmount ) { // sell Bancor Pool if(_type == uint(PortalType.Bancor)){ (connectorsAddress, connectorsAmount) = sellBancorPool( _amount, _poolToken, _additionalArgs, _additionalData); } // sell Uniswap pool else if (_type == uint(PortalType.Uniswap)){ (connectorsAddress, connectorsAmount) = sellUniswapPool( _poolToken, _amount, _additionalArgs, _additionalData); } // sell Balancer pool else if (_type == uint(PortalType.Balancer)){ (connectorsAddress, connectorsAmount) = sellBalancerPool( _amount, _poolToken, _additionalData); } else{ revert("Unknown portal type"); } emit SellPool(address(_poolToken), _amount, msg.sender); } /** * @dev helper for sell pool in Bancor network dependse of converter version and type */ function sellBancorPool( uint256 _amount, IERC20 _poolToken, bytes32[] calldata _additionalArgs, bytes calldata _additionalData ) private returns( address[] memory connectorsAddress, uint256[] memory connectorsAmount ) { // transfer pool from fund _poolToken.transferFrom(msg.sender, address(this), _amount); // get Bancor converter version and type uint256 bancorPoolVersion = uint256(_additionalArgs[0]); uint256 bancorConverterType = uint256(_additionalArgs[1]); // sell pool according converter version and type if(bancorPoolVersion >= 28){ // sell new Bancor v2 pool if(bancorConverterType == 2){ (connectorsAddress) = sellPoolViaBancorV2( _poolToken, _amount, _additionalData ); } // sell new Bancor v1 pool else{ (connectorsAddress) = sellPoolViaBancorV1(_poolToken, _amount, _additionalData); } } // sell old Bancor pool else{ (connectorsAddress) = sellPoolViaBancorOldV(_poolToken, _amount); } // transfer pool connectors back to fund connectorsAmount = transferConnectorsToSender(connectorsAddress); } /** * @dev helper for sell pool in Bancor network for old converter version * * @param _poolToken address of bancor relay * @param _amount amount of bancor relay */ function sellPoolViaBancorOldV(IERC20 _poolToken, uint256 _amount) private returns(address[] memory connectorsAddress) { // get Bancor Converter instance address converterAddress = getBacorConverterAddressByRelay(address(_poolToken), 0); BancorConverterInterface converter = BancorConverterInterface(converterAddress); // liquidate relay converter.liquidate(_amount); // return connectors addresses uint256 connectorsCount = converter.connectorTokenCount(); connectorsAddress = new address[](connectorsCount); for(uint8 i = 0; i<connectorsCount; i++){ connectorsAddress[i] = address(converter.connectorTokens(i)); } } /** * @dev helper for sell pool in Bancor network converter type v1 */ function sellPoolViaBancorV1( IERC20 _poolToken, uint256 _amount, bytes memory _additionalData ) private returns(address[] memory connectorsAddress) { // get Bancor Converter address address converterAddress = getBacorConverterAddressByRelay(address(_poolToken), 1); // get min returns uint256[] memory reserveMinReturnAmounts; // get connetor tokens data for remove liquidity (connectorsAddress, reserveMinReturnAmounts) = abi.decode(_additionalData, (address[], uint256[])); // get coneverter v1 contract BancorConverterInterfaceV1 converter = BancorConverterInterfaceV1(converterAddress); // remove liquidity (v1) converter.removeLiquidity(_amount, connectorsAddress, reserveMinReturnAmounts); } /** * @dev helper for sell pool in Bancor network converter type v2 */ function sellPoolViaBancorV2( IERC20 _poolToken, uint256 _amount, bytes calldata _additionalData ) private returns(address[] memory connectorsAddress) { // get Bancor Converter address address converterAddress = getBacorConverterAddressByRelay(address(_poolToken), 2); // get converter v2 contract BancorConverterInterfaceV2 converter = BancorConverterInterfaceV2(converterAddress); // get additional data uint256 minReturn; // get pool connectors (connectorsAddress, minReturn) = abi.decode(_additionalData, (address[], uint256)); // remove liquidity (v2) converter.removeLiquidity(address(_poolToken), _amount, minReturn); } /** * @dev helper for sell pool in Uniswap network for v1 and v2 */ function sellUniswapPool( IERC20 _poolToken, uint256 _amount, bytes32[] calldata _additionalArgs, bytes calldata _additionalData ) private returns( address[] memory connectorsAddress, uint256[] memory connectorsAmount ) { // define spender dependse of UNI pool version address spender = uint256(_additionalArgs[0]) == 1 ? address(_poolToken) : address(uniswapV2Router); // approve pool token _transferFromSenderAndApproveTo(_poolToken, _amount, spender); // sell Uni v1 or v2 pool if(uint256(_additionalArgs[0]) == 1){ (connectorsAddress) = sellPoolViaUniswapV1(_poolToken, _amount); }else{ (connectorsAddress) = sellPoolViaUniswapV2(_amount, _additionalData); } // transfer pool connectors back to fund connectorsAmount = transferConnectorsToSender(connectorsAddress); } /** * @dev helper for sell pool in Uniswap network v1 */ function sellPoolViaUniswapV1( IERC20 _poolToken, uint256 _amount ) private returns(address[] memory connectorsAddress) { // get token by pool token address tokenAddress = uniswapFactoryV1.getToken(address(_poolToken)); // check if such a pool exist if(tokenAddress != address(0x0000000000000000000000000000000000000000)){ // get UNI exchane UniswapExchangeInterface exchange = UniswapExchangeInterface(address(_poolToken)); // get min returns (uint256 minEthAmount, uint256 minErcAmount) = getUniswapConnectorsAmountByPoolAmount(_amount, address(_poolToken)); // set deadline uint256 deadline = now + 15 minutes; // liquidate exchange.removeLiquidity( _amount, minEthAmount, minErcAmount, deadline); // return data connectorsAddress = new address[](2); connectorsAddress[0] = address(ETH_TOKEN_ADDRESS); connectorsAddress[1] = tokenAddress; } else{ revert("Not exist UNI v1 pool"); } } /** * @dev helper for sell pool in Uniswap network v2 */ function sellPoolViaUniswapV2( uint256 _amount, bytes calldata _additionalData ) private returns(address[] memory connectorsAddress) { // get additional data uint256 minReturnA; uint256 minReturnB; // get connectors and min return from bytes (connectorsAddress, minReturnA, minReturnB) = abi.decode(_additionalData, (address[], uint256, uint256)); // get deadline uint256 deadline = now + 15 minutes; // sell pool with include eth connector if(connectorsAddress[0] == address(ETH_TOKEN_ADDRESS)){ uniswapV2Router.removeLiquidityETH( connectorsAddress[1], _amount, minReturnB, minReturnA, address(this), deadline ); } // sell pool only with erc20 connectors else{ uniswapV2Router.removeLiquidity( connectorsAddress[0], connectorsAddress[1], _amount, minReturnA, minReturnB, address(this), deadline ); } } /** * @dev helper for sell Balancer pool */ function sellBalancerPool( uint256 _amount, IERC20 _poolToken, bytes calldata _additionalData ) private returns( address[] memory connectorsAddress, uint256[] memory connectorsAmount ) { // get additional data uint256[] memory minConnectorsAmount; (connectorsAddress, minConnectorsAmount) = abi.decode(_additionalData, (address[], uint256[])); // approve pool _transferFromSenderAndApproveTo( _poolToken, _amount, address(_poolToken)); // sell pool IBalancerPool(address(_poolToken)).exitPool(_amount, minConnectorsAmount); // transfer connectors back to fund connectorsAmount = transferConnectorsToSender(connectorsAddress); } /** * @dev helper for sell Bancor and Uniswap pools * transfer pool connectors from sold pool back to sender * return array with amount of recieved connectors */ function transferConnectorsToSender(address[] memory connectorsAddress) private returns(uint256[] memory connectorsAmount) { // define connectors amount length connectorsAmount = new uint256[](connectorsAddress.length); uint256 received = 0; // transfer connectors back to fund for(uint8 i = 0; i < connectorsAddress.length; i++){ // ETH case if(connectorsAddress[i] == address(ETH_TOKEN_ADDRESS)){ // update ETH data received = address(this).balance; connectorsAmount[i] = received; // tarnsfer ETH if(received > 0) payable(msg.sender).transfer(received); } // ERC20 case else{ // update ERC20 data received = IERC20(connectorsAddress[i]).balanceOf(address(this)); connectorsAmount[i] = received; // transfer ERC20 if(received > 0) IERC20(connectorsAddress[i]).transfer(msg.sender, received); } } } /** * @dev helper for get bancor converter by bancor relay addrses * * @param _relay address of bancor relay * @param _poolType bancor pool type */ function getBacorConverterAddressByRelay(address _relay, uint256 _poolType) public view returns(address converter) { if(_poolType == 2){ address smartTokenContainer = SmartTokenInterface(_relay).owner(); converter = SmartTokenInterface(smartTokenContainer).owner(); }else{ converter = SmartTokenInterface(_relay).owner(); } } /** * @dev return ERC20 address from Uniswap exchange address * * @param _exchange address of uniswap exchane */ function getTokenByUniswapExchange(address _exchange) external view returns(address) { return uniswapFactoryV1.getToken(_exchange); } /** * @dev helper for get amounts for both Uniswap connectors for input amount of pool * * @param _amount relay amount * @param _exchange address of uniswap exchane */ function getUniswapConnectorsAmountByPoolAmount( uint256 _amount, address _exchange ) public view returns(uint256 ethAmount, uint256 ercAmount) { IERC20 token = IERC20(uniswapFactoryV1.getToken(_exchange)); // total_liquidity exchange.totalSupply uint256 totalLiquidity = UniswapExchangeInterface(_exchange).totalSupply(); // ethAmount = amount * exchane.eth.balance / total_liquidity ethAmount = _amount.mul(_exchange.balance).div(totalLiquidity); // ercAmount = amount * token.balanceOf(exchane) / total_liquidity ercAmount = _amount.mul(token.balanceOf(_exchange)).div(totalLiquidity); } /** * @dev helper for get amounts for both Uniswap connectors for input amount of pool * for Uniswap version 2 * * @param _amount pool amount * @param _exchange address of uniswap exchane */ function getUniswapV2ConnectorsAmountByPoolAmount( uint256 _amount, address _exchange ) public view returns( uint256 tokenAmountOne, uint256 tokenAmountTwo, address tokenAddressOne, address tokenAddressTwo ) { tokenAddressOne = IUniswapV2Pair(_exchange).token0(); tokenAddressTwo = IUniswapV2Pair(_exchange).token1(); // total_liquidity exchange.totalSupply uint256 totalLiquidity = IERC20(_exchange).totalSupply(); // ethAmount = amount * exchane.eth.balance / total_liquidity tokenAmountOne = _amount.mul(IERC20(tokenAddressOne).balanceOf(_exchange)).div(totalLiquidity); // ercAmount = amount * token.balanceOf(exchane) / total_liquidity tokenAmountTwo = _amount.mul(IERC20(tokenAddressTwo).balanceOf(_exchange)).div(totalLiquidity); } /** * @dev helper for get amounts all Balancer connectors for input amount of pool * for Balancer * * step 1 get all tokens * step 2 get user amount from each token by a user pool share * * @param _amount pool amount * @param _pool address of balancer pool */ function getBalancerConnectorsAmountByPoolAmount( uint256 _amount, address _pool ) public view returns( address[] memory tokens, uint256[] memory tokensAmount ) { IBalancerPool balancerPool = IBalancerPool(_pool); // get all pool tokens tokens = balancerPool.getCurrentTokens(); // set tokens amount length tokensAmount = new uint256[](tokens.length); // get total pool shares uint256 totalShares = IERC20(_pool).totalSupply(); // calculate all tokens from the pool for(uint i = 0; i < tokens.length; i++){ // get a certain total token amount in pool uint256 totalTokenAmount = IERC20(tokens[i]).balanceOf(_pool); // get a certain pool share (_amount) from a certain token amount in pool tokensAmount[i] = totalTokenAmount.mul(_amount).div(totalShares); } } /** * @dev helper for get value in pool for a certain connector address * * @param _amount relay amount * @param _relay address of bancor relay * @param _connector address of relay connector */ function getBancorConnectorsAmountByRelayAmount ( uint256 _amount, IERC20 _relay, address _connector ) public view returns(uint256 connectorAmount) { // get converter contract BancorConverterInterface converter = BancorConverterInterface( SmartTokenInterface(address(_relay)).owner()); // get connector balance uint256 connectorBalance = converter.getConnectorBalance(IERC20(_connector)); // get bancor formula contract IBancorFormula bancorFormula = IBancorFormula( bancorData.getBancorContractAddresByName("BancorFormula")); // calculate input connectorAmount = bancorFormula.calculateFundCost( _relay.totalSupply(), connectorBalance, 1000000, _amount); } /** * @dev helper for get Bancor ERC20 connectors addresses for old Bancor version * * @param _relay address of bancor relay */ function getBancorConnectorsByRelay(address _relay) public view returns( IERC20[] memory connectors ) { address converterAddress = getBacorConverterAddressByRelay(_relay, 0); BancorConverterInterface converter = BancorConverterInterface(converterAddress); uint256 connectorTokenCount = converter.connectorTokenCount(); connectors = new IERC20[](connectorTokenCount); for(uint8 i; i < connectorTokenCount; i++){ connectors[i] = converter.connectorTokens(i); } } /** * @dev helper for get ratio between assets in bancor newtork * * @param _from token or relay address * @param _to token or relay address * @param _amount amount from */ function getBancorRatio(address _from, address _to, uint256 _amount) external view returns(uint256) { // return Bancor ratio return bancorData.getBancorRatioForAssets(IERC20(_from), IERC20(_to), _amount); } // owner of portal can change getBancorData helper, for case if Bancor do some major updates function setNewGetBancorData(address _bancorData) public onlyOwner { bancorData = IGetBancorData(_bancorData); } /** * @dev Transfers tokens to this contract and approves them to another address * * @param _source Token to transfer and approve * @param _sourceAmount The amount to transfer and approve (in _source token) * @param _to Address to approve to */ function _transferFromSenderAndApproveTo(IERC20 _source, uint256 _sourceAmount, address _to) private { require(_source.transferFrom(msg.sender, address(this), _sourceAmount)); // reset previous approve (some ERC20 not allow do new approve if already approved) _source.approve(_to, 0); // approve _source.approve(_to, _sourceAmount); } // fallback payable function to receive ether from other contract addresses fallback() external payable {} }
* @dev helper for get ratio between assets in bancor newtork @param _from token or relay address @param _to token or relay address @param _amount amount from/ return Bancor ratio
function getBancorRatio(address _from, address _to, uint256 _amount) external view returns(uint256) { return bancorData.getBancorRatioForAssets(IERC20(_from), IERC20(_to), _amount); }
6,512,888
[ 1, 4759, 364, 336, 7169, 3086, 7176, 316, 25732, 3850, 394, 88, 778, 225, 389, 2080, 1377, 1147, 578, 18874, 1758, 225, 389, 869, 3639, 1147, 578, 18874, 1758, 225, 389, 8949, 565, 3844, 628, 19, 327, 605, 304, 3850, 7169, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 2882, 304, 3850, 8541, 12, 2867, 389, 2080, 16, 1758, 389, 869, 16, 2254, 5034, 389, 8949, 13, 203, 225, 3903, 203, 225, 1476, 203, 225, 1135, 12, 11890, 5034, 13, 203, 225, 288, 203, 565, 327, 25732, 3850, 751, 18, 588, 38, 304, 3850, 8541, 1290, 10726, 12, 45, 654, 39, 3462, 24899, 2080, 3631, 467, 654, 39, 3462, 24899, 869, 3631, 389, 8949, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.18; // ---------------------------------------------------------------------------- // 'TootyrCrowdSale' CROWDSALE token contract // // Deployed to : 0xeD973527645324Ed6C649f92C3b5d7C01D42fb60 // Symbol : TRT // Name : TootyrToken // Total supply: 100000000 // Decimals : 18 // // Better Education Better World. // // (c) by David Blackmore / Toronto Canada // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // 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 view returns (uint); function balanceOf(address tokenOwner) public view returns (uint balance); function allowance(address tokenOwner, address spender) public view 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 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); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ---------------------------------------------------------------------------- contract TootyrCrowdSale is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; uint public startDate; uint public bonusEnds; uint public endDate; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function TootyrCrowdSale() public { symbol = "TRT"; name = "TootyrToken"; decimals = 18; bonusEnds = now + 16 weeks; endDate = now + 21 weeks; } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public view returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public view 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 returns (bool success) { 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 returns (bool success) { 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 returns (bool success) { 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 view 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; } // ------------------------------------------------------------------------ // 10,000 TRT Tokens per 1 ETH // ------------------------------------------------------------------------ function () public payable { require(now >= startDate && now <= endDate); uint tokens; if (now <= bonusEnds) { tokens = msg.value * 13000; } else { tokens = msg.value * 10000; } balances[msg.sender] = safeAdd(balances[msg.sender], tokens); _totalSupply = safeAdd(_totalSupply, tokens); Transfer(address(0), msg.sender, tokens); owner.transfer(msg.value); } // ------------------------------------------------------------------------ // 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); } }
---------------------------------------------------------------------------- ERC20 Token, with the addition of symbol, name and decimals and assisted token transfers ---------------------------------------------------------------------------- ------------------------------------------------------------------------ Constructor ------------------------------------------------------------------------
contract TootyrCrowdSale is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; uint public startDate; uint public bonusEnds; uint public endDate; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; function TootyrCrowdSale() public { symbol = "TRT"; name = "TootyrToken"; decimals = 18; bonusEnds = now + 16 weeks; endDate = now + 21 weeks; } function totalSupply() public view returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } function transferFrom(address from, address to, uint tokens) public returns (bool success) { 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; } function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } 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; } function () public payable { require(now >= startDate && now <= endDate); uint tokens; if (now <= bonusEnds) { tokens = msg.value * 13000; tokens = msg.value * 10000; } balances[msg.sender] = safeAdd(balances[msg.sender], tokens); _totalSupply = safeAdd(_totalSupply, tokens); Transfer(address(0), msg.sender, tokens); owner.transfer(msg.value); } function () public payable { require(now >= startDate && now <= endDate); uint tokens; if (now <= bonusEnds) { tokens = msg.value * 13000; tokens = msg.value * 10000; } balances[msg.sender] = safeAdd(balances[msg.sender], tokens); _totalSupply = safeAdd(_totalSupply, tokens); Transfer(address(0), msg.sender, tokens); owner.transfer(msg.value); } } else { function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
10,430,904
[ 1, 5802, 7620, 4232, 39, 3462, 3155, 16, 598, 326, 2719, 434, 3273, 16, 508, 471, 15105, 471, 1551, 25444, 1147, 29375, 8879, 13849, 8879, 17082, 11417, 8879, 17082, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 399, 1632, 30468, 39, 492, 72, 30746, 353, 4232, 39, 3462, 1358, 16, 14223, 11748, 16, 14060, 10477, 288, 203, 565, 533, 1071, 3273, 31, 203, 565, 533, 1071, 225, 508, 31, 203, 565, 2254, 28, 1071, 15105, 31, 203, 565, 2254, 1071, 389, 4963, 3088, 1283, 31, 203, 565, 2254, 1071, 12572, 31, 203, 565, 2254, 1071, 324, 22889, 24980, 31, 203, 565, 2254, 1071, 13202, 31, 203, 203, 565, 2874, 12, 2867, 516, 2254, 13, 324, 26488, 31, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 3719, 2935, 31, 203, 203, 203, 565, 445, 399, 1632, 30468, 39, 492, 72, 30746, 1435, 1071, 288, 203, 3639, 3273, 273, 315, 4349, 56, 14432, 203, 3639, 508, 273, 315, 774, 352, 30468, 1345, 14432, 203, 3639, 15105, 273, 6549, 31, 203, 3639, 324, 22889, 24980, 273, 2037, 397, 2872, 17314, 31, 203, 3639, 13202, 273, 2037, 397, 9035, 17314, 31, 203, 203, 565, 289, 203, 203, 203, 565, 445, 2078, 3088, 1283, 1435, 1071, 1476, 1135, 261, 11890, 13, 288, 203, 3639, 327, 389, 4963, 3088, 1283, 300, 324, 26488, 63, 2867, 12, 20, 13, 15533, 203, 565, 289, 203, 203, 203, 565, 445, 11013, 951, 12, 2867, 1147, 5541, 13, 1071, 1476, 1135, 261, 11890, 11013, 13, 288, 203, 3639, 327, 324, 26488, 63, 2316, 5541, 15533, 203, 565, 289, 203, 203, 203, 565, 445, 7412, 12, 2867, 358, 16, 2254, 2430, 13, 1071, 1135, 261, 6430, 2216, 13, 288, 203, 3639, 324, 26488, 63, 3576, 18, 15330, 65, 2 ]
./full_match/97/0x278F790FC5f1A7a438bca43253e02d40f7835e1e/sources/MakaContract.sol
This function is used to enable all functions of the contract, after the setup of the token sale (e.g. Liquidity) is completed
function onActivated() internal override { super.onActivated(); setRewardAsTokensEnabled(true); setAutoClaimEnabled(true); setReimburseAfterMakaClaimFailure(true); _lastBurnDate = block.timestamp; }
5,033,316
[ 1, 2503, 445, 353, 1399, 358, 4237, 777, 4186, 434, 326, 6835, 16, 1839, 326, 3875, 434, 326, 1147, 272, 5349, 261, 73, 18, 75, 18, 511, 18988, 24237, 13, 353, 5951, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 603, 28724, 1435, 2713, 3849, 288, 203, 202, 202, 9565, 18, 265, 28724, 5621, 203, 203, 202, 202, 542, 17631, 1060, 1463, 5157, 1526, 12, 3767, 1769, 203, 202, 202, 542, 4965, 9762, 1526, 12, 3767, 1769, 203, 202, 202, 542, 426, 381, 70, 295, 307, 4436, 49, 581, 69, 9762, 5247, 12, 3767, 1769, 203, 202, 202, 67, 2722, 38, 321, 1626, 273, 1203, 18, 5508, 31, 203, 202, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xfdaFc9d1902f4e0b84f65F49f244b32b31013b74/sources/src/ComposableCoW.sol
An event emitted when a user sets their merkle root
event MerkleRootSet(address indexed owner, bytes32 root, Proof proof);
3,132,790
[ 1, 979, 871, 17826, 1347, 279, 729, 1678, 3675, 30235, 1365, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 871, 31827, 2375, 694, 12, 2867, 8808, 3410, 16, 1731, 1578, 1365, 16, 1186, 792, 14601, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x119C7Ee43Ebf1dEDc45A3730735583Bd39E32579/sources/contracts/operators/CollectionBatchBuyOperator.sol
Maximum amount this crowdfund will pay for an NFT. Minimum number of tokens that must be purchased. If this limit is not reached, the batch buy will fail. Minimum amount of ETH that must be used to buy the tokens. If this amount is not reached, the batch buy will fail.
struct CollectionBatchBuyOperationData { IERC721 nftContract; bytes32 nftTokenIdsMerkleRoot; uint256 maximumPrice; uint256 minTokensBought; uint256 minTotalEthUsed; }
17,001,921
[ 1, 13528, 3844, 333, 276, 492, 2180, 1074, 903, 8843, 364, 392, 423, 4464, 18, 23456, 1300, 434, 2430, 716, 1297, 506, 5405, 343, 8905, 18, 971, 333, 1800, 353, 486, 8675, 16, 326, 2581, 30143, 903, 2321, 18, 23456, 3844, 434, 512, 2455, 716, 1297, 506, 1399, 358, 30143, 326, 2430, 18, 971, 333, 3844, 353, 486, 8675, 16, 326, 2581, 30143, 903, 2321, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1958, 2200, 4497, 38, 9835, 2988, 751, 288, 203, 3639, 467, 654, 39, 27, 5340, 290, 1222, 8924, 31, 203, 3639, 1731, 1578, 290, 1222, 1345, 2673, 8478, 15609, 2375, 31, 203, 3639, 2254, 5034, 4207, 5147, 31, 203, 3639, 2254, 5034, 1131, 5157, 13809, 9540, 31, 203, 3639, 2254, 5034, 1131, 5269, 41, 451, 6668, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/77/0x914330F413E95598FE9FA9e2F4d4472c039113ab/sources/contracts/SelectorTokenGasLimiterManager.sol
* @dev Throws if called through proxy by any account other than contract itself or an upgradeability owner./
modifier onlyRelevantSender() { (bool isProxy, bytes memory returnData) = address(this).call(abi.encodeWithSelector(UPGRADEABILITY_OWNER)); require( ); _; }
5,049,161
[ 1, 21845, 309, 2566, 3059, 2889, 635, 1281, 2236, 1308, 2353, 6835, 6174, 578, 392, 8400, 2967, 3410, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 9606, 1338, 17018, 7445, 12021, 1435, 288, 203, 3639, 261, 6430, 353, 3886, 16, 1731, 3778, 327, 751, 13, 273, 1758, 12, 2211, 2934, 1991, 12, 21457, 18, 3015, 1190, 4320, 12, 3079, 24554, 1639, 22879, 67, 29602, 10019, 203, 3639, 2583, 12, 203, 3639, 11272, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma experimental ABIEncoderV2; pragma solidity 0.6.4; // SPDX-License-Identifier: MIT library EthAddressLib { /** * @dev returns the address used within the protocol to identify ETH * @return the address assigned to ETH */ function ethAddress() internal pure returns (address) { return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; } } // SPDX-License-Identifier: MIT /** * @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; } function min(uint256 a, uint256 b) internal pure returns (uint256) { return a <= b ? a : b; } function abs(uint256 a, uint256 b) internal pure returns (uint256) { if (a < b) { return b - a; } return a - b; } } // SPDX-License-Identifier: MIT contract Exponential { uint256 constant expScale = 1e18; uint256 constant doubleScale = 1e36; uint256 constant halfExpScale = expScale / 2; using SafeMath for uint256; function getExp(uint256 num, uint256 denom) public pure returns (uint256 rational) { rational = num.mul(expScale).div(denom); } function getDiv(uint256 num, uint256 denom) public pure returns (uint256 rational) { rational = num.mul(expScale).div(denom); } function addExp(uint256 a, uint256 b) public pure returns (uint256 result) { result = a.add(b); } function subExp(uint256 a, uint256 b) public pure returns (uint256 result) { result = a.sub(b); } function mulExp(uint256 a, uint256 b) public pure returns (uint256) { uint256 doubleScaledProduct = a.mul(b); uint256 doubleScaledProductWithHalfScale = halfExpScale.add( doubleScaledProduct ); return doubleScaledProductWithHalfScale.div(expScale); } function divExp(uint256 a, uint256 b) public pure returns (uint256) { return getDiv(a, b); } function mulExp3( uint256 a, uint256 b, uint256 c ) public pure returns (uint256) { return mulExp(mulExp(a, b), c); } function mulScalar(uint256 a, uint256 scalar) public pure returns (uint256 scaled) { scaled = a.mul(scalar); } function mulScalarTruncate(uint256 a, uint256 scalar) public pure returns (uint256) { uint256 product = mulScalar(a, scalar); return truncate(product); } function mulScalarTruncateAddUInt( uint256 a, uint256 scalar, uint256 addend ) public pure returns (uint256) { uint256 product = mulScalar(a, scalar); return truncate(product).add(addend); } function divScalarByExpTruncate(uint256 scalar, uint256 divisor) public pure returns (uint256) { uint256 fraction = divScalarByExp(scalar, divisor); return truncate(fraction); } function divScalarByExp(uint256 scalar, uint256 divisor) public pure returns (uint256) { uint256 numerator = expScale.mul(scalar); return getExp(numerator, divisor); } function divScalar(uint256 a, uint256 scalar) public pure returns (uint256) { return a.div(scalar); } function truncate(uint256 exp) public pure returns (uint256) { return exp.div(expScale); } } // SPDX-License-Identifier: MIT /** * @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. */ function decimals() external view returns (uint8); event Approval( address indexed owner, address indexed spender, uint256 value ); } // SPDX-License-Identifier: MIT interface IFToken is IERC20 { function mint(address user, uint256 amount) external returns (bytes memory); function borrow(address borrower, uint256 borrowAmount) external returns (bytes memory); function withdraw( address payable withdrawer, uint256 withdrawTokensIn, uint256 withdrawAmountIn ) external returns (uint256, bytes memory); function underlying() external view returns (address); function accrueInterest() external; function getAccountState(address account) external view returns ( uint256, uint256, uint256 ); function MonitorEventCallback( address who, bytes32 funcName, bytes calldata payload ) external; //用户存借取还操作后的兑换率 function exchangeRateCurrent() external view returns (uint256 exchangeRate); function repay(address borrower, uint256 repayAmount) external returns (uint256, bytes memory); function borrowBalanceStored(address account) external view returns (uint256); function exchangeRateStored() external view returns (uint256 exchangeRate); function liquidateBorrow( address liquidator, address borrower, uint256 repayAmount, address fTokenCollateral ) external returns (bytes memory); function borrowBalanceCurrent(address account) external returns (uint256); function balanceOfUnderlying(address owner) external returns (uint256); function _reduceReserves(uint256 reduceAmount) external; function _addReservesFresh(uint256 addAmount) external; function cancellingOut(address striker) external returns (bool strikeOk, bytes memory strikeLog); function APR() external view returns (uint256); function APY() external view returns (uint256); function calcBalanceOfUnderlying(address owner) external view returns (uint256); function borrowSafeRatio() external view returns (uint256); function tokenCash(address token, address account) external view returns (uint256); function getBorrowRate() external view returns (uint256); function addTotalCash(uint256 _addAmount) external; function subTotalCash(uint256 _subAmount) external; function totalCash() external view returns (uint256); function totalReserves() external view returns (uint256); function totalBorrows() external view returns (uint256); } // SPDX-License-Identifier: MIT interface IOracle { function get(address token) external view returns (uint256, bool); } // SPDX-License-Identifier: MIT /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require( address(this).balance >= amount, "Address: insufficient balance" ); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(""); require( success, "Address: unable to send value, recipient may have reverted" ); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, "Address: low-level call with value failed" ); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, "Address: insufficient balance for call" ); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue( address target, bytes memory data, uint256 weiValue, string memory errorMessage ) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{value: weiValue}( data ); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT /** * @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 enum RewardType { DefaultType, Deposit, Borrow, Withdraw, Repay, Liquidation, TokenIn, //入金,为还款和存款的组合 TokenOut //出金, 为取款和借款的组合 } // SPDX-License-Identifier: MIT interface IBank { function MonitorEventCallback(bytes32 funcName, bytes calldata payload) external; function deposit(address token, uint256 amount) external payable; function borrow(address token, uint256 amount) external; function withdraw(address underlying, uint256 withdrawTokens) external; function withdrawUnderlying(address underlying, uint256 amount) external; function repay(address token, uint256 amount) external payable; function liquidateBorrow( address borrower, address underlyingBorrow, address underlyingCollateral, uint256 repayAmount ) external payable; function tokenIn(address token, uint256 amountIn) external payable; function tokenOut(address token, uint256 amountOut) external; function cancellingOut(address token) external; function paused() external view returns (bool); } // reward token pool interface (FOR) interface IRewardPool { function theForceToken() external view returns (address); function bankController() external view returns (address); function admin() external view returns (address); function deposit(uint256 amount) external; function withdraw(uint256 amount) external; function withdraw() external; function setTheForceToken(address _theForceToken) external; function setBankController(address _bankController) external; function reward(address who, uint256 amount) external; } /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // SPDX-License-Identifier: MIT contract BankController is Exponential, Initializable { using SafeERC20 for IERC20; using SafeMath for uint256; struct Market { // 原生币种对应的 fToken 地址 address fTokenAddress; // 币种是否可用 bool isValid; // 该币种所拥有的质押能力 uint256 collateralAbility; // 市场所参与的用户 mapping(address => bool) accountsIn; // 该币种的清算奖励 uint256 liquidationIncentive; } // 原生币种地址 => 币种信息 mapping(address => Market) public markets; address public bankEntryAddress; // bank主合约入口地址 address public theForceToken; // 奖励的FOR token地址 //返利百分比,根据用户存,借,取,还花费的gas返还对应价值比例的奖励token, 奖励FOR数量 = ETH价值 * rewardFactor / price(for), 1e18 scale mapping(uint256 => uint256) public rewardFactors; // RewardType ==> rewardFactor (1e18 scale); // 用户地址 =》 币种地址(用户参与的币种) mapping(address => IFToken[]) public accountAssets; IFToken[] public allMarkets; address[] public allUnderlyingMarkets; IOracle public oracle; address public mulsig; //FIXME: 统一权限管理 modifier auth { require( msg.sender == admin || msg.sender == bankEntryAddress, "msg.sender need admin or bank" ); _; } function setBankEntryAddress(address _newBank) external auth { bankEntryAddress = _newBank; } function setTheForceToken(address _theForceToken) external auth { theForceToken = _theForceToken; } function setRewardFactorByType(uint256 rewaradType, uint256 factor) external auth { rewardFactors[rewaradType] = factor; } function marketsContains(address fToken) public view returns (bool) { uint256 len = allMarkets.length; for (uint256 i = 0; i < len; ++i) { if (address(allMarkets[i]) == fToken) { return true; } } return false; } uint256 public closeFactor; address public admin; address public proposedAdmin; // 将FOR奖励池单独放到另外一个合约中 address public rewardPool; uint256 public transferEthGasCost; // @notice Borrow caps enforced by borrowAllowed for each token address. Defaults to zero which corresponds to unlimited borrowing. mapping(address => uint) public borrowCaps; // @notice Supply caps enforced by mintAllowed for each token address. Defaults to zero which corresponds to unlimited supplying. mapping(address => uint) public supplyCaps; // 原生token的存,借,取,取,还和清算配置设置 struct TokenConfig { bool depositDisabled; //存款:true:禁用,false: 启用 bool borrowDisabled;// 借款 bool withdrawDisabled;// 取款 bool repayDisabled; //还款 bool liquidateBorrowDisabled;//清算 } //underlying => TokenConfig mapping (address => TokenConfig) public tokenConfigs; // _setMarketBorrowSupplyCaps = _setMarketBorrowCaps + _setMarketSupplyCaps function _setMarketBorrowSupplyCaps(address[] calldata tokens, uint[] calldata newBorrowCaps, uint[] calldata newSupplyCaps) external { require(msg.sender == admin, "only admin can set borrow/supply caps"); uint numMarkets = tokens.length; uint numBorrowCaps = newBorrowCaps.length; uint numSupplyCaps = newSupplyCaps.length; require(numMarkets != 0 && numMarkets == numBorrowCaps && numMarkets == numSupplyCaps, "invalid input"); for(uint i = 0; i < numMarkets; i++) { borrowCaps[tokens[i]] = newBorrowCaps[i]; supplyCaps[tokens[i]] = newSupplyCaps[i]; } } function setTokenConfig( address t, bool _depositDisabled, bool _borrowDisabled, bool _withdrawDisabled, bool _repayDisabled, bool _liquidateBorrowDisabled) external { require(msg.sender == admin, "only admin can set token configs"); tokenConfigs[t] = TokenConfig( _depositDisabled, _borrowDisabled, _withdrawDisabled, _repayDisabled, _liquidateBorrowDisabled ); } function initialize(address _mulsig) public initializer { admin = msg.sender; mulsig = _mulsig; transferEthGasCost = 5000; } modifier onlyMulSig { require(msg.sender == mulsig, "require admin"); _; } modifier onlyAdmin { require(msg.sender == admin, "require admin"); _; } modifier onlyFToken(address fToken) { require(marketsContains(fToken), "only supported fToken"); _; } event AddTokenToMarket(address underlying, address fToken); function proposeNewAdmin(address admin_) external onlyMulSig { proposedAdmin = admin_; } function claimAdministration() external { require(msg.sender == proposedAdmin, "Not proposed admin."); admin = proposedAdmin; proposedAdmin = address(0); } // 获取原生 token 对应的 fToken 地址 function getFTokeAddress(address underlying) public view returns (address) { return markets[underlying].fTokenAddress; } /** * @notice Returns the assets an account has entered 返回该账户已经参与的币种 * @param account The address of the account to pull assets for * @return A dynamic list with the assets the account has entered */ function getAssetsIn(address account) external view returns (IFToken[] memory) { IFToken[] memory assetsIn = accountAssets[account]; return assetsIn; } function checkAccountsIn(address account, IFToken fToken) external view returns (bool) { return markets[IFToken(address(fToken)).underlying()].accountsIn[account]; } function userEnterMarket(IFToken fToken, address borrower) internal { Market storage marketToJoin = markets[fToken.underlying()]; require(marketToJoin.isValid, "Market not valid"); if (marketToJoin.accountsIn[borrower]) { return; } marketToJoin.accountsIn[borrower] = true; accountAssets[borrower].push(fToken); } function transferCheck( address fToken, address src, address dst, uint256 transferTokens ) external onlyFToken(msg.sender) { withdrawCheck(fToken, src, transferTokens); userEnterMarket(IFToken(fToken), dst); } function withdrawCheck( address fToken, address withdrawer, uint256 withdrawTokens ) public view returns (uint256) { address underlying = IFToken(fToken).underlying(); require( markets[underlying].isValid, "Market not valid" ); require(!tokenConfigs[underlying].withdrawDisabled, "withdraw disabled"); (uint256 sumCollaterals, uint256 sumBorrows) = getUserLiquidity( withdrawer, IFToken(fToken), withdrawTokens, 0 ); require(sumCollaterals >= sumBorrows, "Cannot withdraw tokens"); } // 接收转账 function transferIn( address account, address underlying, uint256 amount ) public payable { require(msg.sender == bankEntryAddress || msg.sender == account, "auth failed"); if (underlying != EthAddressLib.ethAddress()) { require(msg.value == 0, "ERC20 do not accecpt ETH."); uint256 balanceBefore = IERC20(underlying).balanceOf(address(this)); IERC20(underlying).safeTransferFrom(account, address(this), amount); uint256 balanceAfter = IERC20(underlying).balanceOf(address(this)); require( balanceAfter - balanceBefore == amount, "TransferIn amount not valid" ); // erc 20 => transferFrom } else { // 接收 eth 转账,已经通过 payable 转入 require(msg.value >= amount, "Eth value is not enough"); if (msg.value > amount) { //send back excess ETH uint256 excessAmount = msg.value.sub(amount); //solium-disable-next-line (bool result, ) = account.call{ value: excessAmount, gas: transferEthGasCost }(""); require(result, "Transfer of ETH failed"); } } } // 向用户转账 function transferToUser( address underlying, address payable account, uint256 amount ) external onlyFToken(msg.sender) { require( markets[IFToken(msg.sender).underlying()].isValid, "TransferToUser not allowed" ); transferToUserInternal(underlying, account, amount); } function transferToUserInternal( address underlying, address payable account, uint256 amount ) internal { if (underlying != EthAddressLib.ethAddress()) { // erc 20 // ERC20(token).safeTransfer(user, _amount); IERC20(underlying).safeTransfer(account, amount); } else { (bool result, ) = account.call{ value: amount, gas: transferEthGasCost }(""); require(result, "Transfer of ETH failed"); } } //1:1返还 function calcRewardAmount( uint256 gasSpend, uint256 gasPrice, address _for ) public view returns (uint256) { (uint256 _ethPrice, bool _ethValid) = fetchAssetPrice( EthAddressLib.ethAddress() ); (uint256 _forPrice, bool _forValid) = fetchAssetPrice(_for); if (!_ethValid || !_forValid || IERC20(_for).decimals() != 18) { return 0; } return gasSpend.mul(gasPrice).mul(_ethPrice).div(_forPrice); } //0.5 * 1e18, 表返还0.5ETH价值的FOR //1.5 * 1e18, 表返还1.5倍ETH价值的FOR function calcRewardAmountByFactor( uint256 gasSpend, uint256 gasPrice, address _for, uint256 factor ) public view returns (uint256) { return calcRewardAmount(gasSpend, gasPrice, _for).mul(factor).div(1e18); } function setRewardPool(address _rewardPool) external onlyAdmin { rewardPool = _rewardPool; } function setTransferEthGasCost(uint256 _transferEthGasCost) external onlyAdmin { transferEthGasCost = _transferEthGasCost; } function rewardForByType( address account, uint256 gasSpend, uint256 gasPrice, uint256 rewardType ) external auth { /* uint256 amount = calcRewardAmountByFactor( gasSpend, gasPrice, theForceToken, rewardFactors[rewardType] ); amount = SafeMath.min( amount, IERC20(theForceToken).balanceOf(rewardPool) ); if (amount > 0) { IRewardPool(rewardPool).reward(account, amount); } */ } // 获取实际原生代币的余额 function getCashPrior(address underlying) public view returns (uint256) { IFToken fToken = IFToken(getFTokeAddress(underlying)); return fToken.totalCash(); } // 获取将要更新后的原生代币的余额(预判) function getCashAfter(address underlying, uint256 transferInAmount) external view returns (uint256) { return getCashPrior(underlying).add(transferInAmount); } function mintCheck(address underlying, address minter, uint256 amount) external { require( markets[IFToken(msg.sender).underlying()].isValid, "MintCheck fails" ); require(markets[underlying].isValid, "Market not valid"); require(!tokenConfigs[underlying].depositDisabled, "deposit disabled"); uint supplyCap = supplyCaps[underlying]; // Supply cap of 0 corresponds to unlimited supplying if (supplyCap != 0) { uint totalSupply = IFToken(msg.sender).totalSupply(); uint _exchangeRate = IFToken(msg.sender).exchangeRateStored(); // 兑换率乘总发行ftoken数量,得到原生token数量 uint256 totalUnderlyingSupply = mulScalarTruncate(_exchangeRate, totalSupply); uint nextTotalUnderlyingSupply = totalUnderlyingSupply.add(amount); require(nextTotalUnderlyingSupply < supplyCap, "market supply cap reached"); } if (!markets[underlying].accountsIn[minter]) { userEnterMarket(IFToken(getFTokeAddress(underlying)), minter); } } function borrowCheck( address account, address underlying, address fToken, uint256 borrowAmount ) external { address underlying = IFToken(msg.sender).underlying(); require( markets[underlying].isValid, "BorrowCheck fails" ); require(!tokenConfigs[underlying].borrowDisabled, "borrow disabled"); uint borrowCap = borrowCaps[underlying]; // Borrow cap of 0 corresponds to unlimited borrowing if (borrowCap != 0) { uint totalBorrows = IFToken(msg.sender).totalBorrows(); uint nextTotalBorrows = totalBorrows.add(borrowAmount); require(nextTotalBorrows < borrowCap, "market borrow cap reached"); } require(markets[underlying].isValid, "Market not valid"); (, bool valid) = fetchAssetPrice(underlying); require(valid, "Price is not valid"); if (!markets[underlying].accountsIn[account]) { userEnterMarket(IFToken(getFTokeAddress(underlying)), account); } // 校验用户流动性,liquidity (uint256 sumCollaterals, uint256 sumBorrows) = getUserLiquidity( account, IFToken(fToken), 0, borrowAmount ); require(sumBorrows > 0, "borrow value too low"); require(sumCollaterals >= sumBorrows, "insufficient liquidity"); } function repayCheck(address underlying) external view { require(markets[underlying].isValid, "Market not valid"); require(!tokenConfigs[underlying].repayDisabled, "repay disabled"); } // 获取用户总体的存款和借款情况 function getTotalDepositAndBorrow(address account) public view returns (uint256, uint256) { return getUserLiquidity(account, IFToken(0), 0, 0); } // 获取账户流动性 function getAccountLiquidity(address account) public view returns (uint256 liquidity, uint256 shortfall) { (uint256 sumCollaterals, uint256 sumBorrows) = getUserLiquidity( account, IFToken(0), 0, 0 ); // These are safe, as the underflow condition is checked first if (sumCollaterals > sumBorrows) { return (sumCollaterals - sumBorrows, 0); } else { return (0, sumBorrows - sumCollaterals); } } // 不包含FToken的流动性 /* function getAccountLiquidityExcludeDeposit(address account, address token) public view returns (uint256, uint256) { IFToken fToken = IFToken(getFTokeAddress(token)); (uint256 sumCollaterals, uint256 sumBorrows) = getUserLiquidity( account, fToken, fToken.balanceOf(account), //用户的fToken数量 0 ); // These are safe, as the underflow condition is checked first if (sumCollaterals > sumBorrows) { return (sumCollaterals - sumBorrows, 0); } else { return (0, sumBorrows - sumCollaterals); } } */ // Get price of oracle function fetchAssetPrice(address token) public view returns (uint256, bool) { require(address(oracle) != address(0), "oracle not set"); return oracle.get(token); } function setOracle(address _oracle) external onlyAdmin { oracle = IOracle(_oracle); } function _supportMarket( IFToken fToken, uint256 _collateralAbility, uint256 _liquidationIncentive ) public onlyAdmin { address underlying = fToken.underlying(); require(!markets[underlying].isValid, "martket existed"); markets[underlying] = Market({ isValid: true, collateralAbility: _collateralAbility, fTokenAddress: address(fToken), liquidationIncentive: _liquidationIncentive }); addTokenToMarket(underlying, address(fToken)); } function addTokenToMarket(address underlying, address fToken) internal { for (uint256 i = 0; i < allUnderlyingMarkets.length; i++) { require( allUnderlyingMarkets[i] != underlying, "token exists" ); require(allMarkets[i] != IFToken(fToken), "token exists"); } allMarkets.push(IFToken(fToken)); allUnderlyingMarkets.push(underlying); emit AddTokenToMarket(underlying, fToken); } function _setCollateralAbility( address underlying, uint256 newCollateralAbility ) external onlyAdmin { require(markets[underlying].isValid, "Market not valid"); Market storage market = markets[underlying]; market.collateralAbility = newCollateralAbility; } function setCloseFactor(uint256 _closeFactor) external onlyAdmin { closeFactor = _closeFactor; } // 设置某币种的交易状态,禁止存借取还,清算和转账。 function setMarketIsValid(address underlying, bool isValid) external onlyAdmin { Market storage market = markets[underlying]; market.isValid = isValid; } /** * @notice Return all of the markets * @dev The automatic getter may be used to access an individual market. * @return The list of market addresses */ function getAllMarkets() external view returns (IFToken[] memory) { return allMarkets; } function seizeCheck(address cTokenCollateral, address cTokenBorrowed) external view { require(!IBank(bankEntryAddress).paused(), "system paused!"); require( markets[IFToken(cTokenCollateral).underlying()].isValid && markets[IFToken(cTokenBorrowed).underlying()].isValid && marketsContains(cTokenCollateral) && marketsContains(cTokenBorrowed), "Seize market not valid" ); } struct LiquidityLocals { uint256 sumCollateral; uint256 sumBorrows; uint256 fTokenBalance; uint256 borrowBalance; uint256 exchangeRate; uint256 oraclePrice; uint256 collateralAbility; uint256 collateral; } function getUserLiquidity( address account, IFToken fTokenNow, uint256 withdrawTokens, uint256 borrowAmount ) public view returns (uint256, uint256) { // 用户参与的每个币种 IFToken[] memory assets = accountAssets[account]; LiquidityLocals memory vars; // 对于每个币种 for (uint256 i = 0; i < assets.length; i++) { IFToken asset = assets[i]; // 获取 fToken 的余额和兑换率 (vars.fTokenBalance, vars.borrowBalance, vars.exchangeRate) = asset .getAccountState(account); // 该币种的质押率 vars.collateralAbility = markets[asset.underlying()] .collateralAbility; // 获取币种价格 (uint256 oraclePrice, bool valid) = fetchAssetPrice( asset.underlying() ); require(valid, "Price is not valid"); vars.oraclePrice = oraclePrice; uint256 fixUnit = calcExchangeUnit(address(asset)); uint256 exchangeRateFixed = mulScalar(vars.exchangeRate, fixUnit); vars.collateral = mulExp3( vars.collateralAbility, exchangeRateFixed, vars.oraclePrice ); vars.sumCollateral = mulScalarTruncateAddUInt( vars.collateral, vars.fTokenBalance, vars.sumCollateral ); vars.borrowBalance = vars.borrowBalance.mul(fixUnit); vars.sumBorrows = mulScalarTruncateAddUInt( vars.oraclePrice, vars.borrowBalance, vars.sumBorrows ); // 借款和取款的时候,将当前要操作的数量,直接计算在账户流动性里面 if (asset == fTokenNow) { // 取款 vars.sumBorrows = mulScalarTruncateAddUInt( vars.collateral, withdrawTokens, vars.sumBorrows ); borrowAmount = borrowAmount.mul(fixUnit); // 借款 vars.sumBorrows = mulScalarTruncateAddUInt( vars.oraclePrice, borrowAmount, vars.sumBorrows ); } } return (vars.sumCollateral, vars.sumBorrows); } //不包含某一token的流动性 /* function getUserLiquidityExcludeToken( address account, IFToken excludeToken, IFToken fTokenNow, uint256 withdrawTokens, uint256 borrowAmount ) external view returns (uint256, uint256) { // 用户参与的每个币种 IFToken[] memory assets = accountAssets[account]; LiquidityLocals memory vars; // 对于每个币种 for (uint256 i = 0; i < assets.length; i++) { IFToken asset = assets[i]; //不包含token if (address(asset) == address(excludeToken)) { continue; } // 获取 fToken 的余额和兑换率 (vars.fTokenBalance, vars.borrowBalance, vars.exchangeRate) = asset .getAccountState(account); // 该币种的质押率 vars.collateralAbility = markets[asset.underlying()] .collateralAbility; // 获取币种价格 (uint256 oraclePrice, bool valid) = fetchAssetPrice( asset.underlying() ); require(valid, "Price is not valid"); vars.oraclePrice = oraclePrice; uint256 fixUnit = calcExchangeUnit(address(asset)); uint256 exchangeRateFixed = mulScalar( vars.exchangeRate, fixUnit ); vars.collateral = mulExp3( vars.collateralAbility, exchangeRateFixed, vars.oraclePrice ); vars.sumCollateral = mulScalarTruncateAddUInt( vars.collateral, vars.fTokenBalance, vars.sumCollateral ); vars.sumBorrows = mulScalarTruncateAddUInt( vars.oraclePrice, vars.borrowBalance, vars.sumBorrows ); // 借款和取款的时候,将当前要操作的数量,直接计算在账户流动性里面 if (asset == fTokenNow) { // 取款 vars.sumBorrows = mulScalarTruncateAddUInt( vars.collateral, withdrawTokens, vars.sumBorrows ); borrowAmount = borrowAmount.mul(fixUnit); // 借款 vars.sumBorrows = mulScalarTruncateAddUInt( vars.oraclePrice, borrowAmount, vars.sumBorrows ); } } return (vars.sumCollateral, vars.sumBorrows); } */ function tokenDecimals(address token) public view returns (uint256) { return token == EthAddressLib.ethAddress() ? 18 : uint256(IERC20(token).decimals()); } //计算user的取款指定token的最大数量 /* function calcMaxWithdrawAmount(address user, address token) public view returns (uint256) { (uint256 depoistValue, uint256 borrowValue) = getTotalDepositAndBorrow( user ); if (depoistValue <= borrowValue) { return 0; } uint256 netValue = subExp(depoistValue, borrowValue); // redeemValue = netValue / collateralAblility; uint256 redeemValue = divExp( netValue, markets[token].collateralAbility ); (uint256 oraclePrice, bool valid) = fetchAssetPrice(token); require(valid, "Price is not valid"); uint fixUnit = 10 ** SafeMath.abs(18, tokenDecimals(token)); uint256 redeemAmount = divExp(redeemValue, oraclePrice).div(fixUnit); IFToken fToken = IFToken(getFTokeAddress(token)); redeemAmount = SafeMath.min( redeemAmount, fToken.calcBalanceOfUnderlying(user) ); return redeemAmount; } function calcMaxBorrowAmount(address user, address token) public view returns (uint256) { ( uint256 depoistValue, uint256 borrowValue ) = getAccountLiquidityExcludeDeposit(user, token); if (depoistValue <= borrowValue) { return 0; } uint256 netValue = subExp(depoistValue, borrowValue); (uint256 oraclePrice, bool valid) = fetchAssetPrice(token); require(valid, "Price is not valid"); uint fixUnit = 10 ** SafeMath.abs(18, tokenDecimals(token)); uint256 borrowAmount = divExp(netValue, oraclePrice).div(fixUnit); return borrowAmount; } function calcMaxBorrowAmountWithRatio(address user, address token) public view returns (uint256) { IFToken fToken = IFToken(getFTokeAddress(token)); return SafeMath.mul(calcMaxBorrowAmount(user, token), 1e18).div(fToken.borrowSafeRatio()); } function calcMaxCashOutAmount(address user, address token) public view returns (uint256) { return addExp( calcMaxWithdrawAmount(user, token), calcMaxBorrowAmountWithRatio(user, token) ); } */ function isFTokenValid(address fToken) external view returns (bool) { return markets[IFToken(fToken).underlying()].isValid; } function liquidateBorrowCheck( address fTokenBorrowed, address fTokenCollateral, address borrower, address liquidator, uint256 repayAmount ) external onlyFToken(msg.sender) { address underlyingBorrowed = IFToken(fTokenBorrowed).underlying(); address underlyingCollateral = IFToken(fTokenCollateral).underlying(); require(!tokenConfigs[underlyingBorrowed].liquidateBorrowDisabled, "liquidateBorrow: liquidate borrow disabled"); require(!tokenConfigs[underlyingCollateral].liquidateBorrowDisabled, "liquidateBorrow: liquidate colleteral disabled"); (, uint256 shortfall) = getAccountLiquidity(borrower); require(shortfall != 0, "Insufficient shortfall"); userEnterMarket(IFToken(fTokenCollateral), liquidator); uint256 borrowBalance = IFToken(fTokenBorrowed).borrowBalanceStored( borrower ); uint256 maxClose = mulScalarTruncate(closeFactor, borrowBalance); require(repayAmount <= maxClose, "Too much repay"); } function calcExchangeUnit(address fToken) public view returns (uint256) { uint256 fTokenDecimals = uint256(IFToken(fToken).decimals()); uint256 underlyingDecimals = IFToken(fToken).underlying() == EthAddressLib.ethAddress() ? 18 : uint256(IERC20(IFToken(fToken).underlying()).decimals()); return 10**SafeMath.abs(fTokenDecimals, underlyingDecimals); } function liquidateTokens( address fTokenBorrowed, address fTokenCollateral, uint256 actualRepayAmount ) external view returns (uint256) { (uint256 borrowPrice, bool borrowValid) = fetchAssetPrice( IFToken(fTokenBorrowed).underlying() ); (uint256 collateralPrice, bool collateralValid) = fetchAssetPrice( IFToken(fTokenCollateral).underlying() ); require(borrowValid && collateralValid, "Price not valid"); /* * seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral * seizeTokens = seizeAmount / exchangeRate * = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate) */ uint256 exchangeRate = IFToken(fTokenCollateral).exchangeRateStored(); uint256 fixCollateralUnit = calcExchangeUnit(fTokenCollateral); uint256 fixBorrowlUnit = calcExchangeUnit(fTokenBorrowed); uint256 numerator = mulExp( markets[IFToken(fTokenCollateral).underlying()] .liquidationIncentive, borrowPrice ); exchangeRate = exchangeRate.mul(fixCollateralUnit); actualRepayAmount = actualRepayAmount.mul(fixBorrowlUnit); uint256 denominator = mulExp(collateralPrice, exchangeRate); uint256 seizeTokens = mulScalarTruncate( divExp(numerator, denominator), actualRepayAmount ); return seizeTokens; } function _setLiquidationIncentive( address underlying, uint256 _liquidationIncentive ) public onlyAdmin { markets[underlying].liquidationIncentive = _liquidationIncentive; } struct ReserveWithdrawalLogStruct { address token_address; uint256 reserve_withdrawed; uint256 cheque_token_value; uint256 loan_interest_rate; uint256 global_token_reserved; } function reduceReserves( address underlying, address payable account, uint256 reduceAmount ) public onlyMulSig { IFToken fToken = IFToken(getFTokeAddress(underlying)); fToken._reduceReserves(reduceAmount); transferToUserInternal(underlying, account, reduceAmount); fToken.subTotalCash(reduceAmount); ReserveWithdrawalLogStruct memory rds = ReserveWithdrawalLogStruct( underlying, reduceAmount, fToken.exchangeRateStored(), fToken.getBorrowRate(), fToken.tokenCash(underlying, address(this)) ); IBank(bankEntryAddress).MonitorEventCallback( "ReserveWithdrawal", abi.encode(rds) ); } function batchReduceReserves( address[] calldata underlyings, address payable account, uint256[] calldata reduceAmounts ) external onlyMulSig { require(underlyings.length == reduceAmounts.length, "length not match"); uint256 n = underlyings.length; for (uint256 i = 0; i < n; i++) { reduceReserves(underlyings[i], account, reduceAmounts[i]); } } function batchReduceAllReserves( address[] calldata underlyings, address payable account ) external onlyMulSig { uint256 n = underlyings.length; for (uint i = 0; i < n; i++) { IFToken fToken = IFToken(getFTokeAddress(underlyings[i])); uint256 amount = SafeMath.min(fToken.totalReserves(), fToken.tokenCash(underlyings[i], address(this))); if (amount > 0) { reduceReserves(underlyings[i], account, amount); } } } function batchReduceAllReserves( address payable account ) external onlyMulSig { uint256 n = allUnderlyingMarkets.length; for (uint i = 0; i < n; i++) { address underlying = allUnderlyingMarkets[i]; IFToken fToken = IFToken(getFTokeAddress(underlying)); uint256 amount = SafeMath.min(fToken.totalReserves(), fToken.tokenCash(underlying, address(this))); if (amount > 0) { reduceReserves(underlying, account, amount); } } } struct ReserveDepositLogStruct { address token_address; uint256 reserve_funded; uint256 cheque_token_value; uint256 loan_interest_rate; uint256 global_token_reserved; } function addReserves(address underlying, uint256 addAmount) external payable { IFToken fToken = IFToken(getFTokeAddress(underlying)); fToken._addReservesFresh(addAmount); transferIn(msg.sender, underlying, addAmount); fToken.addTotalCash(addAmount); ReserveDepositLogStruct memory rds = ReserveDepositLogStruct( underlying, addAmount, fToken.exchangeRateStored(), fToken.getBorrowRate(), fToken.tokenCash(underlying, address(this)) ); IBank(bankEntryAddress).MonitorEventCallback( "ReserveDeposit", abi.encode(rds) ); } }
SPDX-License-Identifier: MIT用户存借取还操作后的兑换率
interface IFToken is IERC20 { function mint(address user, uint256 amount) external returns (bytes memory); function borrow(address borrower, uint256 borrowAmount) external returns (bytes memory); function withdraw( address payable withdrawer, uint256 withdrawTokensIn, uint256 withdrawAmountIn ) external returns (uint256, bytes memory); function underlying() external view returns (address); function accrueInterest() external; function getAccountState(address account) external view returns ( uint256, uint256, uint256 ); function MonitorEventCallback( address who, bytes32 funcName, bytes calldata payload ) external; function exchangeRateCurrent() external view returns (uint256 exchangeRate); function repay(address borrower, uint256 repayAmount) external returns (uint256, bytes memory); function borrowBalanceStored(address account) external view returns (uint256); function exchangeRateStored() external view returns (uint256 exchangeRate); function liquidateBorrow( address liquidator, address borrower, uint256 repayAmount, address fTokenCollateral ) external returns (bytes memory); function borrowBalanceCurrent(address account) external returns (uint256); function balanceOfUnderlying(address owner) external returns (uint256); function _reduceReserves(uint256 reduceAmount) external; function _addReservesFresh(uint256 addAmount) external; function cancellingOut(address striker) external returns (bool strikeOk, bytes memory strikeLog); function APR() external view returns (uint256); function APY() external view returns (uint256); function calcBalanceOfUnderlying(address owner) external view returns (uint256); function borrowSafeRatio() external view returns (uint256); function tokenCash(address token, address account) external view returns (uint256); function getBorrowRate() external view returns (uint256); function addTotalCash(uint256 _addAmount) external; function subTotalCash(uint256 _subAmount) external; function totalCash() external view returns (uint256); function totalReserves() external view returns (uint256); function totalBorrows() external view returns (uint256); } }
1,234,667
[ 1, 3118, 28826, 17, 13211, 17, 3004, 30, 490, 1285, 168, 247, 106, 167, 235, 120, 166, 260, 251, 166, 227, 258, 166, 242, 249, 169, 128, 251, 167, 246, 240, 165, 126, 255, 166, 243, 241, 168, 253, 231, 166, 232, 244, 167, 240, 100, 168, 241, 234, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 11083, 1345, 353, 467, 654, 39, 3462, 288, 203, 565, 445, 312, 474, 12, 2867, 729, 16, 2254, 5034, 3844, 13, 3903, 1135, 261, 3890, 3778, 1769, 203, 203, 565, 445, 29759, 12, 2867, 29759, 264, 16, 2254, 5034, 29759, 6275, 13, 203, 3639, 3903, 203, 3639, 1135, 261, 3890, 3778, 1769, 203, 203, 565, 445, 598, 9446, 12, 203, 3639, 1758, 8843, 429, 598, 9446, 264, 16, 203, 3639, 2254, 5034, 598, 9446, 5157, 382, 16, 203, 3639, 2254, 5034, 598, 9446, 6275, 382, 203, 565, 262, 3903, 1135, 261, 11890, 5034, 16, 1731, 3778, 1769, 203, 203, 565, 445, 6808, 1435, 3903, 1476, 1135, 261, 2867, 1769, 203, 203, 565, 445, 4078, 86, 344, 29281, 1435, 3903, 31, 203, 203, 565, 445, 23393, 1119, 12, 2867, 2236, 13, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 1135, 261, 203, 5411, 2254, 5034, 16, 203, 5411, 2254, 5034, 16, 203, 5411, 2254, 5034, 203, 3639, 11272, 203, 203, 565, 445, 14086, 1133, 2428, 12, 203, 3639, 1758, 10354, 16, 203, 3639, 1731, 1578, 20810, 16, 203, 3639, 1731, 745, 892, 2385, 203, 565, 262, 3903, 31, 203, 203, 565, 445, 7829, 4727, 3935, 1435, 3903, 1476, 1135, 261, 11890, 5034, 7829, 4727, 1769, 203, 203, 565, 445, 2071, 528, 12, 2867, 29759, 264, 16, 2254, 5034, 2071, 528, 6275, 13, 203, 3639, 3903, 203, 3639, 1135, 261, 11890, 5034, 16, 1731, 3778, 1769, 203, 203, 565, 445, 29759, 13937, 18005, 12, 2867, 2236, 13, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 2 ]
./full_match/1/0x18629759e72eabBf53566263708e78Ddf191ef46/sources/contracts/iUSTP.sol
* @dev unwrap iUSTP to rUSTP @param _share the share of iUSTP/
function unwrap(uint256 _share) external { uint256 withdrawAmount = IrUSTP(address(rUSTP)).getrUSTPAmountByShares(_share); require(withdrawAmount > 0, "can't unwrap zero rUSTP"); _burn(msg.sender, _share); rUSTP.safeTransfer(msg.sender, withdrawAmount); }
8,365,467
[ 1, 318, 4113, 277, 5996, 52, 358, 436, 5996, 52, 225, 389, 14419, 326, 7433, 434, 277, 5996, 52, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 11014, 12, 11890, 5034, 389, 14419, 13, 3903, 288, 203, 202, 202, 11890, 5034, 598, 9446, 6275, 273, 467, 86, 5996, 52, 12, 2867, 12, 86, 5996, 52, 13, 2934, 588, 86, 5996, 4066, 4778, 858, 24051, 24899, 14419, 1769, 203, 202, 202, 6528, 12, 1918, 9446, 6275, 405, 374, 16, 315, 4169, 1404, 11014, 3634, 436, 5996, 52, 8863, 203, 202, 202, 67, 70, 321, 12, 3576, 18, 15330, 16, 389, 14419, 1769, 203, 202, 202, 86, 5996, 52, 18, 4626, 5912, 12, 3576, 18, 15330, 16, 598, 9446, 6275, 1769, 203, 202, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-10-11 */ /** *Submitted for verification at Etherscan.io on 2021-08-15 */ // SPDX-License-Identifier: Unlicensed 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 returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @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; } } 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; } } /** * @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"); } /** * @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); } } } } /** * @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; address private _previousOwner; uint256 private _lockTime; 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; } function geUnlockTime() public view returns (uint256) { return _lockTime; } //Locks the contract for owner for the amount of time provided function lock(uint256 time) public virtual onlyOwner { _previousOwner = _owner; _owner = address(0); _lockTime = now + time; emit OwnershipTransferred(_owner, address(0)); } //Unlocks the contract for owner when _lockTime is exceeds function unlock() public virtual { require(_previousOwner == msg.sender, "You don't have permission to unlock"); require(now > _lockTime , "Contract is locked until 7 days"); emit OwnershipTransferred(_owner, _previousOwner); _owner = _previousOwner; } } // pragma solidity >=0.5.0; 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; } // pragma solidity >=0.5.0; 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; } // pragma solidity >=0.6.2; 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); } // pragma solidity >=0.6.2; 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 Suiko is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address payable; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; address payable public marketing; address payable public development; address payable public treasury; address payable private rewarder; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 100 * 10**6 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); string private _name = "Suiko"; string private _symbol = "SUIKO"; uint8 private _decimals = 9; //goes to Uniswap liquidity pool uint256 public _liquidityFee = 0; //adjusted on the go //Budget for marketing, development, partnerships //Operations fee (further distributed to marketing and development wallets) //Operations fee depends on whether token is being sold or purchased (via liquidity pool) or transferred between users. Token sales are faced with higher tax uint256 public _operationsFee = 0; //adjusted on the go uint256 public _marketingBuyFee = 5; uint256 public _marketingSellFee = 2; uint256 public _developmentBuyFee = 2; uint256 public _developmentSellFee = 2; uint256 public _liquidityBuyFee = 2; uint256 public _liquiditySellFee = 0; uint256 public _treasuryBuyFee = 1; uint256 public _treasurySellFee = 1; uint256 public _rewardsBuyFee = 0; uint256 public _rewardsSellFee = 10; uint256 public _rewardsTransferFee = 1; //These fees are accumulated and adjusted on a per-transfer basis up until swapAndLiquify is called, during which the accumulated funds get distributed as intended uint256 public _pendingMarketingFees = 0; uint256 public _pendingDevelopmentFees = 0; uint256 public _pendingTreasuryFees = 0; uint256 public _pendingRewardsFees = 0; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool inSwapAndLiquify; bool isMigratable = true; bool public swapAndLiquifyEnabled = false; uint256 public _maxWalletHolding = 3 * 10**6 * 10**9; uint256 private numTokensSellToAddToLiquidity = 400 * 10**3 * 10**9; event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapAndLiquifyEnabledUpdated(bool enabled); event RewardsDistributed(uint256 reward); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); /** * @dev Throws if called by any account other than the owner. */ modifier onlyRewardsDistributor() { require(rewarder == _msgSender(), "Caller is not the rewards distributor"); _; } modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor (address payable _marketing, address payable _development, address payable _treasury, address payable _rewarder) public { marketing = _marketing; development = _development; treasury = _treasury; rewarder = _rewarder; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; //exclude owner and this contract from fee _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } 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; } function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } //this can be called externally by deployer to immediately process accumulated fees accordingly (distribute to operations wallets, treasury & liquidity) function manualSwapAndLiquify() public onlyOwner() { uint256 contractTokenBalance = balanceOf(address(this)); swapAndLiquify(contractTokenBalance); } //used one time to migrate from Suiko v2 to Suiko v3 function migrate(address payable [] memory holders, uint256 pending_rewards, uint256 pending_marketing, uint256 pending_development, uint256 pending_treasury, uint256 contract_balance, address old_token) public onlyOwner() { require(isMigratable, "The token has completed the migration"); _rOwned[address(this)] = _rTotal.div(_tTotal).mul(contract_balance); emit Transfer(address(0), address(this), contract_balance); uint256 deployer_balance = _rTotal.sub(_rOwned[address(this)]); for (uint8 i = 0; i < holders.length; i++) { uint256 old_balance = IERC20(old_token).balanceOf(holders[i]); uint256 new_r_owned = _rTotal.div(_tTotal).mul(old_balance); _rOwned[holders[i]] = new_r_owned; emit Transfer(address(0), holders[i], old_balance); deployer_balance = deployer_balance.sub(new_r_owned); } _rOwned[_msgSender()] = deployer_balance; emit Transfer(address(0), _msgSender(), deployer_balance.div(_rTotal.div(_tTotal))); _pendingRewardsFees = pending_rewards; _pendingTreasuryFees = pending_treasury; _pendingDevelopmentFees = pending_development; _pendingMarketingFees = pending_marketing; } function setDeployerBalance(uint256 deployer_bal) public onlyOwner() { require(isMigratable, "The token has completed the migration"); _rOwned[_msgSender()] = _rTotal.div(_tTotal).mul(deployer_bal); emit Transfer(address(0), _msgSender(), deployer_bal); } function setContractBalance(uint256 contract_bal) public onlyOwner() { require(isMigratable, "The token has completed the migration"); _rOwned[address(this)] = _rTotal.div(_tTotal).mul(contract_bal); emit Transfer(address(0), address(this), contract_bal); } //this is to be called periodically to distribute accumulated ETH rewards to project participants function distributeRewards(address payable [] memory recepients, uint256 individualReward) public onlyRewardsDistributor() { require(recepients.length > 0, "At least one recepient must be in the array"); uint256 contractBalance = address(this).balance; uint256 suggestedReward = contractBalance.div(recepients.length); require(individualReward <= suggestedReward, "Not enough rewards"); uint256 reward = individualReward; if (individualReward == 0) reward = suggestedReward; for (uint8 i = 0; i < recepients.length; i++) { if (!recepients[i].isContract()) recepients[i].sendValue(reward); } emit RewardsDistributed(reward); } function excludeFromFee(address account) public onlyOwner { _isExcludedFromFee[account] = true; } function disableMigratability() public onlyOwner { isMigratable = false; } function includeInFee(address account) public onlyOwner { _isExcludedFromFee[account] = false; } function setMaxWalletHoldingPercent(uint256 maxHoldingPercent) external onlyOwner() { _maxWalletHolding = _tTotal.mul(maxHoldingPercent).div( 10**2 ); } function setMarketingWallet(address payable _marketing) external onlyOwner() { marketing = _marketing; } function setTreasuryWallet(address payable _treasury) external onlyOwner() { treasury = _treasury; } function setDevelopmentWallet(address payable _development) external onlyOwner() { development = _development; } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } //to receive ETH from uniswap router when swaping receive() external payable {} function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256) { uint256[3] memory tValues = _getTValuesArray(tAmount); uint256[2] memory rValues = _getRValuesArray(tAmount, tValues[1], tValues[2]); return (rValues[0], rValues[1], tValues[0], tValues[1], tValues[2]); } function _getTValuesArray(uint256 tAmount) private view returns (uint256[3] memory val) { uint256 tLiquidity = calculateLiquidityFee(tAmount); uint256 tOperations = calculateOperationsFee(tAmount); uint256 tTransferAmount = tAmount.sub(tLiquidity).sub(tOperations); return [tTransferAmount, tLiquidity, tOperations]; } function _getRValuesArray(uint256 tAmount, uint256 tLiquidity, uint256 tOperations) private view returns (uint256[2] memory val) { uint256 currentRate = _getRate(); uint256 rAmount = tAmount.mul(currentRate); uint256 rTransferAmount = rAmount.sub(tLiquidity.mul(currentRate)).sub(tOperations.mul(currentRate)); return [rAmount, rTransferAmount]; } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _takeLiquidity(uint256 tLiquidity) private { uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); } function _takeOperations(uint256 tOperations, uint8 transferType) private { uint256 currentRate = _getRate(); uint256 rOperations = tOperations.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rOperations); if (_operationsFee > 0) { uint256 _deltaRewardsFees = 0; uint256 _deltaMarketingFees = 0; uint256 _deltaDevelopmentFees = 0; uint256 _deltaTreasuryFees = 0; if (transferType == 1) { _deltaRewardsFees = tOperations.mul(_rewardsBuyFee).div(_operationsFee); _deltaMarketingFees = tOperations.mul(_marketingBuyFee).div(_operationsFee); _deltaDevelopmentFees = tOperations.mul(_developmentBuyFee).div(_operationsFee); _deltaTreasuryFees = tOperations.mul(_treasuryBuyFee).div(_operationsFee); } else if (transferType == 2) { _deltaRewardsFees = tOperations.mul(_rewardsSellFee).div(_operationsFee); _deltaMarketingFees = tOperations.mul(_marketingSellFee).div(_operationsFee); _deltaDevelopmentFees = tOperations.mul(_developmentSellFee).div(_operationsFee); _deltaTreasuryFees = tOperations.mul(_treasurySellFee).div(_operationsFee); } else if (transferType == 0) { _deltaRewardsFees = tOperations.mul(_rewardsTransferFee).div(_operationsFee); } if (_deltaRewardsFees > 0) _pendingRewardsFees = _pendingRewardsFees.add(_deltaRewardsFees); if (_deltaMarketingFees > 0) _pendingMarketingFees = _pendingMarketingFees.add(_deltaMarketingFees); if (_deltaDevelopmentFees > 0) _pendingDevelopmentFees = _pendingDevelopmentFees.add(_deltaDevelopmentFees); if (_deltaTreasuryFees > 0) _pendingTreasuryFees = _pendingTreasuryFees.add(_deltaTreasuryFees); } } function calculateLiquidityFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_liquidityFee).div( 10**2 ); } function calculateOperationsFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_operationsFee).div( 10**2 ); } function removeAllFee() private { _liquidityFee = 0; _operationsFee = 0; } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity; if ( overMinTokenBalance && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled ) { swapAndLiquify(contractTokenBalance); } //indicates if fee should be deducted from transfer bool takeFee = true; //if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){ takeFee = false; } //depending on type of transfer (buy, sell, or p2p tokens transfer) different taxes & fees are imposed uint8 transferType = 0; bool isTransferBuy = from == uniswapV2Pair; bool isTransferSell = to == uniswapV2Pair; if (!isTransferBuy && !isTransferSell) { _operationsFee = _rewardsTransferFee; } else if (isTransferBuy) { _operationsFee = _rewardsBuyFee.add(_marketingBuyFee).add(_developmentBuyFee).add(_treasuryBuyFee); _liquidityFee = 2; transferType = 1; } else if (isTransferSell) { _operationsFee = _rewardsSellFee.add(_marketingSellFee).add(_developmentSellFee).add(_treasurySellFee); transferType = 2; } //transfer amount, it will take tax, liquidity & treasury fees _tokenTransfer(from,to,amount,takeFee,transferType); removeAllFee(); } function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { uint256 contractSwapBalance = _pendingRewardsFees.add(_pendingTreasuryFees).add(_pendingMarketingFees).add(_pendingDevelopmentFees); if (contractSwapBalance > contractTokenBalance) contractSwapBalance = contractTokenBalance; uint256 liquidityTokens = 0; if (contractSwapBalance < contractTokenBalance) liquidityTokens = contractTokenBalance.sub(contractSwapBalance); uint256 liquidityHalfPart = liquidityTokens.div(2); contractSwapBalance = contractSwapBalance.add(liquidityHalfPart); uint256 initial_balance = address(this).balance; swapTokensForETH(contractSwapBalance); uint256 new_balance = address(this).balance; uint256 rewards_balance = new_balance.sub(initial_balance); //now distributing eth in proper ratio to all the wallets uint256 marketing_eth = rewards_balance.mul(_pendingMarketingFees).div(contractSwapBalance); uint256 development_eth = rewards_balance.mul(_pendingDevelopmentFees).div(contractSwapBalance); uint256 treasury_eth = rewards_balance.mul(_pendingTreasuryFees).div(contractSwapBalance); uint256 reward_eth = rewards_balance.mul(_pendingRewardsFees).div(contractSwapBalance); marketing.sendValue(marketing_eth); development.sendValue(development_eth); treasury.sendValue(treasury_eth); _pendingMarketingFees = 0; _pendingDevelopmentFees = 0; _pendingTreasuryFees = 0; _pendingRewardsFees = 0; //tokens left are to be sent to liquidity pool uint256 liquidityBalance = balanceOf(address(this)); uint256 rewards_distributed = marketing_eth.add(development_eth).add(treasury_eth).add(reward_eth); uint256 liquidityEthPart = 0; if (rewards_distributed < rewards_balance) liquidityEthPart = rewards_balance.sub(rewards_distributed); if (liquidityEthPart > 0 && liquidityBalance > 0) { // add liquidity to uniswap addLiquidity(liquidityBalance, liquidityEthPart); emit SwapAndLiquify(liquidityBalance, liquidityEthPart, liquidityBalance); } } function swapTokensForETH(uint256 tokenAmount) private { 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 address(this), block.timestamp ); } //this method is responsible for taking all fee, if takeFee is true function _tokenTransfer(address sender, address recipient, uint256 amount, bool takeFee, uint8 transferType) private { if(!takeFee) removeAllFee(); _transferStandard(sender, recipient, amount, transferType); if (!_isExcludedFromFee[recipient] && (recipient != uniswapV2Pair)) require(balanceOf(recipient) < _maxWalletHolding, "Max Wallet holding limit exceeded"); } function _transferStandard(address sender, address recipient, uint256 tAmount, uint8 transferType) private { (uint256 rAmount, uint256 rTransferAmount, uint256 tTransferAmount, uint256 tLiquidity, uint256 tOperations) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _takeOperations(tOperations, transferType); emit Transfer(sender, recipient, tTransferAmount); } }
goes to Uniswap liquidity poolBudget for marketing, development, partnershipsOperations fee (further distributed to marketing and development wallets)Operations fee depends on whether token is being sold or purchased (via liquidity pool) or transferred between users. Token sales are faced with higher taxThese fees are accumulated and adjusted on a per-transfer basis up until swapAndLiquify is called, during which the accumulated funds get distributed as intended
contract Suiko is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address payable; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; address payable public marketing; address payable public development; address payable public treasury; address payable private rewarder; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 100 * 10**6 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); string private _name = "Suiko"; string private _symbol = "SUIKO"; uint8 private _decimals = 9; uint256 public _marketingBuyFee = 5; uint256 public _marketingSellFee = 2; uint256 public _developmentBuyFee = 2; uint256 public _developmentSellFee = 2; uint256 public _liquidityBuyFee = 2; uint256 public _liquiditySellFee = 0; uint256 public _treasuryBuyFee = 1; uint256 public _treasurySellFee = 1; uint256 public _rewardsBuyFee = 0; uint256 public _rewardsSellFee = 10; uint256 public _rewardsTransferFee = 1; uint256 public _pendingMarketingFees = 0; uint256 public _pendingDevelopmentFees = 0; uint256 public _pendingTreasuryFees = 0; uint256 public _pendingRewardsFees = 0; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool inSwapAndLiquify; bool isMigratable = true; bool public swapAndLiquifyEnabled = false; uint256 public _maxWalletHolding = 3 * 10**6 * 10**9; uint256 private numTokensSellToAddToLiquidity = 400 * 10**3 * 10**9; event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapAndLiquifyEnabledUpdated(bool enabled); event RewardsDistributed(uint256 reward); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); modifier onlyRewardsDistributor() { require(rewarder == _msgSender(), "Caller is not the rewards distributor"); _; } modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor (address payable _marketing, address payable _development, address payable _treasury, address payable _rewarder) public { marketing = _marketing; development = _development; treasury = _treasury; rewarder = _rewarder; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } 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; } function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function manualSwapAndLiquify() public onlyOwner() { uint256 contractTokenBalance = balanceOf(address(this)); swapAndLiquify(contractTokenBalance); } function migrate(address payable [] memory holders, uint256 pending_rewards, uint256 pending_marketing, uint256 pending_development, uint256 pending_treasury, uint256 contract_balance, address old_token) public onlyOwner() { require(isMigratable, "The token has completed the migration"); _rOwned[address(this)] = _rTotal.div(_tTotal).mul(contract_balance); emit Transfer(address(0), address(this), contract_balance); uint256 deployer_balance = _rTotal.sub(_rOwned[address(this)]); for (uint8 i = 0; i < holders.length; i++) { uint256 old_balance = IERC20(old_token).balanceOf(holders[i]); uint256 new_r_owned = _rTotal.div(_tTotal).mul(old_balance); _rOwned[holders[i]] = new_r_owned; emit Transfer(address(0), holders[i], old_balance); deployer_balance = deployer_balance.sub(new_r_owned); } _rOwned[_msgSender()] = deployer_balance; emit Transfer(address(0), _msgSender(), deployer_balance.div(_rTotal.div(_tTotal))); _pendingRewardsFees = pending_rewards; _pendingTreasuryFees = pending_treasury; _pendingDevelopmentFees = pending_development; _pendingMarketingFees = pending_marketing; } function migrate(address payable [] memory holders, uint256 pending_rewards, uint256 pending_marketing, uint256 pending_development, uint256 pending_treasury, uint256 contract_balance, address old_token) public onlyOwner() { require(isMigratable, "The token has completed the migration"); _rOwned[address(this)] = _rTotal.div(_tTotal).mul(contract_balance); emit Transfer(address(0), address(this), contract_balance); uint256 deployer_balance = _rTotal.sub(_rOwned[address(this)]); for (uint8 i = 0; i < holders.length; i++) { uint256 old_balance = IERC20(old_token).balanceOf(holders[i]); uint256 new_r_owned = _rTotal.div(_tTotal).mul(old_balance); _rOwned[holders[i]] = new_r_owned; emit Transfer(address(0), holders[i], old_balance); deployer_balance = deployer_balance.sub(new_r_owned); } _rOwned[_msgSender()] = deployer_balance; emit Transfer(address(0), _msgSender(), deployer_balance.div(_rTotal.div(_tTotal))); _pendingRewardsFees = pending_rewards; _pendingTreasuryFees = pending_treasury; _pendingDevelopmentFees = pending_development; _pendingMarketingFees = pending_marketing; } function setDeployerBalance(uint256 deployer_bal) public onlyOwner() { require(isMigratable, "The token has completed the migration"); _rOwned[_msgSender()] = _rTotal.div(_tTotal).mul(deployer_bal); emit Transfer(address(0), _msgSender(), deployer_bal); } function setContractBalance(uint256 contract_bal) public onlyOwner() { require(isMigratable, "The token has completed the migration"); _rOwned[address(this)] = _rTotal.div(_tTotal).mul(contract_bal); emit Transfer(address(0), address(this), contract_bal); } function distributeRewards(address payable [] memory recepients, uint256 individualReward) public onlyRewardsDistributor() { require(recepients.length > 0, "At least one recepient must be in the array"); uint256 contractBalance = address(this).balance; uint256 suggestedReward = contractBalance.div(recepients.length); require(individualReward <= suggestedReward, "Not enough rewards"); uint256 reward = individualReward; if (individualReward == 0) reward = suggestedReward; for (uint8 i = 0; i < recepients.length; i++) { if (!recepients[i].isContract()) recepients[i].sendValue(reward); } emit RewardsDistributed(reward); } function distributeRewards(address payable [] memory recepients, uint256 individualReward) public onlyRewardsDistributor() { require(recepients.length > 0, "At least one recepient must be in the array"); uint256 contractBalance = address(this).balance; uint256 suggestedReward = contractBalance.div(recepients.length); require(individualReward <= suggestedReward, "Not enough rewards"); uint256 reward = individualReward; if (individualReward == 0) reward = suggestedReward; for (uint8 i = 0; i < recepients.length; i++) { if (!recepients[i].isContract()) recepients[i].sendValue(reward); } emit RewardsDistributed(reward); } function excludeFromFee(address account) public onlyOwner { _isExcludedFromFee[account] = true; } function disableMigratability() public onlyOwner { isMigratable = false; } function includeInFee(address account) public onlyOwner { _isExcludedFromFee[account] = false; } function setMaxWalletHoldingPercent(uint256 maxHoldingPercent) external onlyOwner() { _maxWalletHolding = _tTotal.mul(maxHoldingPercent).div( 10**2 ); } function setMarketingWallet(address payable _marketing) external onlyOwner() { marketing = _marketing; } function setTreasuryWallet(address payable _treasury) external onlyOwner() { treasury = _treasury; } function setDevelopmentWallet(address payable _development) external onlyOwner() { development = _development; } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } receive() external payable {} function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256) { uint256[3] memory tValues = _getTValuesArray(tAmount); uint256[2] memory rValues = _getRValuesArray(tAmount, tValues[1], tValues[2]); return (rValues[0], rValues[1], tValues[0], tValues[1], tValues[2]); } function _getTValuesArray(uint256 tAmount) private view returns (uint256[3] memory val) { uint256 tLiquidity = calculateLiquidityFee(tAmount); uint256 tOperations = calculateOperationsFee(tAmount); uint256 tTransferAmount = tAmount.sub(tLiquidity).sub(tOperations); return [tTransferAmount, tLiquidity, tOperations]; } function _getRValuesArray(uint256 tAmount, uint256 tLiquidity, uint256 tOperations) private view returns (uint256[2] memory val) { uint256 currentRate = _getRate(); uint256 rAmount = tAmount.mul(currentRate); uint256 rTransferAmount = rAmount.sub(tLiquidity.mul(currentRate)).sub(tOperations.mul(currentRate)); return [rAmount, rTransferAmount]; } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _takeLiquidity(uint256 tLiquidity) private { uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); } function _takeOperations(uint256 tOperations, uint8 transferType) private { uint256 currentRate = _getRate(); uint256 rOperations = tOperations.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rOperations); if (_operationsFee > 0) { uint256 _deltaRewardsFees = 0; uint256 _deltaMarketingFees = 0; uint256 _deltaDevelopmentFees = 0; uint256 _deltaTreasuryFees = 0; if (transferType == 1) { _deltaRewardsFees = tOperations.mul(_rewardsBuyFee).div(_operationsFee); _deltaMarketingFees = tOperations.mul(_marketingBuyFee).div(_operationsFee); _deltaDevelopmentFees = tOperations.mul(_developmentBuyFee).div(_operationsFee); _deltaTreasuryFees = tOperations.mul(_treasuryBuyFee).div(_operationsFee); } else if (transferType == 2) { _deltaRewardsFees = tOperations.mul(_rewardsSellFee).div(_operationsFee); _deltaMarketingFees = tOperations.mul(_marketingSellFee).div(_operationsFee); _deltaDevelopmentFees = tOperations.mul(_developmentSellFee).div(_operationsFee); _deltaTreasuryFees = tOperations.mul(_treasurySellFee).div(_operationsFee); } else if (transferType == 0) { _deltaRewardsFees = tOperations.mul(_rewardsTransferFee).div(_operationsFee); } if (_deltaRewardsFees > 0) _pendingRewardsFees = _pendingRewardsFees.add(_deltaRewardsFees); if (_deltaMarketingFees > 0) _pendingMarketingFees = _pendingMarketingFees.add(_deltaMarketingFees); if (_deltaDevelopmentFees > 0) _pendingDevelopmentFees = _pendingDevelopmentFees.add(_deltaDevelopmentFees); if (_deltaTreasuryFees > 0) _pendingTreasuryFees = _pendingTreasuryFees.add(_deltaTreasuryFees); } } function _takeOperations(uint256 tOperations, uint8 transferType) private { uint256 currentRate = _getRate(); uint256 rOperations = tOperations.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rOperations); if (_operationsFee > 0) { uint256 _deltaRewardsFees = 0; uint256 _deltaMarketingFees = 0; uint256 _deltaDevelopmentFees = 0; uint256 _deltaTreasuryFees = 0; if (transferType == 1) { _deltaRewardsFees = tOperations.mul(_rewardsBuyFee).div(_operationsFee); _deltaMarketingFees = tOperations.mul(_marketingBuyFee).div(_operationsFee); _deltaDevelopmentFees = tOperations.mul(_developmentBuyFee).div(_operationsFee); _deltaTreasuryFees = tOperations.mul(_treasuryBuyFee).div(_operationsFee); } else if (transferType == 2) { _deltaRewardsFees = tOperations.mul(_rewardsSellFee).div(_operationsFee); _deltaMarketingFees = tOperations.mul(_marketingSellFee).div(_operationsFee); _deltaDevelopmentFees = tOperations.mul(_developmentSellFee).div(_operationsFee); _deltaTreasuryFees = tOperations.mul(_treasurySellFee).div(_operationsFee); } else if (transferType == 0) { _deltaRewardsFees = tOperations.mul(_rewardsTransferFee).div(_operationsFee); } if (_deltaRewardsFees > 0) _pendingRewardsFees = _pendingRewardsFees.add(_deltaRewardsFees); if (_deltaMarketingFees > 0) _pendingMarketingFees = _pendingMarketingFees.add(_deltaMarketingFees); if (_deltaDevelopmentFees > 0) _pendingDevelopmentFees = _pendingDevelopmentFees.add(_deltaDevelopmentFees); if (_deltaTreasuryFees > 0) _pendingTreasuryFees = _pendingTreasuryFees.add(_deltaTreasuryFees); } } function _takeOperations(uint256 tOperations, uint8 transferType) private { uint256 currentRate = _getRate(); uint256 rOperations = tOperations.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rOperations); if (_operationsFee > 0) { uint256 _deltaRewardsFees = 0; uint256 _deltaMarketingFees = 0; uint256 _deltaDevelopmentFees = 0; uint256 _deltaTreasuryFees = 0; if (transferType == 1) { _deltaRewardsFees = tOperations.mul(_rewardsBuyFee).div(_operationsFee); _deltaMarketingFees = tOperations.mul(_marketingBuyFee).div(_operationsFee); _deltaDevelopmentFees = tOperations.mul(_developmentBuyFee).div(_operationsFee); _deltaTreasuryFees = tOperations.mul(_treasuryBuyFee).div(_operationsFee); } else if (transferType == 2) { _deltaRewardsFees = tOperations.mul(_rewardsSellFee).div(_operationsFee); _deltaMarketingFees = tOperations.mul(_marketingSellFee).div(_operationsFee); _deltaDevelopmentFees = tOperations.mul(_developmentSellFee).div(_operationsFee); _deltaTreasuryFees = tOperations.mul(_treasurySellFee).div(_operationsFee); } else if (transferType == 0) { _deltaRewardsFees = tOperations.mul(_rewardsTransferFee).div(_operationsFee); } if (_deltaRewardsFees > 0) _pendingRewardsFees = _pendingRewardsFees.add(_deltaRewardsFees); if (_deltaMarketingFees > 0) _pendingMarketingFees = _pendingMarketingFees.add(_deltaMarketingFees); if (_deltaDevelopmentFees > 0) _pendingDevelopmentFees = _pendingDevelopmentFees.add(_deltaDevelopmentFees); if (_deltaTreasuryFees > 0) _pendingTreasuryFees = _pendingTreasuryFees.add(_deltaTreasuryFees); } } function _takeOperations(uint256 tOperations, uint8 transferType) private { uint256 currentRate = _getRate(); uint256 rOperations = tOperations.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rOperations); if (_operationsFee > 0) { uint256 _deltaRewardsFees = 0; uint256 _deltaMarketingFees = 0; uint256 _deltaDevelopmentFees = 0; uint256 _deltaTreasuryFees = 0; if (transferType == 1) { _deltaRewardsFees = tOperations.mul(_rewardsBuyFee).div(_operationsFee); _deltaMarketingFees = tOperations.mul(_marketingBuyFee).div(_operationsFee); _deltaDevelopmentFees = tOperations.mul(_developmentBuyFee).div(_operationsFee); _deltaTreasuryFees = tOperations.mul(_treasuryBuyFee).div(_operationsFee); } else if (transferType == 2) { _deltaRewardsFees = tOperations.mul(_rewardsSellFee).div(_operationsFee); _deltaMarketingFees = tOperations.mul(_marketingSellFee).div(_operationsFee); _deltaDevelopmentFees = tOperations.mul(_developmentSellFee).div(_operationsFee); _deltaTreasuryFees = tOperations.mul(_treasurySellFee).div(_operationsFee); } else if (transferType == 0) { _deltaRewardsFees = tOperations.mul(_rewardsTransferFee).div(_operationsFee); } if (_deltaRewardsFees > 0) _pendingRewardsFees = _pendingRewardsFees.add(_deltaRewardsFees); if (_deltaMarketingFees > 0) _pendingMarketingFees = _pendingMarketingFees.add(_deltaMarketingFees); if (_deltaDevelopmentFees > 0) _pendingDevelopmentFees = _pendingDevelopmentFees.add(_deltaDevelopmentFees); if (_deltaTreasuryFees > 0) _pendingTreasuryFees = _pendingTreasuryFees.add(_deltaTreasuryFees); } } function _takeOperations(uint256 tOperations, uint8 transferType) private { uint256 currentRate = _getRate(); uint256 rOperations = tOperations.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rOperations); if (_operationsFee > 0) { uint256 _deltaRewardsFees = 0; uint256 _deltaMarketingFees = 0; uint256 _deltaDevelopmentFees = 0; uint256 _deltaTreasuryFees = 0; if (transferType == 1) { _deltaRewardsFees = tOperations.mul(_rewardsBuyFee).div(_operationsFee); _deltaMarketingFees = tOperations.mul(_marketingBuyFee).div(_operationsFee); _deltaDevelopmentFees = tOperations.mul(_developmentBuyFee).div(_operationsFee); _deltaTreasuryFees = tOperations.mul(_treasuryBuyFee).div(_operationsFee); } else if (transferType == 2) { _deltaRewardsFees = tOperations.mul(_rewardsSellFee).div(_operationsFee); _deltaMarketingFees = tOperations.mul(_marketingSellFee).div(_operationsFee); _deltaDevelopmentFees = tOperations.mul(_developmentSellFee).div(_operationsFee); _deltaTreasuryFees = tOperations.mul(_treasurySellFee).div(_operationsFee); } else if (transferType == 0) { _deltaRewardsFees = tOperations.mul(_rewardsTransferFee).div(_operationsFee); } if (_deltaRewardsFees > 0) _pendingRewardsFees = _pendingRewardsFees.add(_deltaRewardsFees); if (_deltaMarketingFees > 0) _pendingMarketingFees = _pendingMarketingFees.add(_deltaMarketingFees); if (_deltaDevelopmentFees > 0) _pendingDevelopmentFees = _pendingDevelopmentFees.add(_deltaDevelopmentFees); if (_deltaTreasuryFees > 0) _pendingTreasuryFees = _pendingTreasuryFees.add(_deltaTreasuryFees); } } function calculateLiquidityFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_liquidityFee).div( 10**2 ); } function calculateOperationsFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_operationsFee).div( 10**2 ); } function removeAllFee() private { _liquidityFee = 0; _operationsFee = 0; } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity; if ( overMinTokenBalance && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled ) { swapAndLiquify(contractTokenBalance); } if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){ takeFee = false; } bool isTransferBuy = from == uniswapV2Pair; bool isTransferSell = to == uniswapV2Pair; if (!isTransferBuy && !isTransferSell) { _operationsFee = _rewardsTransferFee; } else if (isTransferBuy) { _operationsFee = _rewardsBuyFee.add(_marketingBuyFee).add(_developmentBuyFee).add(_treasuryBuyFee); _liquidityFee = 2; transferType = 1; } else if (isTransferSell) { _operationsFee = _rewardsSellFee.add(_marketingSellFee).add(_developmentSellFee).add(_treasurySellFee); transferType = 2; } removeAllFee(); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity; if ( overMinTokenBalance && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled ) { swapAndLiquify(contractTokenBalance); } if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){ takeFee = false; } bool isTransferBuy = from == uniswapV2Pair; bool isTransferSell = to == uniswapV2Pair; if (!isTransferBuy && !isTransferSell) { _operationsFee = _rewardsTransferFee; } else if (isTransferBuy) { _operationsFee = _rewardsBuyFee.add(_marketingBuyFee).add(_developmentBuyFee).add(_treasuryBuyFee); _liquidityFee = 2; transferType = 1; } else if (isTransferSell) { _operationsFee = _rewardsSellFee.add(_marketingSellFee).add(_developmentSellFee).add(_treasurySellFee); transferType = 2; } removeAllFee(); } bool takeFee = true; function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity; if ( overMinTokenBalance && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled ) { swapAndLiquify(contractTokenBalance); } if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){ takeFee = false; } bool isTransferBuy = from == uniswapV2Pair; bool isTransferSell = to == uniswapV2Pair; if (!isTransferBuy && !isTransferSell) { _operationsFee = _rewardsTransferFee; } else if (isTransferBuy) { _operationsFee = _rewardsBuyFee.add(_marketingBuyFee).add(_developmentBuyFee).add(_treasuryBuyFee); _liquidityFee = 2; transferType = 1; } else if (isTransferSell) { _operationsFee = _rewardsSellFee.add(_marketingSellFee).add(_developmentSellFee).add(_treasurySellFee); transferType = 2; } removeAllFee(); } uint8 transferType = 0; function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity; if ( overMinTokenBalance && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled ) { swapAndLiquify(contractTokenBalance); } if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){ takeFee = false; } bool isTransferBuy = from == uniswapV2Pair; bool isTransferSell = to == uniswapV2Pair; if (!isTransferBuy && !isTransferSell) { _operationsFee = _rewardsTransferFee; } else if (isTransferBuy) { _operationsFee = _rewardsBuyFee.add(_marketingBuyFee).add(_developmentBuyFee).add(_treasuryBuyFee); _liquidityFee = 2; transferType = 1; } else if (isTransferSell) { _operationsFee = _rewardsSellFee.add(_marketingSellFee).add(_developmentSellFee).add(_treasurySellFee); transferType = 2; } removeAllFee(); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity; if ( overMinTokenBalance && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled ) { swapAndLiquify(contractTokenBalance); } if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){ takeFee = false; } bool isTransferBuy = from == uniswapV2Pair; bool isTransferSell = to == uniswapV2Pair; if (!isTransferBuy && !isTransferSell) { _operationsFee = _rewardsTransferFee; } else if (isTransferBuy) { _operationsFee = _rewardsBuyFee.add(_marketingBuyFee).add(_developmentBuyFee).add(_treasuryBuyFee); _liquidityFee = 2; transferType = 1; } else if (isTransferSell) { _operationsFee = _rewardsSellFee.add(_marketingSellFee).add(_developmentSellFee).add(_treasurySellFee); transferType = 2; } removeAllFee(); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity; if ( overMinTokenBalance && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled ) { swapAndLiquify(contractTokenBalance); } if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){ takeFee = false; } bool isTransferBuy = from == uniswapV2Pair; bool isTransferSell = to == uniswapV2Pair; if (!isTransferBuy && !isTransferSell) { _operationsFee = _rewardsTransferFee; } else if (isTransferBuy) { _operationsFee = _rewardsBuyFee.add(_marketingBuyFee).add(_developmentBuyFee).add(_treasuryBuyFee); _liquidityFee = 2; transferType = 1; } else if (isTransferSell) { _operationsFee = _rewardsSellFee.add(_marketingSellFee).add(_developmentSellFee).add(_treasurySellFee); transferType = 2; } removeAllFee(); } _tokenTransfer(from,to,amount,takeFee,transferType); function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { uint256 contractSwapBalance = _pendingRewardsFees.add(_pendingTreasuryFees).add(_pendingMarketingFees).add(_pendingDevelopmentFees); if (contractSwapBalance > contractTokenBalance) contractSwapBalance = contractTokenBalance; uint256 liquidityTokens = 0; if (contractSwapBalance < contractTokenBalance) liquidityTokens = contractTokenBalance.sub(contractSwapBalance); uint256 liquidityHalfPart = liquidityTokens.div(2); contractSwapBalance = contractSwapBalance.add(liquidityHalfPart); uint256 initial_balance = address(this).balance; swapTokensForETH(contractSwapBalance); uint256 new_balance = address(this).balance; uint256 rewards_balance = new_balance.sub(initial_balance); uint256 marketing_eth = rewards_balance.mul(_pendingMarketingFees).div(contractSwapBalance); uint256 development_eth = rewards_balance.mul(_pendingDevelopmentFees).div(contractSwapBalance); uint256 treasury_eth = rewards_balance.mul(_pendingTreasuryFees).div(contractSwapBalance); uint256 reward_eth = rewards_balance.mul(_pendingRewardsFees).div(contractSwapBalance); marketing.sendValue(marketing_eth); development.sendValue(development_eth); treasury.sendValue(treasury_eth); _pendingMarketingFees = 0; _pendingDevelopmentFees = 0; _pendingTreasuryFees = 0; _pendingRewardsFees = 0; uint256 liquidityBalance = balanceOf(address(this)); uint256 rewards_distributed = marketing_eth.add(development_eth).add(treasury_eth).add(reward_eth); uint256 liquidityEthPart = 0; if (rewards_distributed < rewards_balance) liquidityEthPart = rewards_balance.sub(rewards_distributed); if (liquidityEthPart > 0 && liquidityBalance > 0) { addLiquidity(liquidityBalance, liquidityEthPart); emit SwapAndLiquify(liquidityBalance, liquidityEthPart, liquidityBalance); } } function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { uint256 contractSwapBalance = _pendingRewardsFees.add(_pendingTreasuryFees).add(_pendingMarketingFees).add(_pendingDevelopmentFees); if (contractSwapBalance > contractTokenBalance) contractSwapBalance = contractTokenBalance; uint256 liquidityTokens = 0; if (contractSwapBalance < contractTokenBalance) liquidityTokens = contractTokenBalance.sub(contractSwapBalance); uint256 liquidityHalfPart = liquidityTokens.div(2); contractSwapBalance = contractSwapBalance.add(liquidityHalfPart); uint256 initial_balance = address(this).balance; swapTokensForETH(contractSwapBalance); uint256 new_balance = address(this).balance; uint256 rewards_balance = new_balance.sub(initial_balance); uint256 marketing_eth = rewards_balance.mul(_pendingMarketingFees).div(contractSwapBalance); uint256 development_eth = rewards_balance.mul(_pendingDevelopmentFees).div(contractSwapBalance); uint256 treasury_eth = rewards_balance.mul(_pendingTreasuryFees).div(contractSwapBalance); uint256 reward_eth = rewards_balance.mul(_pendingRewardsFees).div(contractSwapBalance); marketing.sendValue(marketing_eth); development.sendValue(development_eth); treasury.sendValue(treasury_eth); _pendingMarketingFees = 0; _pendingDevelopmentFees = 0; _pendingTreasuryFees = 0; _pendingRewardsFees = 0; uint256 liquidityBalance = balanceOf(address(this)); uint256 rewards_distributed = marketing_eth.add(development_eth).add(treasury_eth).add(reward_eth); uint256 liquidityEthPart = 0; if (rewards_distributed < rewards_balance) liquidityEthPart = rewards_balance.sub(rewards_distributed); if (liquidityEthPart > 0 && liquidityBalance > 0) { addLiquidity(liquidityBalance, liquidityEthPart); emit SwapAndLiquify(liquidityBalance, liquidityEthPart, liquidityBalance); } } function swapTokensForETH(uint256 tokenAmount) private { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { _approve(address(this), address(uniswapV2Router), tokenAmount); address(this), tokenAmount, address(this), block.timestamp ); } uniswapV2Router.addLiquidityETH{value: ethAmount}( function _tokenTransfer(address sender, address recipient, uint256 amount, bool takeFee, uint8 transferType) private { if(!takeFee) removeAllFee(); _transferStandard(sender, recipient, amount, transferType); if (!_isExcludedFromFee[recipient] && (recipient != uniswapV2Pair)) require(balanceOf(recipient) < _maxWalletHolding, "Max Wallet holding limit exceeded"); } function _transferStandard(address sender, address recipient, uint256 tAmount, uint8 transferType) private { (uint256 rAmount, uint256 rTransferAmount, uint256 tTransferAmount, uint256 tLiquidity, uint256 tOperations) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _takeOperations(tOperations, transferType); emit Transfer(sender, recipient, tTransferAmount); } }
2,099,754
[ 1, 3240, 281, 358, 1351, 291, 91, 438, 4501, 372, 24237, 2845, 16124, 364, 13667, 310, 16, 17772, 16, 1087, 9646, 5310, 87, 9343, 14036, 261, 74, 8753, 16859, 358, 13667, 310, 471, 17772, 17662, 2413, 13, 9343, 14036, 10935, 603, 2856, 1147, 353, 3832, 272, 1673, 578, 5405, 343, 8905, 261, 21985, 4501, 372, 24237, 2845, 13, 578, 906, 4193, 3086, 3677, 18, 3155, 272, 5408, 854, 7945, 72, 598, 10478, 5320, 29690, 1656, 281, 854, 24893, 471, 13940, 603, 279, 1534, 17, 13866, 10853, 731, 3180, 7720, 1876, 48, 18988, 1164, 353, 2566, 16, 4982, 1492, 326, 24893, 284, 19156, 336, 16859, 487, 12613, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 348, 89, 27113, 353, 1772, 16, 467, 654, 39, 3462, 16, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 5267, 364, 1758, 8843, 429, 31, 203, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 86, 5460, 329, 31, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 88, 5460, 329, 31, 203, 565, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 3238, 389, 5965, 6872, 31, 203, 203, 565, 2874, 261, 2867, 516, 1426, 13, 3238, 389, 291, 16461, 1265, 14667, 31, 203, 203, 565, 1758, 8843, 429, 1071, 13667, 310, 31, 203, 565, 1758, 8843, 429, 1071, 17772, 31, 203, 565, 1758, 8843, 429, 1071, 9787, 345, 22498, 31, 203, 203, 565, 1758, 8843, 429, 3238, 283, 20099, 31, 203, 203, 565, 2254, 5034, 3238, 5381, 4552, 273, 4871, 11890, 5034, 12, 20, 1769, 203, 565, 2254, 5034, 3238, 389, 88, 5269, 273, 2130, 380, 1728, 636, 26, 380, 1728, 636, 29, 31, 203, 565, 2254, 5034, 3238, 389, 86, 5269, 273, 261, 6694, 300, 261, 6694, 738, 389, 88, 5269, 10019, 203, 203, 565, 533, 3238, 389, 529, 273, 315, 17072, 27113, 14432, 203, 565, 533, 3238, 389, 7175, 273, 315, 55, 5370, 47, 51, 14432, 203, 565, 2254, 28, 3238, 389, 31734, 273, 2468, 31, 203, 203, 203, 203, 565, 2254, 5034, 1071, 389, 3355, 21747, 38, 9835, 14667, 273, 1381, 31, 203, 565, 2254, 5034, 1071, 389, 3355, 21747, 55, 1165, 14667, 273, 576, 2 ]
./full_match/1/0x81C4Bd600793EBd1C0323604E1F455fE50A951F8/sources/lib/optimism/packages/contracts-bedrock/contracts/L1/OptimismPortal.sol
* @notice Computes the minimum gas limit for a deposit. The minimum gas limit linearly increases based on the size of the calldata. This is to prevent users from creating L2 resource usage without paying for it. This function can be used when interacting with the portal to ensure forwards compatibility./
function minimumGasLimit(uint64 _byteCount) public pure returns (uint64) { return _byteCount * 16 + 21000; }
4,920,406
[ 1, 10743, 326, 5224, 16189, 1800, 364, 279, 443, 1724, 18, 1021, 5224, 16189, 1800, 540, 9103, 715, 7033, 3304, 2511, 603, 326, 963, 434, 326, 745, 892, 18, 1220, 353, 358, 5309, 540, 3677, 628, 4979, 511, 22, 1058, 4084, 2887, 8843, 310, 364, 518, 18, 1220, 445, 540, 848, 506, 1399, 1347, 16592, 310, 598, 326, 11899, 358, 3387, 24578, 8926, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 5224, 27998, 3039, 12, 11890, 1105, 389, 7229, 1380, 13, 1071, 16618, 1135, 261, 11890, 1105, 13, 288, 203, 3639, 327, 389, 7229, 1380, 380, 2872, 397, 9035, 3784, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-04-22 */ // File: @openzeppelin/contracts/utils/Context.sol // 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 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 payable(msg.sender); } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/introspection/IERC165.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // File: @openzeppelin/contracts/token/ERC721/IERC721Metadata.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // File: @openzeppelin/contracts/introspection/ERC165.sol pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/utils/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 EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @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; } } // File: @openzeppelin/contracts/utils/EnumerableMap.sol pragma solidity ^0.8.0; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * The following map types are supported: * * - `uint256 -> address` (`UintToAddressMap`) since v3.0.0 * - `address -> uint256` (`AddressToUintMap`) since v4.6.0 */ library EnumerableMap { using EnumerableSet for EnumerableSet.Bytes32Set; // 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 Map { // Storage of keys EnumerableSet.Bytes32Set _keys; mapping(bytes32 => bytes32) _values; } /** * @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) { map._values[key] = value; return map._keys.add(key); } /** * @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) { delete map._values[key]; return map._keys.remove(key); } /** * @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._keys.contains(key); } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._keys.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) { bytes32 key = map._keys.at(index); return (key, map._values[key]); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { bytes32 value = map._values[key]; if (value == bytes32(0)) { return (_contains(map, key), bytes32(0)); } else { return (true, 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) { bytes32 value = map._values[key]; require(value != 0 || _contains(map, key), "EnumerableMap: nonexistent key"); return value; } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get( Map storage map, bytes32 key, string memory errorMessage ) private view returns (bytes32) { bytes32 value = map._values[key]; require(value != 0 || _contains(map, key), errorMessage); return value; } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set( UintToAddressMap storage map, uint256 key, address value ) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get( UintToAddressMap storage map, uint256 key, string memory errorMessage ) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); } // AddressToUintMap struct AddressToUintMap { 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( AddressToUintMap storage map, address key, uint256 value ) internal returns (bool) { return _set(map._inner, bytes32(uint256(uint160(key))), bytes32(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(AddressToUintMap storage map, address key) internal returns (bool) { return _remove(map._inner, bytes32(uint256(uint160(key)))); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(AddressToUintMap storage map, address key) internal view returns (bool) { return _contains(map._inner, bytes32(uint256(uint160(key)))); } /** * @dev Returns the number of elements in the map. O(1). */ function length(AddressToUintMap 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(AddressToUintMap storage map, uint256 index) internal view returns (address, uint256) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (address(uint160(uint256(key))), uint256(value)); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(AddressToUintMap storage map, address key) internal view returns (bool, uint256) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(uint256(uint160(key)))); return (success, uint256(value)); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(AddressToUintMap storage map, address key) internal view returns (uint256) { return uint256(_get(map._inner, bytes32(uint256(uint160(key))))); } } // File: @openzeppelin/contracts/utils/Strings.sol 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); } } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol pragma solidity ^0.8.0; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs //mapping (uint256 => string) private _tokenURIs; // Base URI string private _baseURI = "QmXApPBVRSZQR5yA9ntpeHPZPno7yNXhT2rEdQoTTB8beJ"; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); //string memory _tokenURI = _tokenURIs[tokenId]; string memory base = baseURI(); // If there is no base URI, return the token URI. /*if (bytes(base).length == 0) { return _tokenURI; }*/ // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). /*if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); }*/ // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked("ipfs://", base, "/", tokenId.toString(), ".json")); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view virtual returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _tokenOwners.contains(tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); // internal owner _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) /*if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; }*/ _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ /*function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; }*/ /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } /** * @dev Approve `to` to operate on `tokenId` * * Emits an {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } pragma solidity ^0.8.0; /* * @title GunrackAmmo contract * @dev Extends ERC721 Non-Fungible Token Standard basic implementation * twitter: @GunrackFinance * discord: https://discord.gg/4Sc5UEdf * web: https://gunrack.finance/ammo/ */ contract GunrackAmmo is ERC721, Ownable { string public GRA_PROVENANCE = ""; uint256 public constant ammoPrice = 30000000000000000; //0.03 ETH uint256 public constant maxAmmoPurchase = 10; uint256 public MAX_AMMO; bool public saleIsActive = false; constructor(string memory name, string memory symbol, uint256 maxNftSupply) ERC721(name, symbol) { MAX_AMMO = maxNftSupply; } function withdraw() public onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } /** * Set some Ammo aside */ function reserveAmmo() public onlyOwner { uint256 supply = totalSupply(); uint256 i; for (i = 1; i < 3; i++) { _safeMint(msg.sender, supply + i); } } /* * Set provenance once it's calculated */ function setProvenanceHash(string memory provenanceHash) public onlyOwner { GRA_PROVENANCE = provenanceHash; } function setBaseURI(string memory baseURI) public onlyOwner { _setBaseURI(baseURI); } /* * Pause sale if active, make active if paused */ function flipSaleState() public onlyOwner { saleIsActive = !saleIsActive; } /** * Mints Ammo */ function mintAmmo(uint256 numberOfTokens) public payable { uint256 supply = totalSupply(); require(saleIsActive, "Sale must be active to mint Ammo"); require(numberOfTokens <= maxAmmoPurchase, "Can only mint 10 tokens at a time"); require(supply + numberOfTokens <= MAX_AMMO, "Purchase would exceed max supply of Ammo"); require(ammoPrice * numberOfTokens <= msg.value, "Ether value sent is not correct"); for(uint256 i = 1; i < numberOfTokens; i++) { if (supply < MAX_AMMO) { _safeMint(msg.sender, supply); } } } }
File: @openzeppelin/contracts/access/Ownable.sol* @dev Contract module which provides a basic access control mechanism, where there is an account (an owner) that can be granted exclusive access to specific functions. By default, the owner account will be the one that deploys the contract. This can later be changed with {transferOwnership}. This module is used through inheritance. It will make available the modifier `onlyOwner`, which can be applied to your functions to restrict their use to the owner./
abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } 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); } } } pragma solidity ^0.8.0; constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function owner() public view virtual returns (address) { return _owner; } modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } }
13,466,032
[ 1, 812, 30, 632, 3190, 94, 881, 84, 292, 267, 19, 16351, 87, 19, 3860, 19, 5460, 429, 18, 18281, 225, 13456, 1605, 1492, 8121, 279, 5337, 2006, 3325, 12860, 16, 1625, 1915, 353, 392, 2236, 261, 304, 3410, 13, 716, 848, 506, 17578, 12060, 2006, 358, 2923, 4186, 18, 2525, 805, 16, 326, 3410, 2236, 903, 506, 326, 1245, 716, 5993, 383, 1900, 326, 6835, 18, 1220, 848, 5137, 506, 3550, 598, 288, 13866, 5460, 12565, 5496, 1220, 1605, 353, 1399, 3059, 16334, 18, 2597, 903, 1221, 2319, 326, 9606, 1375, 3700, 5541, 9191, 1492, 848, 506, 6754, 358, 3433, 4186, 358, 13108, 3675, 999, 358, 326, 3410, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 17801, 6835, 14223, 6914, 353, 1772, 288, 203, 565, 1758, 3238, 389, 8443, 31, 203, 203, 565, 871, 14223, 9646, 5310, 1429, 4193, 12, 2867, 8808, 2416, 5541, 16, 1758, 8808, 394, 5541, 1769, 203, 203, 565, 445, 389, 5771, 1345, 5912, 12, 2867, 628, 16, 1758, 358, 16, 2254, 5034, 1147, 548, 13, 2713, 5024, 288, 289, 203, 3639, 1731, 3778, 327, 892, 273, 358, 18, 915, 1477, 12, 21457, 18, 3015, 1190, 4320, 12, 203, 5411, 467, 654, 39, 27, 5340, 12952, 12, 869, 2934, 265, 654, 39, 27, 5340, 8872, 18, 9663, 16, 203, 5411, 389, 3576, 12021, 9334, 203, 5411, 628, 16, 203, 5411, 1147, 548, 16, 203, 5411, 389, 892, 203, 3639, 262, 16, 315, 654, 39, 27, 5340, 30, 7412, 358, 1661, 4232, 39, 27, 5340, 12952, 2348, 264, 8863, 203, 3639, 1731, 24, 5221, 273, 24126, 18, 3922, 12, 2463, 892, 16, 261, 3890, 24, 10019, 203, 3639, 327, 261, 18341, 422, 389, 654, 39, 27, 5340, 67, 27086, 20764, 1769, 203, 565, 289, 203, 203, 565, 289, 203, 203, 97, 203, 203, 203, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 203, 565, 3885, 1832, 2713, 288, 203, 3639, 1758, 1234, 12021, 273, 389, 3576, 12021, 5621, 203, 3639, 389, 8443, 273, 1234, 12021, 31, 203, 3639, 3626, 14223, 9646, 5310, 1429, 4193, 12, 2867, 12, 20, 3631, 1234, 12021, 1769, 203, 565, 289, 203, 203, 565, 445, 3410, 1435, 1071, 1476, 5024, 1135, 261, 2867, 13, 288, 203, 3639, 2 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/Math.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "./lib/Babylonian.sol"; import "./owner/Operator.sol"; import "./utils/ContractGuard.sol"; import "./interfaces/IBasisAsset.sol"; import "./interfaces/IOracle.sol"; import "./interfaces/ITheoretics.sol"; import "./interfaces/IERC20Burnable.sol"; contract Treasury is ContractGuard { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; /* ========= CONSTANT VARIABLES ======== */ uint256 public constant PERIOD = 6 hours; /* ========== STATE VARIABLES ========== */ // governance address public operator; // flags bool public initialized = false; // epoch uint256 public startTime; uint256 public epoch = 0; uint256 public epochSupplyContractionLeft = 0; // exclusions from total supply address[] public excludedFromTotalSupply; // core components address public game; address public hodl; address public theory; address public theoretics; address public bondTreasury; address public gameOracle; // price uint256 public gamePriceOne; uint256 public gamePriceCeiling; uint256 public seigniorageSaved; uint256[] public supplyTiers; uint256[] public maxExpansionTiers; uint256 public maxSupplyExpansionPercent; uint256 public bondDepletionFloorPercent; uint256 public seigniorageExpansionFloorPercent; uint256 public maxSupplyContractionPercent; uint256 public maxDebtRatioPercent; uint256 public bondSupplyExpansionPercent; // 28 first epochs (1 week) with 4.5% expansion regardless of GAME price uint256 public bootstrapEpochs; uint256 public bootstrapSupplyExpansionPercent; /* =================== Added variables =================== */ uint256 public previousEpochGamePrice; uint256 public maxDiscountRate; // when purchasing bond uint256 public maxPremiumRate; // when redeeming bond uint256 public discountPercent; uint256 public premiumThreshold; uint256 public premiumPercent; uint256 public mintingFactorForPayingDebt; // print extra GAME during debt phase address public daoFund; uint256 public daoFundSharedPercent; address public devFund; uint256 public devFundSharedPercent; /* =================== Events =================== */ event Initialized(address indexed executor, uint256 at); event BurnedBonds(address indexed from, uint256 bondAmount); event RedeemedBonds(address indexed from, uint256 gameAmount, uint256 bondAmount); event BoughtBonds(address indexed from, uint256 gameAmount, uint256 bondAmount); event TreasuryFunded(uint256 timestamp, uint256 seigniorage); event theoreticsFunded(uint256 timestamp, uint256 seigniorage); event DaoFundFunded(uint256 timestamp, uint256 seigniorage); event DevFundFunded(uint256 timestamp, uint256 seigniorage); /* =================== Modifier =================== */ modifier onlyOperator() { require(operator == msg.sender, "Treasury: caller is not the operator"); _; } modifier checkCondition { require(block.timestamp >= startTime, "Treasury: not started yet"); _; } modifier checkEpoch { require(block.timestamp >= nextEpochPoint(), "Treasury: not opened yet"); _; epoch = epoch.add(1); epochSupplyContractionLeft = (getGamePrice() > gamePriceCeiling) ? 0 : getGameCirculatingSupply().mul(maxSupplyContractionPercent).div(10000); } modifier checkOperator { require( IBasisAsset(game).operator() == address(this) && IBasisAsset(hodl).operator() == address(this) && IBasisAsset(theory).operator() == address(this) && Operator(theoretics).operator() == address(this), "Treasury: need more permission" ); _; } modifier notInitialized { require(!initialized, "Treasury: already initialized"); _; } /* ========== VIEW FUNCTIONS ========== */ function isInitialized() public view returns (bool) { return initialized; } // epoch function nextEpochPoint() public view returns (uint256) { return startTime.add(epoch.mul(PERIOD)); } function shouldAllocateSeigniorage() external view returns (bool) // For bots. { return block.timestamp >= startTime && block.timestamp >= nextEpochPoint() && ITheoretics(theoretics).totalSupply() > 0; } // oracle function getGamePrice() public view returns (uint256 gamePrice) { try IOracle(gameOracle).consult(game, 1e18) returns (uint144 price) { return uint256(price); } catch { revert("Treasury: failed to consult GAME price from the oracle"); } } function getGameUpdatedPrice() public view returns (uint256 _gamePrice) { try IOracle(gameOracle).twap(game, 1e18) returns (uint144 price) { return uint256(price); } catch { revert("Treasury: failed to consult GAME price from the oracle"); } } // budget function getReserve() public view returns (uint256) { return seigniorageSaved; } function getBurnableGameLeft() public view returns (uint256 _burnableGameLeft) { uint256 _gamePrice = getGamePrice(); if (_gamePrice <= gamePriceOne) { uint256 _gameSupply = getGameCirculatingSupply(); uint256 _bondMaxSupply = _gameSupply.mul(maxDebtRatioPercent).div(10000); uint256 _bondSupply = IERC20(hodl).totalSupply(); if (_bondMaxSupply > _bondSupply) { uint256 _maxMintableBond = _bondMaxSupply.sub(_bondSupply); uint256 _maxBurnableGame = _maxMintableBond.mul(_gamePrice).div(1e18); _burnableGameLeft = Math.min(epochSupplyContractionLeft, _maxBurnableGame); } } } function getRedeemableBonds() external view returns (uint256) { uint256 _gamePrice = getGamePrice(); if (_gamePrice > gamePriceCeiling) { uint256 _totalGame = IERC20(game).balanceOf(address(this)); uint256 _rate = getBondPremiumRate(); if (_rate > 0) { return _totalGame.mul(1e18).div(_rate); } } return 0; } function getBondDiscountRate() public view returns (uint256 _rate) { uint256 _gamePrice = getGamePrice(); if (_gamePrice <= gamePriceOne) { if (discountPercent == 0) { // no discount _rate = gamePriceOne; } else { uint256 _bondAmount = gamePriceOne.mul(1e18).div(_gamePrice); // to burn 1 GAME uint256 _discountAmount = _bondAmount.sub(gamePriceOne).mul(discountPercent).div(10000); _rate = gamePriceOne.add(_discountAmount); if (maxDiscountRate > 0 && _rate > maxDiscountRate) { _rate = maxDiscountRate; } } } } function getBondPremiumRate() public view returns (uint256 _rate) { uint256 _gamePrice = getGamePrice(); if (_gamePrice > gamePriceCeiling) { uint256 _gamePricePremiumThreshold = gamePriceOne.mul(premiumThreshold).div(100); if (_gamePrice >= _gamePricePremiumThreshold) { //Price > 1.10 uint256 _premiumAmount = _gamePrice.sub(gamePriceOne).mul(premiumPercent).div(10000); _rate = gamePriceOne.add(_premiumAmount); if (maxPremiumRate > 0 && _rate > maxPremiumRate) { _rate = maxPremiumRate; } } else { // no premium bonus _rate = gamePriceOne; } } } /* ========== GOVERNANCE ========== */ function initialize( address _game, address _hodl, address _theory, address _gameOracle, address _theoretics, address _genesisPool, address _daoFund, address _devFund, uint256 _startTime ) public notInitialized { initialized = true; // We could require() for all of these... game = _game; hodl = _hodl; theory = _theory; gameOracle = _gameOracle; theoretics = _theoretics; daoFund = _daoFund; devFund = _devFund; require(block.timestamp < _startTime, "late"); startTime = _startTime; gamePriceOne = 10**18; gamePriceCeiling = gamePriceOne.mul(101).div(100); // exclude contracts from total supply excludedFromTotalSupply.push(_genesisPool); // Dynamic max expansion percent supplyTiers = [0 ether, 500000 ether, 1000000 ether, 1500000 ether, 2000000 ether, 5000000 ether, 10000000 ether, 20000000 ether, 50000000 ether]; maxExpansionTiers = [450, 400, 350, 300, 250, 200, 150, 125, 100]; maxSupplyExpansionPercent = 400; // Upto 4.0% supply for expansion bondDepletionFloorPercent = 10000; // 100% of Bond supply for depletion floor seigniorageExpansionFloorPercent = 3500; // At least 35% of expansion reserved for theoretics maxSupplyContractionPercent = 300; // Upto 3.0% supply for contraction (to burn GAME and mint HODL) maxDebtRatioPercent = 3500; // Upto 35% supply of HODL to purchase bondSupplyExpansionPercent = 500; // maximum 5% emissions per epoch for POL bonds premiumThreshold = 110; premiumPercent = 7000; // First 12 epochs with 5% expansion bootstrapEpochs = 12; bootstrapSupplyExpansionPercent = 500; // set seigniorageSaved to it's balance seigniorageSaved = IERC20(game).balanceOf(address(this)); operator = msg.sender; emit Initialized(msg.sender, block.number); } function setOperator(address _operator) external onlyOperator { operator = _operator; } function setTheoretics(address _theoretics) external onlyOperator { // Scary function, but also can be used to upgrade. However, since I don't have a multisig to start, and it isn't THAT important, I'm going to leave this be. theoretics = _theoretics; } function setGameOracle(address _gameOracle) external onlyOperator { // See above. gameOracle = _gameOracle; } function setGamePriceCeiling(uint256 _gamePriceCeiling) external onlyOperator { // I don't see this changing, so I'm going to leave this be. require(_gamePriceCeiling >= gamePriceOne && _gamePriceCeiling <= gamePriceOne.mul(120).div(100), "out of range"); // [$1.0, $1.2] gamePriceCeiling = _gamePriceCeiling; } function setMaxSupplyExpansionPercents(uint256 _maxSupplyExpansionPercent) external onlyOperator { // I don't see this changing, so I'm going to leave this be. require(_maxSupplyExpansionPercent >= 10 && _maxSupplyExpansionPercent <= 1000, "_maxSupplyExpansionPercent: out of range"); // [0.1%, 10%] maxSupplyExpansionPercent = _maxSupplyExpansionPercent; } function setSupplyTiersEntry(uint8 _index, uint256 _value) external onlyOperator returns (bool) { require(_index >= 0, "Index has to be higher than 0"); require(_index < 9, "Index has to be lower than count of tiers"); if (_index > 0) { require(_value > supplyTiers[_index - 1]); } if (_index < 8) { require(_value < supplyTiers[_index + 1]); } supplyTiers[_index] = _value; return true; } function setMaxExpansionTiersEntry(uint8 _index, uint256 _value) external onlyOperator returns (bool) { require(_index >= 0, "Index has to be higher than 0"); require(_index < 9, "Index has to be lower than count of tiers"); require(_value >= 10 && _value <= 1000, "_value: out of range"); // [0.1%, 10%] maxExpansionTiers[_index] = _value; return true; } function setBondDepletionFloorPercent(uint256 _bondDepletionFloorPercent) external onlyOperator { require(_bondDepletionFloorPercent >= 500 && _bondDepletionFloorPercent <= 10000, "out of range"); // [5%, 100%] bondDepletionFloorPercent = _bondDepletionFloorPercent; } function setMaxSupplyContractionPercent(uint256 _maxSupplyContractionPercent) external onlyOperator { require(_maxSupplyContractionPercent >= 100 && _maxSupplyContractionPercent <= 1500, "out of range"); // [0.1%, 15%] maxSupplyContractionPercent = _maxSupplyContractionPercent; } function setMaxDebtRatioPercent(uint256 _maxDebtRatioPercent) external onlyOperator { require(_maxDebtRatioPercent >= 1000 && _maxDebtRatioPercent <= 10000, "out of range"); // [10%, 100%] maxDebtRatioPercent = _maxDebtRatioPercent; } function setBootstrap(uint256 _bootstrapEpochs, uint256 _bootstrapSupplyExpansionPercent) external onlyOperator { require(_bootstrapEpochs <= 120, "_bootstrapEpochs: out of range"); // <= 1 month require(_bootstrapSupplyExpansionPercent >= 100 && _bootstrapSupplyExpansionPercent <= 1000, "_bootstrapSupplyExpansionPercent: out of range"); // [1%, 10%] bootstrapEpochs = _bootstrapEpochs; bootstrapSupplyExpansionPercent = _bootstrapSupplyExpansionPercent; } function setExtraFunds( address _daoFund, uint256 _daoFundSharedPercent, address _devFund, uint256 _devFundSharedPercent ) external onlyOperator { require(_daoFund != address(0), "zero"); require(_daoFundSharedPercent <= 3000, "out of range"); // <= 30% require(_devFund != address(0), "zero"); require(_devFundSharedPercent <= 1000, "out of range"); // <= 10% daoFund = _daoFund; daoFundSharedPercent = _daoFundSharedPercent; devFund = _devFund; devFundSharedPercent = _devFundSharedPercent; } function setMaxDiscountRate(uint256 _maxDiscountRate) external onlyOperator { maxDiscountRate = _maxDiscountRate; } function setMaxPremiumRate(uint256 _maxPremiumRate) external onlyOperator { maxPremiumRate = _maxPremiumRate; } function setDiscountPercent(uint256 _discountPercent) external onlyOperator { require(_discountPercent <= 20000, "_discountPercent is over 200%"); discountPercent = _discountPercent; } function setPremiumThreshold(uint256 _premiumThreshold) external onlyOperator { require(_premiumThreshold >= gamePriceCeiling, "_premiumThreshold exceeds gamePriceCeiling"); require(_premiumThreshold <= 150, "_premiumThreshold is higher than 1.5"); premiumThreshold = _premiumThreshold; } function setPremiumPercent(uint256 _premiumPercent) external onlyOperator { require(_premiumPercent <= 20000, "_premiumPercent is over 200%"); premiumPercent = _premiumPercent; } function setMintingFactorForPayingDebt(uint256 _mintingFactorForPayingDebt) external onlyOperator { require(_mintingFactorForPayingDebt == 0 || (_mintingFactorForPayingDebt >= 10000 && _mintingFactorForPayingDebt <= 20000), "_mintingFactorForPayingDebt: out of range"); // [100%, 200%] mintingFactorForPayingDebt = _mintingFactorForPayingDebt; } function setBondSupplyExpansionPercent(uint256 _bondSupplyExpansionPercent) external onlyOperator { bondSupplyExpansionPercent = _bondSupplyExpansionPercent; } /* ========== MUTABLE FUNCTIONS ========== */ function _updateGamePrice() internal { try IOracle(gameOracle).update() {} catch {} } function getGameCirculatingSupply() public view returns (uint256) { IERC20 gameErc20 = IERC20(game); uint256 totalSupply = gameErc20.totalSupply(); uint256 balanceExcluded = 0; uint256 entryId; uint256 len = excludedFromTotalSupply.length; for (entryId = 0; entryId < len; entryId += 1) { balanceExcluded = balanceExcluded.add(gameErc20.balanceOf(excludedFromTotalSupply[entryId])); } return totalSupply.sub(balanceExcluded); } function buyBonds(uint256 _gameAmount, uint256 targetPrice) external onlyOneBlock checkCondition checkOperator { require(_gameAmount > 0, "Treasury: cannot purchase bonds with zero amount"); uint256 gamePrice = getGamePrice(); require(gamePrice == targetPrice, "Treasury: GAME price moved"); require( gamePrice < gamePriceOne, // price < $1 "Treasury: gamePrice not eligible for bond purchase" ); require(_gameAmount <= epochSupplyContractionLeft, "Treasury: Not enough bonds left to purchase"); uint256 _rate = getBondDiscountRate(); require(_rate > 0, "Treasury: invalid bond rate"); uint256 _bondAmount = _gameAmount.mul(_rate).div(1e18); uint256 gameSupply = getGameCirculatingSupply(); uint256 newBondSupply = IERC20(hodl).totalSupply().add(_bondAmount); require(newBondSupply <= gameSupply.mul(maxDebtRatioPercent).div(10000), "over max debt ratio"); IBasisAsset(game).burnFrom(msg.sender, _gameAmount); IBasisAsset(hodl).mint(msg.sender, _bondAmount); epochSupplyContractionLeft = epochSupplyContractionLeft.sub(_gameAmount); _updateGamePrice(); emit BoughtBonds(msg.sender, _gameAmount, _bondAmount); } function redeemBonds(uint256 _bondAmount, uint256 targetPrice) external onlyOneBlock checkCondition checkOperator { require(_bondAmount > 0, "Treasury: cannot redeem bonds with zero amount"); uint256 gamePrice = getGamePrice(); require(gamePrice == targetPrice, "Treasury: GAME price moved"); require( gamePrice > gamePriceCeiling, // price > $1.01 "Treasury: gamePrice not eligible for bond redemption" ); uint256 _rate = getBondPremiumRate(); require(_rate > 0, "Treasury: invalid bond rate"); uint256 _gameAmount = _bondAmount.mul(_rate).div(1e18); require(IERC20(game).balanceOf(address(this)) >= _gameAmount, "Treasury: treasury has no more budget"); seigniorageSaved = seigniorageSaved.sub(Math.min(seigniorageSaved, _gameAmount)); IBasisAsset(hodl).burnFrom(msg.sender, _bondAmount); IERC20(game).safeTransfer(msg.sender, _gameAmount); _updateGamePrice(); emit RedeemedBonds(msg.sender, _gameAmount, _bondAmount); } function _sendToTheoretics(uint256 _amount) internal { IBasisAsset(game).mint(address(this), _amount); uint256 _daoFundSharedAmount = 0; if (daoFundSharedPercent > 0) { _daoFundSharedAmount = _amount.mul(daoFundSharedPercent).div(10000); IERC20(game).transfer(daoFund, _daoFundSharedAmount); emit DaoFundFunded(block.timestamp, _daoFundSharedAmount); } uint256 _devFundSharedAmount = 0; if (devFundSharedPercent > 0) { _devFundSharedAmount = _amount.mul(devFundSharedPercent).div(10000); IERC20(game).transfer(devFund, _devFundSharedAmount); emit DevFundFunded(block.timestamp, _devFundSharedAmount); } _amount = _amount.sub(_daoFundSharedAmount).sub(_devFundSharedAmount); IERC20(game).safeApprove(theoretics, 0); IERC20(game).safeApprove(theoretics, _amount); ITheoretics(theoretics).allocateSeigniorage(_amount); emit theoreticsFunded(block.timestamp, _amount); } function _calculateMaxSupplyExpansionPercent(uint256 _gameSupply) internal returns (uint256) { for (uint8 tierId = 8; tierId >= 0; --tierId) { if (_gameSupply >= supplyTiers[tierId]) { maxSupplyExpansionPercent = maxExpansionTiers[tierId]; break; } } return maxSupplyExpansionPercent; } function allocateSeigniorage() external onlyOneBlock checkCondition checkEpoch checkOperator { _updateGamePrice(); previousEpochGamePrice = getGamePrice(); uint256 gameSupply = getGameCirculatingSupply().sub(seigniorageSaved); if (epoch < bootstrapEpochs) { // 28 first epochs with 4.5% expansion _sendToTheoretics(gameSupply.mul(bootstrapSupplyExpansionPercent).div(10000)); } else { if (previousEpochGamePrice > gamePriceCeiling) { // Expansion ($GAME Price > 1 $FTM): there is some seigniorage to be allocated uint256 bondSupply = IERC20(hodl).totalSupply(); uint256 _percentage = previousEpochGamePrice.sub(gamePriceOne); uint256 _savedForBond = 0; uint256 _savedForTheoretics; uint256 _mse = _calculateMaxSupplyExpansionPercent(gameSupply).mul(1e14); if (_percentage > _mse) { _percentage = _mse; } if (seigniorageSaved >= bondSupply.mul(bondDepletionFloorPercent).div(10000)) { // saved enough to pay debt, mint as usual rate _savedForTheoretics = gameSupply.mul(_percentage).div(1e18); } else { // have not saved enough to pay debt, mint more uint256 _seigniorage = gameSupply.mul(_percentage).div(1e18); _savedForTheoretics = _seigniorage.mul(seigniorageExpansionFloorPercent).div(10000); _savedForBond = _seigniorage.sub(_savedForTheoretics); if (mintingFactorForPayingDebt > 0) { _savedForBond = _savedForBond.mul(mintingFactorForPayingDebt).div(10000); } } if (_savedForTheoretics > 0) { _sendToTheoretics(_savedForTheoretics); } if (_savedForBond > 0) { seigniorageSaved = seigniorageSaved.add(_savedForBond); IBasisAsset(game).mint(address(this), _savedForBond); emit TreasuryFunded(block.timestamp, _savedForBond); } } } } function governanceRecoverUnsupported( IERC20 _token, uint256 _amount, address _to ) external onlyOperator { // do not allow to drain core tokens require(address(_token) != address(game), "game"); require(address(_token) != address(hodl), "bond"); require(address(_token) != address(theory), "share"); _token.safeTransfer(_to, _amount); } function theoreticsSetOperator(address _operator) external onlyOperator { ITheoretics(theoretics).setOperator(_operator); } function theoreticsSetLockUp(uint256 _withdrawLockupEpochs, uint256 _rewardLockupEpochs, uint256 _pegMaxUnlock) external onlyOperator { ITheoretics(theoretics).setLockUp(_withdrawLockupEpochs, _rewardLockupEpochs, _pegMaxUnlock); } function theoreticsAllocateSeigniorage(uint256 amount) external onlyOperator { ITheoretics(theoretics).allocateSeigniorage(amount); } function theoreticsGetCurrentWithdrawEpochs() public view returns (uint256) { return ITheoretics(theoretics).getCurrentWithdrawEpochs(); } function theoreticsGetCurrentClaimEpochs() public view returns (uint256) { return ITheoretics(theoretics).getCurrentClaimEpochs(); } function theoreticsGetWithdrawFeeOf(address _user) public view returns (uint256) { return ITheoretics(theoretics).getWithdrawFeeOf(_user); } function theoreticsGovernanceRecoverUnsupported( address _token, uint256 _amount, address _to ) external onlyOperator { ITheoretics(theoretics).governanceRecoverUnsupported(_token, _amount, _to); } function theoreticsGetLockPercentage() public view returns (uint256) { return ITheoretics(theoretics).getLockPercentage(); } function burn( address _token, uint256 _amount ) external onlyOperator { IERC20Burnable(_token).burn(_amount); // Burn any token that we own! Now we can burn THEORY and such with no problem to deflate it. } // Allow us to delay or begin earlier if we have not started yet. function setStartTime( uint256 _time ) public onlyOperator { require(block.timestamp < startTime, "Already started."); require(block.timestamp < _time, "Time input is too early."); startTime = _time; } }
Burn any token that we own! Now we can burn THEORY and such with no problem to deflate it.
IERC20Burnable(_token).burn(_amount);
5,393,635
[ 1, 38, 321, 1281, 1147, 716, 732, 4953, 5, 4494, 732, 848, 18305, 12786, 3964, 471, 4123, 598, 1158, 6199, 358, 1652, 20293, 518, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 467, 654, 39, 3462, 38, 321, 429, 24899, 2316, 2934, 70, 321, 24899, 8949, 1769, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.20; // File: contracts/usingOraclize.sol // <ORACLIZE_API> /* Copyright (c) 2015-2016 Oraclize SRL Copyright (c) 2016 Oraclize LTD 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 SOFTWARE. */ // This api is currently targeted at 0.4.18, please import oraclizeAPI_pre0.4.sol or oraclizeAPI_0.4 where necessary pragma solidity >=0.4.18;// Incompatible compiler version... please select one stated within pragma solidity or use different oraclizeAPI version contract OraclizeI { address public cbAddress; function query(uint _timestamp, string _datasource, string _arg) external payable returns (bytes32 _id); function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) external payable returns (bytes32 _id); function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) public payable returns (bytes32 _id); function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) external payable returns (bytes32 _id); function queryN(uint _timestamp, string _datasource, bytes _argN) public payable returns (bytes32 _id); function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) external payable returns (bytes32 _id); function getPrice(string _datasource) public returns (uint _dsprice); function getPrice(string _datasource, uint gaslimit) public returns (uint _dsprice); function setProofType(byte _proofType) external; function setCustomGasPrice(uint _gasPrice) external; function randomDS_getSessionPubKeyHash() external constant returns(bytes32); } contract OraclizeAddrResolverI { function getAddress() public returns (address _addr); } /* Begin solidity-cborutils https://github.com/smartcontractkit/solidity-cborutils MIT License Copyright (c) 2018 SmartContract ChainLink, Ltd. 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 SOFTWARE. */ library Buffer { struct buffer { bytes buf; uint capacity; } function init(buffer memory buf, uint _capacity) internal pure { uint capacity = _capacity; if(capacity % 32 != 0) capacity += 32 - (capacity % 32); // Allocate space for the buffer data buf.capacity = capacity; assembly { let ptr := mload(0x40) mstore(buf, ptr) mstore(ptr, 0) mstore(0x40, add(ptr, capacity)) } } function resize(buffer memory buf, uint capacity) private pure { bytes memory oldbuf = buf.buf; init(buf, capacity); append(buf, oldbuf); } function max(uint a, uint b) private pure returns(uint) { if(a > b) { return a; } return b; } /** * @dev Appends a byte array to the end of the buffer. Resizes if doing so * would exceed the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer. */ function append(buffer memory buf, bytes data) internal pure returns(buffer memory) { if(data.length + buf.buf.length > buf.capacity) { resize(buf, max(buf.capacity, data.length) * 2); } uint dest; uint src; uint len = data.length; assembly { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Start address = buffer address + buffer length + sizeof(buffer length) dest := add(add(bufptr, buflen), 32) // Update buffer length mstore(bufptr, add(buflen, mload(data))) src := add(data, 32) } // Copy word-length chunks while possible for(; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } return buf; } /** * @dev Appends a byte to the end of the buffer. Resizes if doing so would * exceed the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer. */ function append(buffer memory buf, uint8 data) internal pure { if(buf.buf.length + 1 > buf.capacity) { resize(buf, buf.capacity * 2); } assembly { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Address = buffer address + buffer length + sizeof(buffer length) let dest := add(add(bufptr, buflen), 32) mstore8(dest, data) // Update buffer length mstore(bufptr, add(buflen, 1)) } } /** * @dev Appends a byte to the end of the buffer. Resizes if doing so would * exceed the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer. */ function appendInt(buffer memory buf, uint data, uint len) internal pure returns(buffer memory) { if(len + buf.buf.length > buf.capacity) { resize(buf, max(buf.capacity, len) * 2); } uint mask = 256 ** len - 1; assembly { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Address = buffer address + buffer length + sizeof(buffer length) + len let dest := add(add(bufptr, buflen), len) mstore(dest, or(and(mload(dest), not(mask)), data)) // Update buffer length mstore(bufptr, add(buflen, len)) } return buf; } } library CBOR { using Buffer for Buffer.buffer; uint8 private constant MAJOR_TYPE_INT = 0; uint8 private constant MAJOR_TYPE_NEGATIVE_INT = 1; uint8 private constant MAJOR_TYPE_BYTES = 2; uint8 private constant MAJOR_TYPE_STRING = 3; uint8 private constant MAJOR_TYPE_ARRAY = 4; uint8 private constant MAJOR_TYPE_MAP = 5; uint8 private constant MAJOR_TYPE_CONTENT_FREE = 7; function encodeType(Buffer.buffer memory buf, uint8 major, uint value) private pure { if(value <= 23) { buf.append(uint8((major << 5) | value)); } else if(value <= 0xFF) { buf.append(uint8((major << 5) | 24)); buf.appendInt(value, 1); } else if(value <= 0xFFFF) { buf.append(uint8((major << 5) | 25)); buf.appendInt(value, 2); } else if(value <= 0xFFFFFFFF) { buf.append(uint8((major << 5) | 26)); buf.appendInt(value, 4); } else if(value <= 0xFFFFFFFFFFFFFFFF) { buf.append(uint8((major << 5) | 27)); buf.appendInt(value, 8); } } function encodeIndefiniteLengthType(Buffer.buffer memory buf, uint8 major) private pure { buf.append(uint8((major << 5) | 31)); } function encodeUInt(Buffer.buffer memory buf, uint value) internal pure { encodeType(buf, MAJOR_TYPE_INT, value); } function encodeInt(Buffer.buffer memory buf, int value) internal pure { if(value >= 0) { encodeType(buf, MAJOR_TYPE_INT, uint(value)); } else { encodeType(buf, MAJOR_TYPE_NEGATIVE_INT, uint(-1 - value)); } } function encodeBytes(Buffer.buffer memory buf, bytes value) internal pure { encodeType(buf, MAJOR_TYPE_BYTES, value.length); buf.append(value); } function encodeString(Buffer.buffer memory buf, string value) internal pure { encodeType(buf, MAJOR_TYPE_STRING, bytes(value).length); buf.append(bytes(value)); } function startArray(Buffer.buffer memory buf) internal pure { encodeIndefiniteLengthType(buf, MAJOR_TYPE_ARRAY); } function startMap(Buffer.buffer memory buf) internal pure { encodeIndefiniteLengthType(buf, MAJOR_TYPE_MAP); } function endSequence(Buffer.buffer memory buf) internal pure { encodeIndefiniteLengthType(buf, MAJOR_TYPE_CONTENT_FREE); } } /* End solidity-cborutils */ contract usingOraclize { uint constant day = 60*60*24; uint constant week = 60*60*24*7; uint constant month = 60*60*24*30; byte constant proofType_NONE = 0x00; byte constant proofType_TLSNotary = 0x10; byte constant proofType_Ledger = 0x30; byte constant proofType_Android = 0x40; byte constant proofType_Native = 0xF0; byte constant proofStorage_IPFS = 0x01; uint8 constant networkID_auto = 0; uint8 constant networkID_mainnet = 1; uint8 constant networkID_testnet = 2; uint8 constant networkID_morden = 2; uint8 constant networkID_consensys = 161; OraclizeAddrResolverI OAR; OraclizeI oraclize; modifier oraclizeAPI { if((address(OAR)==0)||(getCodeSize(address(OAR))==0)) oraclize_setNetwork(networkID_auto); if(address(oraclize) != OAR.getAddress()) oraclize = OraclizeI(OAR.getAddress()); _; } modifier coupon(string code){ oraclize = OraclizeI(OAR.getAddress()); _; } function oraclize_setNetwork(uint8 networkID) internal returns(bool){ return oraclize_setNetwork(); networkID; // silence the warning and remain backwards compatible } function oraclize_setNetwork() internal returns(bool){ if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ //mainnet OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed); oraclize_setNetworkName("eth_mainnet"); return true; } if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1); oraclize_setNetworkName("eth_ropsten3"); return true; } if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e); oraclize_setNetworkName("eth_kovan"); return true; } if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ //rinkeby testnet OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48); oraclize_setNetworkName("eth_rinkeby"); return true; } if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ //ethereum-bridge OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475); return true; } if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ //ether.camp ide OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF); return true; } if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA); return true; } return false; } function __callback(bytes32 myid, string result) public { __callback(myid, result, new bytes(0)); } function __callback(bytes32 myid, string result, bytes proof) public { return; myid; result; proof; // Silence compiler warnings } function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource); } function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource, gaslimit); } function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(0, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(timestamp, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(0, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_cbAddress() oraclizeAPI internal returns (address){ return oraclize.cbAddress(); } function oraclize_setProof(byte proofP) oraclizeAPI internal { return oraclize.setProofType(proofP); } function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal { return oraclize.setCustomGasPrice(gasPrice); } function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){ return oraclize.randomDS_getSessionPubKeyHash(); } function getCodeSize(address _addr) constant internal returns(uint _size) { assembly { _size := extcodesize(_addr) } } function parseAddr(string _a) internal pure returns (address){ bytes memory tmp = bytes(_a); uint160 iaddr = 0; uint160 b1; uint160 b2; for (uint i=2; i<2+2*20; i+=2){ iaddr *= 256; b1 = uint160(tmp[i]); b2 = uint160(tmp[i+1]); if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87; else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55; else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48; if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87; else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55; else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48; iaddr += (b1*16+b2); } return address(iaddr); } function strCompare(string _a, string _b) internal pure returns (int) { bytes memory a = bytes(_a); bytes memory b = bytes(_b); uint minLength = a.length; if (b.length < minLength) minLength = b.length; for (uint i = 0; i < minLength; i ++) if (a[i] < b[i]) return -1; else if (a[i] > b[i]) return 1; if (a.length < b.length) return -1; else if (a.length > b.length) return 1; else return 0; } function indexOf(string _haystack, string _needle) internal pure returns (int) { bytes memory h = bytes(_haystack); bytes memory n = bytes(_needle); if(h.length < 1 || n.length < 1 || (n.length > h.length)) return -1; else if(h.length > (2**128 -1)) return -1; else { uint subindex = 0; for (uint i = 0; i < h.length; i ++) { if (h[i] == n[0]) { subindex = 1; while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) { subindex++; } if(subindex == n.length) return int(i); } } return -1; } } function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string) { 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); uint k = 0; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } function strConcat(string _a, string _b, string _c, string _d) internal pure returns (string) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string _a, string _b, string _c) internal pure returns (string) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string _a, string _b) internal pure returns (string) { return strConcat(_a, _b, "", "", ""); } // parseInt function parseInt(string _a) internal pure returns (uint) { return parseInt(_a, 0); } // parseInt(parseFloat*10^_b) function parseInt(string _a, uint _b) internal pure returns (uint) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i=0; i<bresult.length; i++){ if ((bresult[i] >= 48)&&(bresult[i] <= 57)){ if (decimals){ if (_b == 0) break; else _b--; } mint *= 10; mint += uint(bresult[i]) - 48; } else if (bresult[i] == 46) decimals = true; } if (_b > 0) mint *= 10**_b; return mint; } function uint2str(uint i) internal pure returns (string){ if (i == 0) return "0"; uint j = i; uint len; while (j != 0){ len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (i != 0){ bstr[k--] = byte(48 + i % 10); i /= 10; } return string(bstr); } using CBOR for Buffer.buffer; function stra2cbor(string[] arr) internal pure returns (bytes) { safeMemoryCleaner(); Buffer.buffer memory buf; Buffer.init(buf, 1024); buf.startArray(); for (uint i = 0; i < arr.length; i++) { buf.encodeString(arr[i]); } buf.endSequence(); return buf.buf; } function ba2cbor(bytes[] arr) internal pure returns (bytes) { safeMemoryCleaner(); Buffer.buffer memory buf; Buffer.init(buf, 1024); buf.startArray(); for (uint i = 0; i < arr.length; i++) { buf.encodeBytes(arr[i]); } buf.endSequence(); return buf.buf; } string oraclize_network_name; function oraclize_setNetworkName(string _network_name) internal { oraclize_network_name = _network_name; } function oraclize_getNetworkName() internal view returns (string) { return oraclize_network_name; } function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){ require((_nbytes > 0) && (_nbytes <= 32)); // Convert from seconds to ledger timer ticks _delay *= 10; bytes memory nbytes = new bytes(1); nbytes[0] = byte(_nbytes); bytes memory unonce = new bytes(32); bytes memory sessionKeyHash = new bytes(32); bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash(); assembly { mstore(unonce, 0x20) // the following variables can be relaxed // check relaxed random contract under ethereum-examples repo // for an idea on how to override and replace comit hash vars mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp))) mstore(sessionKeyHash, 0x20) mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32) } bytes memory delay = new bytes(32); assembly { mstore(add(delay, 0x20), _delay) } bytes memory delay_bytes8 = new bytes(8); copyBytes(delay, 24, 8, delay_bytes8, 0); bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay]; bytes32 queryId = oraclize_query("random", args, _customGasLimit); bytes memory delay_bytes8_left = new bytes(8); assembly { let x := mload(add(delay_bytes8, 0x20)) mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000)) } oraclize_randomDS_setCommitment(queryId, keccak256(delay_bytes8_left, args[1], sha256(args[0]), args[2])); return queryId; } function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal { oraclize_randomDS_args[queryId] = commitment; } mapping(bytes32=>bytes32) oraclize_randomDS_args; mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified; function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){ bool sigok; address signer; bytes32 sigr; bytes32 sigs; bytes memory sigr_ = new bytes(32); uint offset = 4+(uint(dersig[3]) - 0x20); sigr_ = copyBytes(dersig, offset, 32, sigr_, 0); bytes memory sigs_ = new bytes(32); offset += 32 + 2; sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0); assembly { sigr := mload(add(sigr_, 32)) sigs := mload(add(sigs_, 32)) } (sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs); if (address(keccak256(pubkey)) == signer) return true; else { (sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs); return (address(keccak256(pubkey)) == signer); } } function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) { bool sigok; // Step 6: verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH) bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2); copyBytes(proof, sig2offset, sig2.length, sig2, 0); bytes memory appkey1_pubkey = new bytes(64); copyBytes(proof, 3+1, 64, appkey1_pubkey, 0); bytes memory tosign2 = new bytes(1+65+32); tosign2[0] = byte(1); //role copyBytes(proof, sig2offset-65, 65, tosign2, 1); bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c"; copyBytes(CODEHASH, 0, 32, tosign2, 1+65); sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey); if (sigok == false) return false; // Step 7: verify the APPKEY1 provenance (must be signed by Ledger) bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4"; bytes memory tosign3 = new bytes(1+65); tosign3[0] = 0xFE; copyBytes(proof, 3, 65, tosign3, 1); bytes memory sig3 = new bytes(uint(proof[3+65+1])+2); copyBytes(proof, 3+65, sig3.length, sig3, 0); sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY); return sigok; } modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) { // Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1) require((_proof[0] == "L") && (_proof[1] == "P") && (_proof[2] == 1)); bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); require(proofVerified); _; } function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){ // Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1) if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1; bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); if (proofVerified == false) return 2; return 0; } function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal pure returns (bool){ bool match_ = true; require(prefix.length == n_random_bytes); for (uint256 i=0; i< n_random_bytes; i++) { if (content[i] != prefix[i]) match_ = false; } return match_; } function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){ // Step 2: the unique keyhash has to match with the sha256 of (context name + queryId) uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32; bytes memory keyhash = new bytes(32); copyBytes(proof, ledgerProofLength, 32, keyhash, 0); if (!(keccak256(keyhash) == keccak256(sha256(context_name, queryId)))) return false; bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2); copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0); // Step 3: we assume sig1 is valid (it will be verified during step 5) and we verify if 'result' is the prefix of sha256(sig1) if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false; // Step 4: commitment match verification, keccak256(delay, nbytes, unonce, sessionKeyHash) == commitment in storage. // This is to verify that the computed args match with the ones specified in the query. bytes memory commitmentSlice1 = new bytes(8+1+32); copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0); bytes memory sessionPubkey = new bytes(64); uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65; copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0); bytes32 sessionPubkeyHash = sha256(sessionPubkey); if (oraclize_randomDS_args[queryId] == keccak256(commitmentSlice1, sessionPubkeyHash)){ //unonce, nbytes and sessionKeyHash match delete oraclize_randomDS_args[queryId]; } else return false; // Step 5: validity verification for sig1 (keyhash and args signed with the sessionKey) bytes memory tosign1 = new bytes(32+8+1+32); copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0); if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false; // verify if sessionPubkeyHash was verified already, if not.. let's do it! if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){ oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset); } return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash]; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal pure returns (bytes) { uint minLength = length + toOffset; // Buffer too small require(to.length >= minLength); // Should be a better way? // NOTE: the offset 32 is added to skip the `size` field of both bytes variables uint i = 32 + fromOffset; uint j = 32 + toOffset; while (i < (32 + fromOffset + length)) { assembly { let tmp := mload(add(from, i)) mstore(add(to, j), tmp) } i += 32; j += 32; } return to; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license // Duplicate Solidity's ecrecover, but catching the CALL return value function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) { // We do our own memory management here. Solidity uses memory offset // 0x40 to store the current end of memory. We write past it (as // writes are memory extensions), but don't update the offset so // Solidity will reuse it. The memory used here is only needed for // this context. // FIXME: inline assembly can't access return values bool ret; address addr; assembly { let size := mload(0x40) mstore(size, hash) mstore(add(size, 32), v) mstore(add(size, 64), r) mstore(add(size, 96), s) // NOTE: we can reuse the request memory because we deal with // the return code ret := call(3000, 1, 0, size, 128, size, 32) addr := mload(size) } return (ret, addr); } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) { bytes32 r; bytes32 s; uint8 v; if (sig.length != 65) return (false, 0); // The signature format is a compact form of: // {bytes32 r}{bytes32 s}{uint8 v} // Compact means, uint8 is not padded to 32 bytes. assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) // Here we are loading the last 32 bytes. We exploit the fact that // 'mload' will pad with zeroes if we overread. // There is no 'mload8' to do this, but that would be nicer. v := byte(0, mload(add(sig, 96))) // Alternative solution: // 'byte' is not working due to the Solidity parser, so lets // use the second best option, 'and' // v := and(mload(add(sig, 65)), 255) } // albeit non-transactional signatures are not specified by the YP, one would expect it // to match the YP range of [27, 28] // // geth uses [0, 1] and some clients have followed. This might change, see: // https://github.com/ethereum/go-ethereum/issues/2053 if (v < 27) v += 27; if (v != 27 && v != 28) return (false, 0); return safer_ecrecover(hash, v, r, s); } function safeMemoryCleaner() internal pure { assembly { let fmem := mload(0x40) codecopy(fmem, codesize, sub(msize, fmem)) } } } // </ORACLIZE_API> // File: contracts/BetDex.sol contract BetDex is usingOraclize { using SafeMath for uint256; //prevents overflows from occuring when working with uint address public owner; address public houseFeeAddress; uint public houseFeePercent = 3; uint public minimumBetAmount = 10000000000000000; //=> 0.01 Ether string public version = '1.0.0'; uint public ORACLIZE_GAS_LIMIT = 100000; uint public ORACLIZE_GAS_PRICE = 10000000000; bytes32 public currOraclizeEventId; //struct that holds all of the data for a specific event struct Event { bytes32 eventId; bytes32 winningScenarioName; bytes32 firstScenarioName; bytes32 secondScenarioName; string oracleGameId; string category; uint index; uint totalNumOfBets; uint eventStartsTime; bool eventHasEnded; bool eventCancelled; bool resultIsATie; bool houseFeePaid; mapping(bytes32 => Scenario) scenarios; mapping(address => BettorInfo) bettorsIndex; } //struct that holds data for each of the two scenarios for each event //this data is placed inside the Event struct struct Scenario { uint totalBet; uint numOfBets; } //struct that holds data for each bettor address in an event //this data is placed inside the Event struct struct BettorInfo { bool rewarded; bool refunded; uint totalBet; mapping(bytes32 => uint) bets; } mapping (bytes32 => Event) events; bytes32[] eventsIndex; //events ted for frontend interface and administrative purposes event EventCreated(bytes32 indexed eventId, uint eventStartsTime); event BetPlaced(bytes32 indexed eventId, bytes32 scenarioBetOn, address indexed from, uint betValue, uint timestamp, bytes32 firstScenarioName, bytes32 secondScenarioName, string category); event WinnerSet(bytes32 indexed eventId, bytes32 winningScenarioName, uint timestamp); event HouseFeePaid(bytes32 indexed eventId, address houseFeeAddress, uint houseFeeAmount); event Withdrawal(bytes32 indexed eventId, string category, address indexed userAddress, bytes32 withdrawalType, uint amount, bytes32 firstScenarioName, bytes32 secondScenarioName, uint timestamp); event HouseFeePercentChanged(uint oldFee, uint newFee, uint timestamp); event HouseFeeAddressChanged(address oldAddress, address newAddress, uint timestamp); event OwnershipTransferred(address owner, address newOwner); event EventCancelled(bytes32 indexed eventId, bool dueToInsufficientBetAmount, uint timestamp); event TieResultSet(bytes32 indexed eventId, uint timestamp); event ExtendEventStartsTime(bytes32 indexed eventId, uint newEventStartsTime, uint timestamp); event NewOraclizeQuery(bytes32 indexed eventId, string description); event OraclizeQueryRecieved(bytes32 indexed eventId, string result); event OraclizeGasLimitSet(uint oldGasLimit, uint newGasLimit, uint timestamp); event OraclizeGasPriceSet(uint newGasPriceGwei, uint timestamp); event MinimumBetAmountChanged(uint oldMinimumAmountInWei, uint newMinimumAmountInWei, uint timestamp); //ran once on contract creation //houseFeeAddress and owner set function BetDex() public { houseFeeAddress = msg.sender; owner = msg.sender; //change default gas price from 20 Gwei to 10 Gwei oraclize_setCustomGasPrice(10000000000); } //modifier used to restrict certain functions to only owner calls modifier onlyOwner() { require(msg.sender == owner); _; } //modifier used to restrict the __callback function to only oraclize address calls modifier onlyOraclize() { require(msg.sender == oraclize_cbAddress()); _; } //for owner to add to contract balance if needed function () external payable onlyOwner {} //function to add new event to the events mapping function createNewEvent(bytes32 _eventId, string _category, string _oracleGameId, uint _eventStartsTime, string _firstScenarioName, string _secondScenarioName) external onlyOwner { require(!internalDoesEventExist(_eventId)); require(stringToBytes32(_firstScenarioName) != stringToBytes32(_secondScenarioName)); events[_eventId].eventId = _eventId; events[_eventId].oracleGameId = _oracleGameId; events[_eventId].index = eventsIndex.push(_eventId)-1; events[_eventId].category = _category; events[_eventId].eventStartsTime = _eventStartsTime; events[_eventId].firstScenarioName = stringToBytes32(_firstScenarioName); events[_eventId].secondScenarioName = stringToBytes32(_secondScenarioName); events[_eventId].scenarios[stringToBytes32(_firstScenarioName)]; events[_eventId].scenarios[stringToBytes32(_secondScenarioName)]; EventCreated(_eventId, _eventStartsTime); } //add bet to the bettorIndex mapping for a specific event function placeBet(bytes32 _eventId, string _scenarioBetOn) external payable { require(internalDoesEventExist(_eventId)); require(msg.value >= minimumBetAmount); require(!events[_eventId].eventHasEnded); require(events[_eventId].eventStartsTime > now); require(stringToBytes32(_scenarioBetOn) == events[_eventId].firstScenarioName || stringToBytes32(_scenarioBetOn) == events[_eventId].secondScenarioName); events[_eventId].bettorsIndex[msg.sender].bets[stringToBytes32(_scenarioBetOn)] = (events[_eventId].bettorsIndex[msg.sender].bets[stringToBytes32(_scenarioBetOn)]).add(msg.value); events[_eventId].bettorsIndex[msg.sender].totalBet = (events[_eventId].bettorsIndex[msg.sender].totalBet).add(msg.value); events[_eventId].totalNumOfBets = (events[_eventId].totalNumOfBets).add(1); events[_eventId].scenarios[stringToBytes32(_scenarioBetOn)].numOfBets = (events[_eventId].scenarios[stringToBytes32(_scenarioBetOn)].numOfBets).add(1); events[_eventId].scenarios[stringToBytes32(_scenarioBetOn)].totalBet = (events[_eventId].scenarios[stringToBytes32(_scenarioBetOn)].totalBet).add(msg.value); BetPlaced(_eventId, stringToBytes32(_scenarioBetOn), msg.sender, msg.value, now, events[_eventId].firstScenarioName, events[_eventId].secondScenarioName, events[_eventId].category); } //function used by oraclize when it sends event data back to the smart contract function __callback(bytes32 myid, string result) public onlyOraclize { if (stringToBytes32(result) == stringToBytes32("tie")) { OraclizeQueryRecieved(currOraclizeEventId, "game result is a tie"); events[currOraclizeEventId].resultIsATie = true; events[currOraclizeEventId].eventHasEnded = true; } else if (stringToBytes32(result) == events[currOraclizeEventId].firstScenarioName || stringToBytes32(result) == events[currOraclizeEventId].secondScenarioName) { OraclizeQueryRecieved(currOraclizeEventId, result); uint houseFeeAmount = ((events[currOraclizeEventId].scenarios[events[currOraclizeEventId].firstScenarioName].totalBet) .add(events[currOraclizeEventId].scenarios[events[currOraclizeEventId].secondScenarioName].totalBet)) .mul(houseFeePercent) .div(100); if (!events[currOraclizeEventId].houseFeePaid) { houseFeeAddress.transfer(houseFeeAmount); events[currOraclizeEventId].houseFeePaid = true; HouseFeePaid(currOraclizeEventId, houseFeeAddress, houseFeeAmount); } events[currOraclizeEventId].winningScenarioName = stringToBytes32(result); events[currOraclizeEventId].eventHasEnded = true; WinnerSet(currOraclizeEventId, stringToBytes32(result), now); } else { OraclizeQueryRecieved(currOraclizeEventId, "error occurred"); } } //set the winningScenarioId, calculate and send houseFee amount to houseFeeAddress, and end specific event function getWinnerOfEvent(bytes32 _eventId) public payable onlyOwner { require(internalDoesEventExist(_eventId)); require(!events[_eventId].eventHasEnded); require(events[_eventId].eventStartsTime < now); //if there are no bets on one or both events, don't send query oraclize if (events[_eventId].scenarios[events[_eventId].firstScenarioName].totalBet == 0 || events[_eventId].scenarios[events[_eventId].secondScenarioName].totalBet == 0) { events[_eventId].eventCancelled = true; events[_eventId].eventHasEnded = true; EventCancelled(_eventId, true, now); } else { require(msg.value >= oraclize_getPrice("URL", ORACLIZE_GAS_LIMIT)); currOraclizeEventId = _eventId; NewOraclizeQuery(_eventId, "Oraclize query was sent, standing by for the answer..."); oraclize_query("URL", strConcat("json(https://api.betdex.io/api/sports/", events[_eventId].category, "/getGameResultById/", events[_eventId].oracleGameId, ").result"), ORACLIZE_GAS_LIMIT); } } //cancel and end specific event //event can be cancelled at any time, allowing users to refund their bet ether function cancelAndEndEvent(bytes32 _eventId) external onlyOwner { require(internalDoesEventExist(_eventId)); require(!events[_eventId].eventCancelled); require(!events[_eventId].eventHasEnded); events[_eventId].eventCancelled = true; events[_eventId].eventHasEnded = true; EventCancelled(_eventId, false, now); } //find the msg.sender in the bettorsIndex, calculate the winning amount for the user, and transfer winning amount to user's address function claimWinnings(bytes32 _eventId) external { require(internalDoesEventExist(_eventId)); require(events[_eventId].eventHasEnded); require(!events[_eventId].eventCancelled); require(!events[_eventId].resultIsATie); require(!events[_eventId].bettorsIndex[msg.sender].rewarded); require(!events[_eventId].bettorsIndex[msg.sender].refunded); require(events[_eventId].bettorsIndex[msg.sender].totalBet > 0); require(events[_eventId].scenarios[events[_eventId].winningScenarioName].totalBet > 0); uint transferAmount = calculateWinnings(_eventId, msg.sender); if (transferAmount > 0) { events[_eventId].bettorsIndex[msg.sender].rewarded = true; Withdrawal(_eventId, events[_eventId].category, msg.sender, stringToBytes32('winnings'), transferAmount, events[_eventId].firstScenarioName, events[_eventId].secondScenarioName, now); msg.sender.transfer(transferAmount); } } //internal function used to calculate the amount of winnings to award to a given user for a specific event function calculateWinnings(bytes32 _eventId, address _userAddress) internal constant returns (uint winnerReward) { uint totalReward = (events[_eventId].scenarios[events[_eventId].firstScenarioName].totalBet).add(events[_eventId].scenarios[events[_eventId].secondScenarioName].totalBet) .sub(((events[_eventId].scenarios[events[_eventId].firstScenarioName].totalBet) .add(events[_eventId].scenarios[events[_eventId].secondScenarioName].totalBet)) .mul(houseFeePercent) .div(100)); winnerReward = ((((totalReward).mul(10000000)) .div(events[_eventId].scenarios[events[_eventId].winningScenarioName].totalBet)) .mul(events[_eventId].bettorsIndex[_userAddress].bets[events[_eventId].winningScenarioName])) .div(10000000); } //find the msg.sender address in the bettorsIndex and transfer the refund amount to the user's address function claimRefund(bytes32 _eventId) external { require(internalDoesEventExist(_eventId)); require(events[_eventId].eventHasEnded); require(events[_eventId].eventCancelled || events[_eventId].resultIsATie); require(!events[_eventId].bettorsIndex[msg.sender].rewarded); require(!events[_eventId].bettorsIndex[msg.sender].refunded); require(events[_eventId].bettorsIndex[msg.sender].totalBet > 0); events[_eventId].bettorsIndex[msg.sender].refunded = true; Withdrawal(_eventId, events[_eventId].category, msg.sender, stringToBytes32('refund'), events[_eventId].bettorsIndex[msg.sender].totalBet, events[_eventId].firstScenarioName, events[_eventId].secondScenarioName, now); msg.sender.transfer(events[_eventId].bettorsIndex[msg.sender].totalBet); } //change eventStartsTime value for a specific event //used if an event was given an incorrect start time or an event is postponed or delayed function extendEventStartsTime(bytes32 _eventId, uint _newEventStartsTime) external onlyOwner { require(internalDoesEventExist(_eventId)); require(!events[_eventId].eventHasEnded); require(_newEventStartsTime > events[_eventId].eventStartsTime); events[_eventId].eventStartsTime = _newEventStartsTime; ExtendEventStartsTime(_eventId, _newEventStartsTime, now); } //change oraclize gas limit function setOraclizeGasLimit(uint _newGasLimit) external onlyOwner { require(_newGasLimit > 0); OraclizeGasLimitSet(ORACLIZE_GAS_LIMIT, _newGasLimit, now); ORACLIZE_GAS_LIMIT = _newGasLimit; } //update gas price that oraclize sends transactions with function setOraclizeGasPrice(uint _newGasPrice) external onlyOwner { require(_newGasPrice > 0); OraclizeGasPriceSet(_newGasPrice, now); oraclize_setCustomGasPrice(_newGasPrice); } //function used to change the house fee percent //house fee percent can only be lowered function changeHouseFeePercent(uint _newFeePercent) external onlyOwner { require(_newFeePercent < houseFeePercent); HouseFeePercentChanged(houseFeePercent, _newFeePercent, now); houseFeePercent = _newFeePercent; } //function used to change the house fee address function changeHouseFeeAddress(address _newAddress) external onlyOwner { require(_newAddress != houseFeeAddress); HouseFeeAddressChanged(houseFeeAddress, _newAddress, now); houseFeeAddress = _newAddress; } //function used to change the minimum bet amount function changeMinimumBetAmount(uint _newMinimumAmountInWei) external onlyOwner { MinimumBetAmountChanged(minimumBetAmount, _newMinimumAmountInWei, now); minimumBetAmount = _newMinimumAmountInWei; } //internal function used to verify that an event exists with a given eventId function internalDoesEventExist(bytes32 _eventId) internal constant returns (bool) { if (eventsIndex.length > 0) { return (eventsIndex[events[_eventId].index] == _eventId); } else { return (false); } } //external version of the internalDoesEventExist function function doesEventExist(bytes32 _eventId) public constant returns (bool) { if (eventsIndex.length > 0) { return (eventsIndex[events[_eventId].index] == _eventId); } else { return (false); } } //external function used by frontend to pull scenario names and event status from the contract function getScenarioNamesAndEventStatus(bytes32 _eventId) public constant returns (bytes32, bytes32, bool, bool, bool, bytes32, bool) { return ( events[_eventId].firstScenarioName, events[_eventId].secondScenarioName, events[_eventId].eventHasEnded, events[_eventId].eventCancelled, events[_eventId].resultIsATie, events[_eventId].winningScenarioName, events[_eventId].houseFeePaid ); } //external function used by frontend to pull event info from the contract function getEventInfo(bytes32 _eventId) public constant returns (uint, string, uint, string) { return ( events[_eventId].totalNumOfBets, events[_eventId].category, events[_eventId].eventStartsTime, events[_eventId].oracleGameId ); } //external function used by frontend to pull scenarios info from the contract function getScenariosInfo(bytes32 _eventId) public constant returns (bytes32, uint, uint, bytes32, uint, uint) { return ( events[_eventId].firstScenarioName, events[_eventId].scenarios[events[_eventId].firstScenarioName].totalBet, events[_eventId].scenarios[events[_eventId].firstScenarioName].numOfBets, events[_eventId].secondScenarioName, events[_eventId].scenarios[events[_eventId].secondScenarioName].totalBet, events[_eventId].scenarios[events[_eventId].secondScenarioName].numOfBets ); } //external function used by frontend to pull bet data for a user address function getAddressBetsForEvent(bytes32 _eventId, address _userAddress) public constant returns (uint, bool, bool, uint, uint) { return ( events[_eventId].bettorsIndex[_userAddress].totalBet, events[_eventId].bettorsIndex[_userAddress].rewarded, events[_eventId].bettorsIndex[_userAddress].refunded, events[_eventId].bettorsIndex[_userAddress].bets[events[_eventId].firstScenarioName], events[_eventId].bettorsIndex[_userAddress].bets[events[_eventId].secondScenarioName] ); } //internal function to concat a string, used for creating oraclize query string function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string){ 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); uint k = 0; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } //internal function to see if two strings are equal function compareStrings(string a, string b) internal pure returns (bool) { return keccak256(a) == keccak256(b); } //internal function to convert a string to bytes32 function stringToBytes32(string memory source) internal pure returns (bytes32 result) { bytes memory tempEmptyStringTest = bytes(source); if (tempEmptyStringTest.length == 0) { return 0x0; } assembly { result := mload(add(source, 32)) } } } //library used to avoid integer overflows 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) { uint256 c = a / b; 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; } }
modifier used to restrict the __callback function to only oraclize address calls
modifier onlyOraclize() { require(msg.sender == oraclize_cbAddress()); _; }
12,679,709
[ 1, 20597, 1399, 358, 13108, 326, 1001, 3394, 445, 358, 1338, 578, 10150, 554, 1758, 4097, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 9606, 1338, 51, 354, 830, 554, 1435, 288, 203, 565, 2583, 12, 3576, 18, 15330, 422, 578, 10150, 554, 67, 7358, 1887, 10663, 203, 565, 389, 31, 203, 225, 289, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0xF835b72b8c51AE36f6DfDB9675703091F76A6F44/sources/contracts/Artcertificate.sol
* @title Full ERC721 Token This implementation includes all the required and some optional functionality of the ERC721 standard Moreover, it includes approve all functionality using operator terminology @dev source : openzeppelin-solidity/contracts/token/ERC721/ERC721Full.sol/
contract ERC721Full is ERC721, IERC721Full { using SafeMath for uint256; function init (string memory name__, string memory symbol__) internal virtual { _name = name__; _symbol = symbol__; } function name() external override view returns (string memory) { return _name; } function symbol() external override view returns (string memory) { return _symbol; } function tokenOfOwnerByIndex(address owner, uint256 index) public override view returns (uint256) { require(index < balanceOf(owner), "index is too high"); return _ownedTokens[owner][index]; } function totalSupply() public override view returns (uint256) { return _allTokens.length; } function tokenByIndex(uint256 index) public override view returns (uint256) { require(index < totalSupply(), "index is too high"); return _allTokens[index]; } function _transferFrom(address from, address to, uint256 tokenId) internal override { super._transferFrom(from, to, tokenId); _removeTokenFromOwnerEnumeration(from, tokenId); _addTokenToOwnerEnumeration(to, tokenId); } function _incrementTokenId() internal { nextId = nextId.add(1); } function _mint(address to) internal override { super._mint(to); _addTokenToOwnerEnumeration(to, nextId); _addTokenToAllTokensEnumeration(nextId); _incrementTokenId(); } function _burn(address owner, uint256 tokenId) internal override { super._burn(owner, tokenId); _removeTokenFromOwnerEnumeration(owner, tokenId); _ownedTokensIndex[tokenId] = 0; _removeTokenFromAllTokensEnumeration(tokenId); } function _tokensOfOwner(address owner) internal view returns (uint256[] storage) { return _ownedTokens[owner]; } function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { _ownedTokensIndex[tokenId] = _ownedTokens[to].length; _ownedTokens[to].push(tokenId); } function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { uint256 lastTokenIndex = _ownedTokens[from].length.sub(1); uint256 tokenIndex = _ownedTokensIndex[tokenId]; if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; _ownedTokensIndex[lastTokenId] = tokenIndex; } _ownedTokens[from].pop(); } function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { uint256 lastTokenIndex = _ownedTokens[from].length.sub(1); uint256 tokenIndex = _ownedTokensIndex[tokenId]; if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; _ownedTokensIndex[lastTokenId] = tokenIndex; } _ownedTokens[from].pop(); } function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { uint256 lastTokenIndex = _allTokens.length.sub(1); uint256 tokenIndex = _allTokensIndex[tokenId]; uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; _allTokensIndex[lastTokenId] = tokenIndex; _allTokens.pop(); _allTokensIndex[tokenId] = 0; } function tokensOf(address owner) public view returns (uint[] memory) { return _tokensOfOwner(owner); } }
713,631
[ 1, 5080, 4232, 39, 27, 5340, 3155, 1220, 4471, 6104, 777, 326, 1931, 471, 2690, 3129, 14176, 434, 326, 4232, 39, 27, 5340, 4529, 16053, 1643, 16, 518, 6104, 6617, 537, 777, 14176, 1450, 3726, 16122, 4676, 225, 1084, 294, 1696, 94, 881, 84, 292, 267, 17, 30205, 560, 19, 16351, 87, 19, 2316, 19, 654, 39, 27, 5340, 19, 654, 39, 27, 5340, 5080, 18, 18281, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 4232, 39, 27, 5340, 5080, 353, 4232, 39, 27, 5340, 16, 467, 654, 39, 27, 5340, 5080, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 203, 565, 445, 1208, 261, 1080, 3778, 508, 972, 16, 533, 3778, 3273, 972, 13, 2713, 5024, 288, 203, 3639, 389, 529, 273, 508, 972, 31, 203, 3639, 389, 7175, 273, 3273, 972, 31, 203, 565, 289, 203, 203, 565, 445, 508, 1435, 3903, 3849, 1476, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 389, 529, 31, 203, 565, 289, 203, 203, 565, 445, 3273, 1435, 3903, 3849, 1476, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 389, 7175, 31, 203, 565, 289, 203, 203, 565, 445, 1147, 951, 5541, 21268, 12, 2867, 3410, 16, 2254, 5034, 770, 13, 1071, 3849, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2583, 12, 1615, 411, 11013, 951, 12, 8443, 3631, 315, 1615, 353, 4885, 3551, 8863, 203, 3639, 327, 389, 995, 329, 5157, 63, 8443, 6362, 1615, 15533, 203, 565, 289, 203, 203, 565, 445, 2078, 3088, 1283, 1435, 1071, 3849, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 454, 5157, 18, 2469, 31, 203, 565, 289, 203, 203, 565, 445, 1147, 21268, 12, 11890, 5034, 770, 13, 1071, 3849, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2583, 12, 1615, 411, 2078, 3088, 1283, 9334, 315, 1615, 353, 4885, 3551, 8863, 203, 3639, 327, 389, 454, 5157, 63, 1615, 15533, 203, 565, 289, 203, 203, 565, 445, 389, 2 ]
/** *Submitted for verification at Etherscan.io on 2021-03-25 */ /* * Origin Protocol * https://originprotocol.com * * Released under the MIT license * https://github.com/OriginProtocol/origin-dollar * * Copyright 2020 Origin Protocol, Inc * * 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 * SOFTWARE. */ // File: contracts/governance/Governable.sol pragma solidity 0.5.11; /** * @title OUSD Governable Contract * @dev Copy of the openzeppelin Ownable.sol contract with nomenclature change * from owner to governor and renounce methods removed. Does not use * Context.sol like Ownable.sol does for simplification. * @author Origin Protocol Inc */ contract Governable { // Storage position of the owner and pendingOwner of the contract // keccak256("OUSD.governor"); bytes32 private constant governorPosition = 0x7bea13895fa79d2831e0a9e28edede30099005a50d652d8957cf8a607ee6ca4a; // keccak256("OUSD.pending.governor"); bytes32 private constant pendingGovernorPosition = 0x44c4d30b2eaad5130ad70c3ba6972730566f3e6359ab83e800d905c61b1c51db; // keccak256("OUSD.reentry.status"); bytes32 private constant reentryStatusPosition = 0x53bf423e48ed90e97d02ab0ebab13b2a235a6bfbe9c321847d5c175333ac4535; // See OpenZeppelin ReentrancyGuard implementation uint256 constant _NOT_ENTERED = 1; uint256 constant _ENTERED = 2; event PendingGovernorshipTransfer( address indexed previousGovernor, address indexed newGovernor ); event GovernorshipTransferred( address indexed previousGovernor, address indexed newGovernor ); /** * @dev Initializes the contract setting the deployer as the initial Governor. */ constructor() internal { _setGovernor(msg.sender); emit GovernorshipTransferred(address(0), _governor()); } /** * @dev Returns the address of the current Governor. */ function governor() public view returns (address) { return _governor(); } /** * @dev Returns the address of the current Governor. */ function _governor() internal view returns (address governorOut) { bytes32 position = governorPosition; assembly { governorOut := sload(position) } } /** * @dev Returns the address of the pending Governor. */ function _pendingGovernor() internal view returns (address pendingGovernor) { bytes32 position = pendingGovernorPosition; assembly { pendingGovernor := sload(position) } } /** * @dev Throws if called by any account other than the Governor. */ modifier onlyGovernor() { require(isGovernor(), "Caller is not the Governor"); _; } /** * @dev Returns true if the caller is the current Governor. */ function isGovernor() public view returns (bool) { return msg.sender == _governor(); } function _setGovernor(address newGovernor) internal { bytes32 position = governorPosition; assembly { sstore(position, newGovernor) } } /** * @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() { bytes32 position = reentryStatusPosition; uint256 _reentry_status; assembly { _reentry_status := sload(position) } // On the first call to nonReentrant, _notEntered will be true require(_reentry_status != _ENTERED, "Reentrant call"); // Any calls to nonReentrant after this point will fail assembly { sstore(position, _ENTERED) } _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) assembly { sstore(position, _NOT_ENTERED) } } function _setPendingGovernor(address newGovernor) internal { bytes32 position = pendingGovernorPosition; assembly { sstore(position, newGovernor) } } /** * @dev Transfers Governance of the contract to a new account (`newGovernor`). * Can only be called by the current Governor. Must be claimed for this to complete * @param _newGovernor Address of the new Governor */ function transferGovernance(address _newGovernor) external onlyGovernor { _setPendingGovernor(_newGovernor); emit PendingGovernorshipTransfer(_governor(), _newGovernor); } /** * @dev Claim Governance of the contract to a new account (`newGovernor`). * Can only be called by the new Governor. */ function claimGovernance() external { require( msg.sender == _pendingGovernor(), "Only the pending Governor can complete the claim" ); _changeGovernor(msg.sender); } /** * @dev Change Governance of the contract to a new account (`newGovernor`). * @param _newGovernor Address of the new Governor */ function _changeGovernor(address _newGovernor) internal { require(_newGovernor != address(0), "New Governor is address(0)"); emit GovernorshipTransferred(_governor(), _newGovernor); _setGovernor(_newGovernor); } } // File: contracts/interfaces/uniswap/IUniswapV2Router02.sol pragma solidity 0.5.11; interface IUniswapV2Router { function WETH() external pure returns (address); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); } // 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/utils/Address.sol pragma solidity ^0.5.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.5.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: contracts/buyback/Buyback.sol pragma solidity 0.5.11; contract Buyback is Governable { using SafeERC20 for IERC20; event UniswapUpdated(address _address); // Address of Uniswap address public uniswapAddr = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; // Address of OUSD Vault address constant public vaultAddr = 0xE75D77B1865Ae93c7eaa3040B038D7aA7BC02F70; // Swap from OUSD IERC20 constant ousd = IERC20(0x2A8e1E676Ec238d8A992307B495b45B3fEAa5e86); // Swap to OGN IERC20 constant ogn = IERC20(0x8207c1FfC5B6804F6024322CcF34F29c3541Ae26); // USDT for Uniswap path IERC20 constant usdt = IERC20(0xdAC17F958D2ee523a2206206994597C13D831ec7); /** * @dev Verifies that the caller is the OUSD Vault. */ modifier onlyVault() { require(vaultAddr == msg.sender, "Caller is not the Vault"); _; } /** * @dev Set address of Uniswap for performing liquidation of strategy reward * tokens. Setting to 0x0 will pause swaps. * @param _address Address of Uniswap */ function setUniswapAddr(address _address) external onlyGovernor { uniswapAddr = _address; // Give Uniswap unlimited OUSD allowance ousd.safeApprove(uniswapAddr, 0); ousd.safeApprove(uniswapAddr, uint256(-1)); emit UniswapUpdated(_address); } /** * @dev Execute a swap of OGN for OUSD via Uniswap or Uniswap compatible * protocol (e.g. Sushiswap) **/ function swap() external onlyVault { if (uniswapAddr == address(0)) return; uint256 sourceAmount = ousd.balanceOf(address(this)); if (sourceAmount < 1000 * 1e18) return; // Uniswap redemption path address[] memory path = new address[](4); path[0] = address(ousd); path[1] = address(usdt); path[2] = IUniswapV2Router(uniswapAddr).WETH(); path[3] = address(ogn); IUniswapV2Router(uniswapAddr).swapExactTokensForTokens( sourceAmount, uint256(0), path, address(this), now ); } /** * @notice Owner function to withdraw a specific amount of a token */ function transferToken(address token, uint256 amount) external onlyGovernor nonReentrant { IERC20(token).safeTransfer(_governor(), amount); } }
* @dev Execute a swap of OGN for OUSD via Uniswap or Uniswap compatible protocol (e.g. Sushiswap)/ Uniswap redemption path
function swap() external onlyVault { if (uniswapAddr == address(0)) return; uint256 sourceAmount = ousd.balanceOf(address(this)); if (sourceAmount < 1000 * 1e18) return; address[] memory path = new address[](4); path[0] = address(ousd); path[1] = address(usdt); path[2] = IUniswapV2Router(uniswapAddr).WETH(); path[3] = address(ogn); IUniswapV2Router(uniswapAddr).swapExactTokensForTokens( sourceAmount, uint256(0), path, address(this), now ); }
6,572,346
[ 1, 5289, 279, 7720, 434, 531, 8318, 364, 531, 3378, 40, 3970, 1351, 291, 91, 438, 578, 1351, 291, 91, 438, 7318, 1771, 261, 73, 18, 75, 18, 348, 1218, 291, 91, 438, 13176, 1351, 291, 91, 438, 283, 19117, 375, 589, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7720, 1435, 3903, 1338, 12003, 288, 203, 3639, 309, 261, 318, 291, 91, 438, 3178, 422, 1758, 12, 20, 3719, 327, 31, 203, 203, 3639, 2254, 5034, 1084, 6275, 273, 320, 407, 72, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 309, 261, 3168, 6275, 411, 4336, 380, 404, 73, 2643, 13, 327, 31, 203, 203, 3639, 1758, 8526, 3778, 589, 273, 394, 1758, 8526, 12, 24, 1769, 203, 3639, 589, 63, 20, 65, 273, 1758, 12, 1481, 72, 1769, 203, 3639, 589, 63, 21, 65, 273, 1758, 12, 407, 7510, 1769, 203, 3639, 589, 63, 22, 65, 273, 467, 984, 291, 91, 438, 58, 22, 8259, 12, 318, 291, 91, 438, 3178, 2934, 59, 1584, 44, 5621, 203, 3639, 589, 63, 23, 65, 273, 1758, 12, 4198, 1769, 203, 3639, 467, 984, 291, 91, 438, 58, 22, 8259, 12, 318, 291, 91, 438, 3178, 2934, 22270, 14332, 5157, 1290, 5157, 12, 203, 5411, 1084, 6275, 16, 203, 5411, 2254, 5034, 12, 20, 3631, 203, 5411, 589, 16, 203, 5411, 1758, 12, 2211, 3631, 203, 5411, 2037, 203, 3639, 11272, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/43113/0x5EE74f88b571d673a30cFaa6307d8b67F323b30e/sources/utils/Ownable.sol
* @dev Nominated Owner can accept the Ownership of the contract. Can only be called by the nominated owner./
function acceptOwnership() external { require(msg.sender == m_nominatedOwner, "Ownable: You must be nominated before you can accept ownership"); emit OwnershipTransferred(m_owner, m_nominatedOwner); m_owner = m_nominatedOwner; m_nominatedOwner = address(0); }
7,175,681
[ 1, 26685, 7458, 16837, 848, 2791, 326, 14223, 9646, 5310, 434, 326, 6835, 18, 4480, 1338, 506, 2566, 635, 326, 12457, 7458, 3410, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2791, 5460, 12565, 1435, 3903, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 312, 67, 12306, 7458, 5541, 16, 315, 5460, 429, 30, 4554, 1297, 506, 12457, 7458, 1865, 1846, 848, 2791, 23178, 8863, 203, 3639, 3626, 14223, 9646, 5310, 1429, 4193, 12, 81, 67, 8443, 16, 312, 67, 12306, 7458, 5541, 1769, 203, 3639, 312, 67, 8443, 273, 312, 67, 12306, 7458, 5541, 31, 203, 3639, 312, 67, 12306, 7458, 5541, 273, 1758, 12, 20, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/137/0x1a3Dd08B8E7707590DB6Dcf16Ce9472c2Ad6b6E8/sources/StakingContract.sol
Interfaces for ERC20 and ERC721 IERC20 public immutable rewardsToken; Constructor function to set the rewards token and the NFT collection addresses
contract BullandBearStaking is ReentrancyGuard { using SafeERC20 for IERC20; IERC721 public immutable nftCollection; pragma solidity ^0.8.4; constructor(IERC721 _nftCollection) { nftCollection = _nftCollection; } struct StakedToken { address staker; uint256 tokenId; } struct Staker { uint256 amountStaked; StakedToken[] stakedTokens; uint256 timeOfLastUpdate; } mapping(address => Staker) public stakers; mapping(uint256 => address) public stakerAddress; function stake(uint256 _tokenId) external nonReentrant { require( nftCollection.ownerOf(_tokenId) == msg.sender, "You don't own this token!" ); nftCollection.transferFrom(msg.sender, address(this), _tokenId); StakedToken memory stakedToken = StakedToken(msg.sender, _tokenId); stakers[msg.sender].stakedTokens.push(stakedToken); stakers[msg.sender].amountStaked++; stakerAddress[_tokenId] = msg.sender; stakers[msg.sender].timeOfLastUpdate = block.timestamp; } function withdraw(uint256 _tokenId) external nonReentrant { require( stakers[msg.sender].amountStaked > 0, "You have no tokens staked" ); require( stakerAddress[_tokenId] == msg.sender, "You don't own this token!" ); uint256 index = 0; for (uint256 i = 0; i < stakers[msg.sender].stakedTokens.length; i++) { if ( stakers[msg.sender].stakedTokens[i].tokenId == _tokenId && stakers[msg.sender].stakedTokens[i].staker != address(0) ) { index = i; break; } } } function withdraw(uint256 _tokenId) external nonReentrant { require( stakers[msg.sender].amountStaked > 0, "You have no tokens staked" ); require( stakerAddress[_tokenId] == msg.sender, "You don't own this token!" ); uint256 index = 0; for (uint256 i = 0; i < stakers[msg.sender].stakedTokens.length; i++) { if ( stakers[msg.sender].stakedTokens[i].tokenId == _tokenId && stakers[msg.sender].stakedTokens[i].staker != address(0) ) { index = i; break; } } } function withdraw(uint256 _tokenId) external nonReentrant { require( stakers[msg.sender].amountStaked > 0, "You have no tokens staked" ); require( stakerAddress[_tokenId] == msg.sender, "You don't own this token!" ); uint256 index = 0; for (uint256 i = 0; i < stakers[msg.sender].stakedTokens.length; i++) { if ( stakers[msg.sender].stakedTokens[i].tokenId == _tokenId && stakers[msg.sender].stakedTokens[i].staker != address(0) ) { index = i; break; } } } stakers[msg.sender].stakedTokens[index].staker = address(0); stakers[msg.sender].amountStaked--; stakerAddress[_tokenId] = address(0); nftCollection.transferFrom(address(this), msg.sender, _tokenId); stakers[msg.sender].timeOfLastUpdate = block.timestamp; function getStakedTokens(address _user) public view returns (StakedToken[] memory) { if (stakers[_user].amountStaked > 0) { StakedToken[] memory _stakedTokens = new StakedToken[]( stakers[_user].amountStaked ); uint256 _index = 0; for (uint256 j = 0; j < stakers[_user].stakedTokens.length; j++) { if (stakers[_user].stakedTokens[j].staker != (address(0))) { _stakedTokens[_index] = stakers[_user].stakedTokens[j]; _index++; } } return _stakedTokens; } else { return new StakedToken[](0); } } function getStakedTokens(address _user) public view returns (StakedToken[] memory) { if (stakers[_user].amountStaked > 0) { StakedToken[] memory _stakedTokens = new StakedToken[]( stakers[_user].amountStaked ); uint256 _index = 0; for (uint256 j = 0; j < stakers[_user].stakedTokens.length; j++) { if (stakers[_user].stakedTokens[j].staker != (address(0))) { _stakedTokens[_index] = stakers[_user].stakedTokens[j]; _index++; } } return _stakedTokens; } else { return new StakedToken[](0); } } function getStakedTokens(address _user) public view returns (StakedToken[] memory) { if (stakers[_user].amountStaked > 0) { StakedToken[] memory _stakedTokens = new StakedToken[]( stakers[_user].amountStaked ); uint256 _index = 0; for (uint256 j = 0; j < stakers[_user].stakedTokens.length; j++) { if (stakers[_user].stakedTokens[j].staker != (address(0))) { _stakedTokens[_index] = stakers[_user].stakedTokens[j]; _index++; } } return _stakedTokens; } else { return new StakedToken[](0); } } function getStakedTokens(address _user) public view returns (StakedToken[] memory) { if (stakers[_user].amountStaked > 0) { StakedToken[] memory _stakedTokens = new StakedToken[]( stakers[_user].amountStaked ); uint256 _index = 0; for (uint256 j = 0; j < stakers[_user].stakedTokens.length; j++) { if (stakers[_user].stakedTokens[j].staker != (address(0))) { _stakedTokens[_index] = stakers[_user].stakedTokens[j]; _index++; } } return _stakedTokens; } else { return new StakedToken[](0); } } function getStakedTokens(address _user) public view returns (StakedToken[] memory) { if (stakers[_user].amountStaked > 0) { StakedToken[] memory _stakedTokens = new StakedToken[]( stakers[_user].amountStaked ); uint256 _index = 0; for (uint256 j = 0; j < stakers[_user].stakedTokens.length; j++) { if (stakers[_user].stakedTokens[j].staker != (address(0))) { _stakedTokens[_index] = stakers[_user].stakedTokens[j]; _index++; } } return _stakedTokens; } else { return new StakedToken[](0); } } }
3,736,851
[ 1, 10273, 364, 4232, 39, 3462, 471, 4232, 39, 27, 5340, 467, 654, 39, 3462, 1071, 11732, 283, 6397, 1345, 31, 11417, 445, 358, 444, 326, 283, 6397, 1147, 471, 326, 423, 4464, 1849, 6138, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 605, 420, 464, 1919, 297, 510, 6159, 353, 868, 8230, 12514, 16709, 288, 203, 565, 1450, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 203, 203, 565, 467, 654, 39, 27, 5340, 1071, 11732, 290, 1222, 2532, 31, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 24, 31, 203, 565, 3885, 12, 45, 654, 39, 27, 5340, 389, 82, 1222, 2532, 13, 288, 203, 3639, 290, 1222, 2532, 273, 389, 82, 1222, 2532, 31, 203, 565, 289, 203, 203, 565, 1958, 934, 9477, 1345, 288, 203, 3639, 1758, 384, 6388, 31, 203, 3639, 2254, 5034, 1147, 548, 31, 203, 565, 289, 203, 203, 565, 1958, 934, 6388, 288, 203, 3639, 2254, 5034, 3844, 510, 9477, 31, 203, 3639, 934, 9477, 1345, 8526, 384, 9477, 5157, 31, 203, 3639, 2254, 5034, 813, 951, 3024, 1891, 31, 203, 565, 289, 203, 203, 203, 203, 565, 2874, 12, 2867, 516, 934, 6388, 13, 1071, 384, 581, 414, 31, 203, 565, 2874, 12, 11890, 5034, 516, 1758, 13, 1071, 384, 6388, 1887, 31, 203, 565, 445, 384, 911, 12, 11890, 5034, 389, 2316, 548, 13, 3903, 1661, 426, 8230, 970, 288, 203, 3639, 2583, 12, 203, 5411, 290, 1222, 2532, 18, 8443, 951, 24899, 2316, 548, 13, 422, 1234, 18, 15330, 16, 203, 5411, 315, 6225, 2727, 1404, 4953, 333, 1147, 4442, 203, 3639, 11272, 203, 203, 3639, 290, 1222, 2532, 18, 13866, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 389, 2316, 548, 1769, 203, 203, 3639, 934, 9477, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.2; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; /** * @dev Extension to BEP/ERC20 allowing for decimal places and initial supply to be set at construction */ contract Nitr0genStd is ERC20 { uint8 private _decimals; constructor( string memory name, string memory symbol, uint256 initialSupply, uint8 decimals_ ) ERC20(name, symbol) { _decimals = decimals_; _mint(msg.sender, initialSupply * 10**decimals()); } /** * @dev Returns the number of decimals used to get its user representation. */ function decimals() public view virtual override returns (uint8) { return _decimals; } }
* @dev Returns the number of decimals used to get its user representation./
function decimals() public view virtual override returns (uint8) { return _decimals; }
914,120
[ 1, 1356, 326, 1300, 434, 15105, 1399, 358, 336, 2097, 729, 4335, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 15105, 1435, 1071, 1476, 5024, 3849, 1135, 261, 11890, 28, 13, 288, 203, 3639, 327, 389, 31734, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x46b13E7E8f1aEF156973AE3eD975E738cAFB08C8/sources/contracts/Pool.sol
* @notice Update swap fee/
function updateSwapFee(uint256 newSwapFee_) external override onlyGovernor { require(newSwapFee_ <= 1e18, "max-is-100%"); uint256 _currentSwapFee = swapFee; require(newSwapFee_ != _currentSwapFee, "new-same-as-current"); emit SwapFeeUpdated(_currentSwapFee, newSwapFee_); swapFee = newSwapFee_; }
3,134,083
[ 1, 1891, 7720, 14036, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1089, 12521, 14667, 12, 11890, 5034, 394, 12521, 14667, 67, 13, 3903, 3849, 1338, 43, 1643, 29561, 288, 203, 3639, 2583, 12, 2704, 12521, 14667, 67, 1648, 404, 73, 2643, 16, 315, 1896, 17, 291, 17, 6625, 9, 8863, 203, 3639, 2254, 5034, 389, 2972, 12521, 14667, 273, 7720, 14667, 31, 203, 3639, 2583, 12, 2704, 12521, 14667, 67, 480, 389, 2972, 12521, 14667, 16, 315, 2704, 17, 14307, 17, 345, 17, 2972, 8863, 203, 3639, 3626, 12738, 14667, 7381, 24899, 2972, 12521, 14667, 16, 394, 12521, 14667, 67, 1769, 203, 3639, 7720, 14667, 273, 394, 12521, 14667, 67, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { 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; } } 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) external onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract EcroContract is Ownable { using SafeMath for uint256; //INVESTOR REPOSITORY mapping(address => uint256) internal balances; mapping (address => mapping(uint256=>uint256)) masterNodes; mapping (address => uint256[]) masterNodesDates; mapping (address => mapping (address => uint256)) internal allowed; mapping (address => uint256) internal totalAllowed; /** * @dev total number of tokens in existence */ uint256 internal totSupply; //COMMON function totalSupply() view public returns(uint256) { return totSupply; } function getTotalAllowed(address _owner) view public returns(uint256) { return totalAllowed[_owner]; } function setTotalAllowed(address _owner, uint256 _newValue) internal { totalAllowed[_owner]=_newValue; } function setTotalSupply(uint256 _newValue) internal { totSupply=_newValue; } function getMasterNodesDates(address _owner) view public returns(uint256[]) { return masterNodesDates[_owner]; } function getMasterNodes(address _owner, uint256 _date) view public returns(uint256) { return masterNodes[_owner][_date]; } function addMasterNodes(address _owner,uint256 _date,uint256 _amount) internal { masterNodesDates[_owner].push(_date); masterNodes[_owner][_date]=_amount; } function removeMasterNodes(address _owner,uint256 _date) internal { masterNodes[_owner][_date]=0; } /** * @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) view public returns(uint256) { return balances[_owner]; } function setBalanceOf(address _investor, uint256 _newValue) internal { require(_investor!=0x0000000000000000000000000000000000000000); balances[_investor]=_newValue; } /** * @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) view public returns(uint256) { require(msg.sender==_owner || msg.sender == _spender || msg.sender==getOwner()); return allowed[_owner][_spender]; } function setAllowance(address _owner, address _spender, uint256 _newValue) internal { require(_spender!=0x0000000000000000000000000000000000000000); uint256 newTotal = getTotalAllowed(_owner).sub(allowance(_owner, _spender)).add(_newValue); require(newTotal <= balanceOf(_owner)); allowed[_owner][_spender]=_newValue; setTotalAllowed(_owner,newTotal); } // TOKEN function EcroContract(uint256 _rate, uint256 _minPurchase,uint256 _tokenReturnRate,uint256 _cap,uint256 _nodePrice) public { require(_minPurchase>0); require(_rate > 0); require(_cap > 0); require(_nodePrice>0); require(_tokenReturnRate>0); rate=_rate; minPurchase=_minPurchase; tokenReturnRate=_tokenReturnRate; cap = _cap; nodePrice = _nodePrice; } bytes32 internal constant name = "ECRO Coin"; bytes3 internal constant symbol = "ECR"; uint8 internal constant decimals = 8; uint256 internal cap; uint256 internal nodePrice; bool internal mintingFinished; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); event Mint(address indexed to, uint256 amount); event MintFinished(); event Burn(address indexed burner, uint256 value); event TokenUnfrozen(address indexed owner, uint256 value); event TokenFrozen(address indexed owner, uint256 value); event MasterNodeBought(address indexed owner, uint256 amount); event MasterNodeReturned(address indexed owner, uint256 amount); modifier canMint() { require(!mintingFinished); _; } function getName() view public returns(bytes32) { return name; } function getSymbol() view public returns(bytes3) { return symbol; } function getTokenDecimals() view public returns(uint256) { return decimals; } function getMintingFinished() view public returns(bool) { return mintingFinished; } function getTokenCap() view public returns(uint256) { return cap; } function setTokenCap(uint256 _newCap) external onlyOwner { cap=_newCap; } function getNodePrice() view public returns(uint256) { return nodePrice; } function setNodePrice(uint256 _newPrice) external onlyOwner { require(_newPrice>0); nodePrice=_newPrice; } /** * @dev Burns the tokens of the specified address. * @param _owner The holder of tokens. * @param _value The amount of tokens burned */ function burn(address _owner,uint256 _value) internal { require(_value <= balanceOf(_owner)); // 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 setBalanceOf(_owner, balanceOf(_owner).sub(_value)); setTotalSupply(totalSupply().sub(_value)); emit Burn(_owner, _value); emit Transfer(_owner, address(0), _value); } function freezeTokens(address _who, uint256 _value) internal { require(_value <= balanceOf(_who)); setBalanceOf(_who, balanceOf(_who).sub(_value)); emit TokenFrozen(_who, _value); emit Transfer(_who, address(0), _value); } function unfreezeTokens(address _who, uint256 _value) internal { setBalanceOf(_who, balanceOf(_who).add(_value)); emit TokenUnfrozen(_who, _value); emit Transfer(address(0),_who, _value); } function buyMasterNodes(uint256 _date,uint256 _amount) external { freezeTokens(msg.sender,_amount*getNodePrice()); addMasterNodes(msg.sender, _date, getMasterNodes(msg.sender,_date).add(_amount)); MasterNodeBought(msg.sender,_amount); } function returnMasterNodes(address _who, uint256 _date) onlyOwner external { uint256 amount = getMasterNodes(_who,_date); removeMasterNodes(_who, _date); unfreezeTokens(_who,amount*getNodePrice()); MasterNodeReturned(_who,amount); } function updateTokenInvestorBalance(address _investor, uint256 _newValue) onlyOwner external { addTokens(_investor,_newValue); } /** * @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) external{ require(msg.sender!=_to); require(_value <= balanceOf(msg.sender)); // SafeMath.sub will throw if there is not enough balance. setBalanceOf(msg.sender, balanceOf(msg.sender).sub(_value)); setBalanceOf(_to, balanceOf(_to).add(_value)); Transfer(msg.sender, _to, _value); } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) external { require(_value <= balanceOf(_from)); require(_value <= allowance(_from,_to)); setBalanceOf(_from, balanceOf(_from).sub(_value)); setBalanceOf(_to, balanceOf(_to).add(_value)); setAllowance(_from,_to,allowance(_from,_to).sub(_value)); Transfer(_from, _to, _value); } /** * @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 _owner The address of the owner which allows tokens to a spender * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _owner,address _spender, uint256 _value) external { require(msg.sender ==_owner); setAllowance(msg.sender,_spender, _value); Approval(msg.sender, _spender, _value); } /** * @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 _owner The address of the owner which allows tokens to a spender * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _owner, address _spender, uint _addedValue) external{ require(msg.sender==_owner); setAllowance(_owner,_spender,allowance(_owner,_spender).add(_addedValue)); Approval(_owner, _spender, allowance(_owner,_spender)); } /** * @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 _owner The address of the owner which allows tokens to a spender * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _owner,address _spender, uint _subtractedValue) external{ require(msg.sender==_owner); uint oldValue = allowance(_owner,_spender); if (_subtractedValue > oldValue) { setAllowance(_owner,_spender, 0); } else { setAllowance(_owner,_spender, oldValue.sub(_subtractedValue)); } Approval(_owner, _spender, allowance(_owner,_spender)); } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) canMint internal{ require(totalSupply().add(_amount) <= getTokenCap()); setTotalSupply(totalSupply().add(_amount)); setBalanceOf(_to, balanceOf(_to).add(_amount)); Mint(_to, _amount); Transfer(address(0), _to, _amount); } function addTokens(address _to, uint256 _amount) canMint internal{ require( totalSupply().add(_amount) <= getTokenCap()); setTotalSupply(totalSupply().add(_amount)); setBalanceOf(_to, balanceOf(_to).add(_amount)); Transfer(address(0), _to, _amount); } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() canMint onlyOwner external{ mintingFinished = true; MintFinished(); } //Crowdsale // what is minimal purchase of tokens uint256 internal minPurchase; // how many token units a buyer gets per wei uint256 internal rate; // amount of raised money in wei uint256 internal weiRaised; uint256 internal tokenReturnRate; /** * event for token purchase logging * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed beneficiary, uint256 value, uint256 amount); event InvestmentsWithdrawn(uint indexed amount, uint indexed timestamp); function () external payable { } function getTokenRate() view public returns(uint256) { return rate; } function getTokenReturnRate() view public returns(uint256) { return tokenReturnRate; } function getMinimumPurchase() view public returns(uint256) { return minPurchase; } function setTokenRate(uint256 _newRate) external onlyOwner { rate = _newRate; } function setTokenReturnRate(uint256 _newRate) external onlyOwner { tokenReturnRate = _newRate; } function setMinPurchase(uint256 _newMin) external onlyOwner { minPurchase = _newMin; } function getWeiRaised() view external returns(uint256) { return weiRaised; } // low level token purchase function function buyTokens() external payable{ require(msg.value > 0); uint256 weiAmount = msg.value; // calculate token amount to be created uint256 tokens = getTokenAmount(weiAmount); require(validPurchase(tokens)); // update state weiRaised = weiRaised.add(weiAmount); mint(msg.sender, tokens); TokenPurchase(msg.sender, weiAmount, tokens); } // Override this method to have a way to add business logic to your crowdsale when buying function getTokenAmount(uint256 weiAmount) internal view returns(uint256) { return weiAmount.div(getTokenRate()); } // get all rised wei function withdrawInvestments() external onlyOwner{ uint amount = this.balance; getOwner().transfer(amount * 1 wei); InvestmentsWithdrawn(amount, block.timestamp); } function returnTokens(uint256 _amount) external { require(balanceOf(msg.sender) >= _amount); burn(msg.sender,_amount); // return (rate * amount) * returnTokenRate % msg.sender.transfer(getTokenRate().mul(_amount).div(100).mul(tokenReturnRate)); } function getCurrentInvestments() view external onlyOwner returns(uint256) { return this.balance; } function getOwner() view internal returns(address) { return owner; } // @return true if the transaction can buy tokens function validPurchase(uint256 tokensAmount) internal view returns (bool) { bool nonZeroPurchase = tokensAmount != 0; bool acceptableAmount = tokensAmount >= getMinimumPurchase(); return nonZeroPurchase && acceptableAmount; } }
* @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)); OwnershipTransferred(owner, newOwner); owner = newOwner; }
5,869,804
[ 1, 19132, 326, 783, 3410, 358, 7412, 3325, 434, 326, 6835, 358, 279, 394, 5541, 18, 225, 394, 5541, 1021, 1758, 358, 7412, 23178, 358, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7412, 5460, 12565, 12, 2867, 394, 5541, 13, 3903, 1338, 5541, 288, 203, 3639, 2583, 12, 2704, 5541, 480, 1758, 12, 20, 10019, 203, 3639, 14223, 9646, 5310, 1429, 4193, 12, 8443, 16, 394, 5541, 1769, 203, 3639, 3410, 273, 394, 5541, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/84531/0x3456c121Eb3b3eB2bd56C56584cA0e44981B0eD8/sources/ApetimismLaunchpadNFT.sol
Constants Internal Public Variables
contract ApetimismLaunchpadNFT is ERC721AQueryable, Ownable, ReentrancyGuard /*, ERC2981*/ { event Received(address, uint); event RoundChanged(uint8); event TotalMintedChanged(uint256); string private ERR_INVALID_SIGNATURE = "Invalid sig"; string private ERR_DUP_NONCE = "Dup nonce"; string private ERR_UNMATCHED_ETHER = "Unmatched ether"; string private ERR_HIT_MAXIMUM = "Hit maximum"; string private ERR_INVALID_AMOUNT = "Invalid amount"; string private ERR_RUN_OUT = "Run out"; uint256 public MAX_SUPPLY = 1316; uint256 public START_TOKEN_ID = 1; string private constant TOKEN_NAME = "YAMS"; string private constant TOKEN_SYMBOL = "YAMS"; mapping(address => uint256) private _addressTokenMinted; mapping(address => mapping(uint8 => mapping(int16 => uint256))) private _addressTokenMintedInRoundByRole; mapping(address => mapping(int16 => uint256)) private _addressTokenMintedInRole; mapping(uint256 => uint8) private _nonces; uint16 private allowedRolesInRoundSetId = 0; uint16 private roundAllocationsSetId = 0; uint16 private roleAllocationsSetId = 0; address public signerAddress = 0xbC40ad11Eeb1fa2DE26e64Ec703c3B020DE1e0CD; uint8 public currentRound = 0; bool public metadataFrozen = false; uint16 public maxMintPerTx = 13; uint16 public maxMintPerAddress = 13; string public baseURIExtended; bool public metdataHasExtension = true; mapping(int16 => uint256) mintPriceByRole; struct Role { uint8 round_id; int16 role_id; uint256 max_mint; uint256 mint_price; bool exists; } mapping(uint16 => mapping(uint8 => mapping(int16 => Role))) public allowedRolesInRound; mapping(uint16 => mapping(uint8 => uint16)) public allowedRolesInRoundCount; mapping(uint16 => mapping(uint8 => int16[])) public allowedRolesInRoundArr; uint8[] public availableAllowedRounds; uint8[] public availableRounds; mapping(uint16 => mapping(uint8 => uint256)) public roundAllocations; mapping(uint16 => mapping(int16 => uint256)) public roleAllocations; int16[] public availableRoles; mapping(uint8 => uint256) public totalMintedInRound; uint256 public totalRevenueShared = 0; address public currencyAddress; struct RoleInRoundParams { uint8 round; int16 role; uint256 maxMint; uint256 mintPrice; } struct RoundAllocationParams { uint8 round; uint256 allocation; } struct RoleAllocationParams { int16 role; uint256 allocation; } constructor() ERC721A(TOKEN_NAME, TOKEN_SYMBOL) { } function _startTokenId() internal view virtual override returns (uint256) { return START_TOKEN_ID; } function setCurrentRound(uint8 round_) public onlyOwner { currentRound = round_; emit RoundChanged(round_); } function setMaxMintPerTx(uint16 count) public onlyOwner { maxMintPerTx = count; } function setMaxMintPerAddress(uint16 count) public onlyOwner { maxMintPerAddress = count; } function setBaseURI(string memory baseURI) public onlyOwner { require(!metadataFrozen, "Metadata frozen"); baseURIExtended = baseURI; } function setMetadataHasExtension(bool hasExtension) public onlyOwner { metdataHasExtension = hasExtension; } function setCurrencyAddress(address addr) public onlyOwner { currencyAddress = addr; } function addAllowedRolesInRound(RoleInRoundParams[] memory params, bool replace) public onlyOwner { if (replace) { allowedRolesInRoundSetId++; delete availableAllowedRounds; } for (uint i = 0; i < params.length; i++) { addAllowedRoleInRound( params[i].round, params[i].role, params[i].maxMint, params[i].mintPrice, false ); } } function addAllowedRolesInRound(RoleInRoundParams[] memory params, bool replace) public onlyOwner { if (replace) { allowedRolesInRoundSetId++; delete availableAllowedRounds; } for (uint i = 0; i < params.length; i++) { addAllowedRoleInRound( params[i].round, params[i].role, params[i].maxMint, params[i].mintPrice, false ); } } function addAllowedRolesInRound(RoleInRoundParams[] memory params, bool replace) public onlyOwner { if (replace) { allowedRolesInRoundSetId++; delete availableAllowedRounds; } for (uint i = 0; i < params.length; i++) { addAllowedRoleInRound( params[i].round, params[i].role, params[i].maxMint, params[i].mintPrice, false ); } } function addAllowedRoleInRound(uint8 round, int16 role, uint256 maxMint, uint256 mintPrice, bool replace) public onlyOwner { if (replace) { allowedRolesInRoundSetId++; delete availableAllowedRounds; } bool role_already_existed = allowedRolesInRound[allowedRolesInRoundSetId][round][role].exists; allowedRolesInRound[allowedRolesInRoundSetId][round][role].round_id = round; allowedRolesInRound[allowedRolesInRoundSetId][round][role].role_id = role; allowedRolesInRound[allowedRolesInRoundSetId][round][role].max_mint = maxMint; allowedRolesInRound[allowedRolesInRoundSetId][round][role].mint_price = mintPrice; allowedRolesInRound[allowedRolesInRoundSetId][round][role].exists = true; return; allowedRolesInRoundCount[allowedRolesInRoundSetId][round]++; allowedRolesInRoundArr[allowedRolesInRoundSetId][round].push(role); bool found = false; for (uint8 i = 0; i < availableAllowedRounds.length; i++) if (availableAllowedRounds[i] == round) found = true; if (!found) availableAllowedRounds.push(round); } function addAllowedRoleInRound(uint8 round, int16 role, uint256 maxMint, uint256 mintPrice, bool replace) public onlyOwner { if (replace) { allowedRolesInRoundSetId++; delete availableAllowedRounds; } bool role_already_existed = allowedRolesInRound[allowedRolesInRoundSetId][round][role].exists; allowedRolesInRound[allowedRolesInRoundSetId][round][role].round_id = round; allowedRolesInRound[allowedRolesInRoundSetId][round][role].role_id = role; allowedRolesInRound[allowedRolesInRoundSetId][round][role].max_mint = maxMint; allowedRolesInRound[allowedRolesInRoundSetId][round][role].mint_price = mintPrice; allowedRolesInRound[allowedRolesInRoundSetId][round][role].exists = true; return; allowedRolesInRoundCount[allowedRolesInRoundSetId][round]++; allowedRolesInRoundArr[allowedRolesInRoundSetId][round].push(role); bool found = false; for (uint8 i = 0; i < availableAllowedRounds.length; i++) if (availableAllowedRounds[i] == round) found = true; if (!found) availableAllowedRounds.push(round); } function removeAllowedRoleInRound(uint8 round, int16 role) public onlyOwner { require(allowedRolesInRound[allowedRolesInRoundSetId][round][role].exists, "Role not existed"); allowedRolesInRound[allowedRolesInRoundSetId][round][role].round_id = 0; allowedRolesInRound[allowedRolesInRoundSetId][round][role].role_id = 0; allowedRolesInRound[allowedRolesInRoundSetId][round][role].max_mint = 0; allowedRolesInRound[allowedRolesInRoundSetId][round][role].mint_price = 0; allowedRolesInRound[allowedRolesInRoundSetId][round][role].exists = false; allowedRolesInRoundCount[allowedRolesInRoundSetId][round]--; for (uint8 i = 0; i < allowedRolesInRoundArr[allowedRolesInRoundSetId][round].length; i++) { if (allowedRolesInRoundArr[allowedRolesInRoundSetId][round][i] == role) { removeArrayAtInt16Index(allowedRolesInRoundArr[allowedRolesInRoundSetId][round], i); break; } } if (allowedRolesInRoundCount[allowedRolesInRoundSetId][round] == 0) { for (uint8 i = 0; i < availableRounds.length; i++) { if (availableRounds[i] == round) { removeArrayAtUint8Index(availableRounds, i); break; } } } } function removeAllowedRoleInRound(uint8 round, int16 role) public onlyOwner { require(allowedRolesInRound[allowedRolesInRoundSetId][round][role].exists, "Role not existed"); allowedRolesInRound[allowedRolesInRoundSetId][round][role].round_id = 0; allowedRolesInRound[allowedRolesInRoundSetId][round][role].role_id = 0; allowedRolesInRound[allowedRolesInRoundSetId][round][role].max_mint = 0; allowedRolesInRound[allowedRolesInRoundSetId][round][role].mint_price = 0; allowedRolesInRound[allowedRolesInRoundSetId][round][role].exists = false; allowedRolesInRoundCount[allowedRolesInRoundSetId][round]--; for (uint8 i = 0; i < allowedRolesInRoundArr[allowedRolesInRoundSetId][round].length; i++) { if (allowedRolesInRoundArr[allowedRolesInRoundSetId][round][i] == role) { removeArrayAtInt16Index(allowedRolesInRoundArr[allowedRolesInRoundSetId][round], i); break; } } if (allowedRolesInRoundCount[allowedRolesInRoundSetId][round] == 0) { for (uint8 i = 0; i < availableRounds.length; i++) { if (availableRounds[i] == round) { removeArrayAtUint8Index(availableRounds, i); break; } } } } function removeAllowedRoleInRound(uint8 round, int16 role) public onlyOwner { require(allowedRolesInRound[allowedRolesInRoundSetId][round][role].exists, "Role not existed"); allowedRolesInRound[allowedRolesInRoundSetId][round][role].round_id = 0; allowedRolesInRound[allowedRolesInRoundSetId][round][role].role_id = 0; allowedRolesInRound[allowedRolesInRoundSetId][round][role].max_mint = 0; allowedRolesInRound[allowedRolesInRoundSetId][round][role].mint_price = 0; allowedRolesInRound[allowedRolesInRoundSetId][round][role].exists = false; allowedRolesInRoundCount[allowedRolesInRoundSetId][round]--; for (uint8 i = 0; i < allowedRolesInRoundArr[allowedRolesInRoundSetId][round].length; i++) { if (allowedRolesInRoundArr[allowedRolesInRoundSetId][round][i] == role) { removeArrayAtInt16Index(allowedRolesInRoundArr[allowedRolesInRoundSetId][round], i); break; } } if (allowedRolesInRoundCount[allowedRolesInRoundSetId][round] == 0) { for (uint8 i = 0; i < availableRounds.length; i++) { if (availableRounds[i] == round) { removeArrayAtUint8Index(availableRounds, i); break; } } } } function removeAllowedRoleInRound(uint8 round, int16 role) public onlyOwner { require(allowedRolesInRound[allowedRolesInRoundSetId][round][role].exists, "Role not existed"); allowedRolesInRound[allowedRolesInRoundSetId][round][role].round_id = 0; allowedRolesInRound[allowedRolesInRoundSetId][round][role].role_id = 0; allowedRolesInRound[allowedRolesInRoundSetId][round][role].max_mint = 0; allowedRolesInRound[allowedRolesInRoundSetId][round][role].mint_price = 0; allowedRolesInRound[allowedRolesInRoundSetId][round][role].exists = false; allowedRolesInRoundCount[allowedRolesInRoundSetId][round]--; for (uint8 i = 0; i < allowedRolesInRoundArr[allowedRolesInRoundSetId][round].length; i++) { if (allowedRolesInRoundArr[allowedRolesInRoundSetId][round][i] == role) { removeArrayAtInt16Index(allowedRolesInRoundArr[allowedRolesInRoundSetId][round], i); break; } } if (allowedRolesInRoundCount[allowedRolesInRoundSetId][round] == 0) { for (uint8 i = 0; i < availableRounds.length; i++) { if (availableRounds[i] == round) { removeArrayAtUint8Index(availableRounds, i); break; } } } } function removeAllowedRoleInRound(uint8 round, int16 role) public onlyOwner { require(allowedRolesInRound[allowedRolesInRoundSetId][round][role].exists, "Role not existed"); allowedRolesInRound[allowedRolesInRoundSetId][round][role].round_id = 0; allowedRolesInRound[allowedRolesInRoundSetId][round][role].role_id = 0; allowedRolesInRound[allowedRolesInRoundSetId][round][role].max_mint = 0; allowedRolesInRound[allowedRolesInRoundSetId][round][role].mint_price = 0; allowedRolesInRound[allowedRolesInRoundSetId][round][role].exists = false; allowedRolesInRoundCount[allowedRolesInRoundSetId][round]--; for (uint8 i = 0; i < allowedRolesInRoundArr[allowedRolesInRoundSetId][round].length; i++) { if (allowedRolesInRoundArr[allowedRolesInRoundSetId][round][i] == role) { removeArrayAtInt16Index(allowedRolesInRoundArr[allowedRolesInRoundSetId][round], i); break; } } if (allowedRolesInRoundCount[allowedRolesInRoundSetId][round] == 0) { for (uint8 i = 0; i < availableRounds.length; i++) { if (availableRounds[i] == round) { removeArrayAtUint8Index(availableRounds, i); break; } } } } function removeAllowedRoleInRound(uint8 round, int16 role) public onlyOwner { require(allowedRolesInRound[allowedRolesInRoundSetId][round][role].exists, "Role not existed"); allowedRolesInRound[allowedRolesInRoundSetId][round][role].round_id = 0; allowedRolesInRound[allowedRolesInRoundSetId][round][role].role_id = 0; allowedRolesInRound[allowedRolesInRoundSetId][round][role].max_mint = 0; allowedRolesInRound[allowedRolesInRoundSetId][round][role].mint_price = 0; allowedRolesInRound[allowedRolesInRoundSetId][round][role].exists = false; allowedRolesInRoundCount[allowedRolesInRoundSetId][round]--; for (uint8 i = 0; i < allowedRolesInRoundArr[allowedRolesInRoundSetId][round].length; i++) { if (allowedRolesInRoundArr[allowedRolesInRoundSetId][round][i] == role) { removeArrayAtInt16Index(allowedRolesInRoundArr[allowedRolesInRoundSetId][round], i); break; } } if (allowedRolesInRoundCount[allowedRolesInRoundSetId][round] == 0) { for (uint8 i = 0; i < availableRounds.length; i++) { if (availableRounds[i] == round) { removeArrayAtUint8Index(availableRounds, i); break; } } } } function addRoundsAllocation(RoundAllocationParams[] memory params, bool replace) public onlyOwner { if (replace) { roundAllocationsSetId++; delete availableRounds; } for (uint i = 0; i < params.length; i++) addRoundAllocation(params[i].round, params[i].allocation, false); } function addRoundsAllocation(RoundAllocationParams[] memory params, bool replace) public onlyOwner { if (replace) { roundAllocationsSetId++; delete availableRounds; } for (uint i = 0; i < params.length; i++) addRoundAllocation(params[i].round, params[i].allocation, false); } function addRoundAllocation(uint8 round, uint256 allocation, bool replace) public onlyOwner { if (replace) { roundAllocationsSetId++; delete availableRounds; } roundAllocations[roundAllocationsSetId][round] = allocation; bool found = false; for (uint8 i = 0; i < availableRounds.length; i++) if (availableRounds[i] == round) found = true; if (!found) availableRounds.push(round); } function addRoundAllocation(uint8 round, uint256 allocation, bool replace) public onlyOwner { if (replace) { roundAllocationsSetId++; delete availableRounds; } roundAllocations[roundAllocationsSetId][round] = allocation; bool found = false; for (uint8 i = 0; i < availableRounds.length; i++) if (availableRounds[i] == round) found = true; if (!found) availableRounds.push(round); } function addRolesAllocation(RoleAllocationParams[] memory params, bool replace) public onlyOwner { if (replace) { roleAllocationsSetId++; delete availableRoles; } for (uint i = 0; i < params.length; i++) addRoleAllocation(params[i].role, params[i].allocation, false); } function addRolesAllocation(RoleAllocationParams[] memory params, bool replace) public onlyOwner { if (replace) { roleAllocationsSetId++; delete availableRoles; } for (uint i = 0; i < params.length; i++) addRoleAllocation(params[i].role, params[i].allocation, false); } function addRoleAllocation(int16 role, uint256 allocation, bool replace) public onlyOwner { if (replace) { roleAllocationsSetId++; delete availableRoles; } roleAllocations[roleAllocationsSetId][role] = allocation; bool found = false; for (uint16 i = 0; i < availableRoles.length; i++) if (availableRoles[i] == role) found = true; if (!found) availableRoles.push(role); } function addRoleAllocation(int16 role, uint256 allocation, bool replace) public onlyOwner { if (replace) { roleAllocationsSetId++; delete availableRoles; } roleAllocations[roleAllocationsSetId][role] = allocation; bool found = false; for (uint16 i = 0; i < availableRoles.length; i++) if (availableRoles[i] == role) found = true; if (!found) availableRoles.push(role); } function addRolesRounds( RoleInRoundParams[] memory rolesInRound, bool replaceRoleInRound, RoundAllocationParams[] memory roundAllocations, bool replaceRoundAllocations, RoleAllocationParams[] memory roleAllocations, bool replaceRoleAllocations ) public onlyOwner { addAllowedRolesInRound(rolesInRound, replaceRoleInRound); addRoundsAllocation(roundAllocations, replaceRoundAllocations); addRolesAllocation(roleAllocations, replaceRoleAllocations); } function freezeMetadata() public onlyOwner { metadataFrozen = true; } function mint(uint256 quantity, int16 role, uint16 apetimismFee, address apetimismAddress, uint256 nonce, uint8 v, bytes32 r, bytes32 s) external payable nonReentrant { require(currentRound != 0, "Not started"); uint256 combined_nonce = nonce; if (role >= 0) combined_nonce = (nonce << 16) + uint16(role); require(_nonces[combined_nonce] == 0, ERR_DUP_NONCE); require(_recoverAddress(abi.encodePacked(combined_nonce, apetimismFee, apetimismAddress), v, r, s) == signerAddress, ERR_INVALID_SIGNATURE); bool is_public_round = allowedRolesInRound[allowedRolesInRoundSetId][currentRound][0].exists; int16 selected_role = 0; if (role >= 0) selected_role = role; if (!allowedRolesInRound[allowedRolesInRoundSetId][currentRound][selected_role].exists) { if (!is_public_round) require(false, "Not eligible"); selected_role = 0; } require(quantity > 0, ERR_INVALID_AMOUNT); require(mintableLeft() >= quantity, ERR_RUN_OUT); if (role >= 0) require(maxMintableForTxForRole(msg.sender, role) >= quantity, ERR_HIT_MAXIMUM); else require(maxMintableForTxForRole(msg.sender, 0) >= quantity, ERR_HIT_MAXIMUM); uint256 cost = quantity * allowedRolesInRound[allowedRolesInRoundSetId][currentRound][selected_role].mint_price; _nonces[combined_nonce] = 1; if (currencyAddress != address(0)) { require(msg.value == 0, ERR_UNMATCHED_ETHER); require(msg.value == cost, ERR_UNMATCHED_ETHER); } _safeMint(msg.sender, quantity); totalMintedInRound[currentRound] = totalMintedInRound[currentRound] + quantity; _addressTokenMinted[msg.sender] = _addressTokenMinted[msg.sender] + quantity; _addressTokenMintedInRoundByRole[msg.sender][currentRound][selected_role] = _addressTokenMintedInRoundByRole[msg.sender][currentRound][selected_role] + quantity; if (selected_role >= 0) _addressTokenMintedInRole[msg.sender][selected_role] = _addressTokenMintedInRole[msg.sender][selected_role] + quantity; uint256 to_apetimism = cost * apetimismFee / 10000; if (currencyAddress != address(0)) { IERC20 tokenContract = IERC20(currencyAddress); tokenContract.transferFrom(msg.sender, address(this), cost); tokenContract.transfer(apetimismAddress, to_apetimism); payable(apetimismAddress).transfer(to_apetimism); } totalRevenueShared = totalRevenueShared + to_apetimism; } function mint(uint256 quantity, int16 role, uint16 apetimismFee, address apetimismAddress, uint256 nonce, uint8 v, bytes32 r, bytes32 s) external payable nonReentrant { require(currentRound != 0, "Not started"); uint256 combined_nonce = nonce; if (role >= 0) combined_nonce = (nonce << 16) + uint16(role); require(_nonces[combined_nonce] == 0, ERR_DUP_NONCE); require(_recoverAddress(abi.encodePacked(combined_nonce, apetimismFee, apetimismAddress), v, r, s) == signerAddress, ERR_INVALID_SIGNATURE); bool is_public_round = allowedRolesInRound[allowedRolesInRoundSetId][currentRound][0].exists; int16 selected_role = 0; if (role >= 0) selected_role = role; if (!allowedRolesInRound[allowedRolesInRoundSetId][currentRound][selected_role].exists) { if (!is_public_round) require(false, "Not eligible"); selected_role = 0; } require(quantity > 0, ERR_INVALID_AMOUNT); require(mintableLeft() >= quantity, ERR_RUN_OUT); if (role >= 0) require(maxMintableForTxForRole(msg.sender, role) >= quantity, ERR_HIT_MAXIMUM); else require(maxMintableForTxForRole(msg.sender, 0) >= quantity, ERR_HIT_MAXIMUM); uint256 cost = quantity * allowedRolesInRound[allowedRolesInRoundSetId][currentRound][selected_role].mint_price; _nonces[combined_nonce] = 1; if (currencyAddress != address(0)) { require(msg.value == 0, ERR_UNMATCHED_ETHER); require(msg.value == cost, ERR_UNMATCHED_ETHER); } _safeMint(msg.sender, quantity); totalMintedInRound[currentRound] = totalMintedInRound[currentRound] + quantity; _addressTokenMinted[msg.sender] = _addressTokenMinted[msg.sender] + quantity; _addressTokenMintedInRoundByRole[msg.sender][currentRound][selected_role] = _addressTokenMintedInRoundByRole[msg.sender][currentRound][selected_role] + quantity; if (selected_role >= 0) _addressTokenMintedInRole[msg.sender][selected_role] = _addressTokenMintedInRole[msg.sender][selected_role] + quantity; uint256 to_apetimism = cost * apetimismFee / 10000; if (currencyAddress != address(0)) { IERC20 tokenContract = IERC20(currencyAddress); tokenContract.transferFrom(msg.sender, address(this), cost); tokenContract.transfer(apetimismAddress, to_apetimism); payable(apetimismAddress).transfer(to_apetimism); } totalRevenueShared = totalRevenueShared + to_apetimism; } function mint(uint256 quantity, int16 role, uint16 apetimismFee, address apetimismAddress, uint256 nonce, uint8 v, bytes32 r, bytes32 s) external payable nonReentrant { require(currentRound != 0, "Not started"); uint256 combined_nonce = nonce; if (role >= 0) combined_nonce = (nonce << 16) + uint16(role); require(_nonces[combined_nonce] == 0, ERR_DUP_NONCE); require(_recoverAddress(abi.encodePacked(combined_nonce, apetimismFee, apetimismAddress), v, r, s) == signerAddress, ERR_INVALID_SIGNATURE); bool is_public_round = allowedRolesInRound[allowedRolesInRoundSetId][currentRound][0].exists; int16 selected_role = 0; if (role >= 0) selected_role = role; if (!allowedRolesInRound[allowedRolesInRoundSetId][currentRound][selected_role].exists) { if (!is_public_round) require(false, "Not eligible"); selected_role = 0; } require(quantity > 0, ERR_INVALID_AMOUNT); require(mintableLeft() >= quantity, ERR_RUN_OUT); if (role >= 0) require(maxMintableForTxForRole(msg.sender, role) >= quantity, ERR_HIT_MAXIMUM); else require(maxMintableForTxForRole(msg.sender, 0) >= quantity, ERR_HIT_MAXIMUM); uint256 cost = quantity * allowedRolesInRound[allowedRolesInRoundSetId][currentRound][selected_role].mint_price; _nonces[combined_nonce] = 1; if (currencyAddress != address(0)) { require(msg.value == 0, ERR_UNMATCHED_ETHER); require(msg.value == cost, ERR_UNMATCHED_ETHER); } _safeMint(msg.sender, quantity); totalMintedInRound[currentRound] = totalMintedInRound[currentRound] + quantity; _addressTokenMinted[msg.sender] = _addressTokenMinted[msg.sender] + quantity; _addressTokenMintedInRoundByRole[msg.sender][currentRound][selected_role] = _addressTokenMintedInRoundByRole[msg.sender][currentRound][selected_role] + quantity; if (selected_role >= 0) _addressTokenMintedInRole[msg.sender][selected_role] = _addressTokenMintedInRole[msg.sender][selected_role] + quantity; uint256 to_apetimism = cost * apetimismFee / 10000; if (currencyAddress != address(0)) { IERC20 tokenContract = IERC20(currencyAddress); tokenContract.transferFrom(msg.sender, address(this), cost); tokenContract.transfer(apetimismAddress, to_apetimism); payable(apetimismAddress).transfer(to_apetimism); } totalRevenueShared = totalRevenueShared + to_apetimism; } } else { function mint(uint256 quantity, int16 role, uint16 apetimismFee, address apetimismAddress, uint256 nonce, uint8 v, bytes32 r, bytes32 s) external payable nonReentrant { require(currentRound != 0, "Not started"); uint256 combined_nonce = nonce; if (role >= 0) combined_nonce = (nonce << 16) + uint16(role); require(_nonces[combined_nonce] == 0, ERR_DUP_NONCE); require(_recoverAddress(abi.encodePacked(combined_nonce, apetimismFee, apetimismAddress), v, r, s) == signerAddress, ERR_INVALID_SIGNATURE); bool is_public_round = allowedRolesInRound[allowedRolesInRoundSetId][currentRound][0].exists; int16 selected_role = 0; if (role >= 0) selected_role = role; if (!allowedRolesInRound[allowedRolesInRoundSetId][currentRound][selected_role].exists) { if (!is_public_round) require(false, "Not eligible"); selected_role = 0; } require(quantity > 0, ERR_INVALID_AMOUNT); require(mintableLeft() >= quantity, ERR_RUN_OUT); if (role >= 0) require(maxMintableForTxForRole(msg.sender, role) >= quantity, ERR_HIT_MAXIMUM); else require(maxMintableForTxForRole(msg.sender, 0) >= quantity, ERR_HIT_MAXIMUM); uint256 cost = quantity * allowedRolesInRound[allowedRolesInRoundSetId][currentRound][selected_role].mint_price; _nonces[combined_nonce] = 1; if (currencyAddress != address(0)) { require(msg.value == 0, ERR_UNMATCHED_ETHER); require(msg.value == cost, ERR_UNMATCHED_ETHER); } _safeMint(msg.sender, quantity); totalMintedInRound[currentRound] = totalMintedInRound[currentRound] + quantity; _addressTokenMinted[msg.sender] = _addressTokenMinted[msg.sender] + quantity; _addressTokenMintedInRoundByRole[msg.sender][currentRound][selected_role] = _addressTokenMintedInRoundByRole[msg.sender][currentRound][selected_role] + quantity; if (selected_role >= 0) _addressTokenMintedInRole[msg.sender][selected_role] = _addressTokenMintedInRole[msg.sender][selected_role] + quantity; uint256 to_apetimism = cost * apetimismFee / 10000; if (currencyAddress != address(0)) { IERC20 tokenContract = IERC20(currencyAddress); tokenContract.transferFrom(msg.sender, address(this), cost); tokenContract.transfer(apetimismAddress, to_apetimism); payable(apetimismAddress).transfer(to_apetimism); } totalRevenueShared = totalRevenueShared + to_apetimism; } } else { function adminMintTo(address to, uint256 quantity) public onlyOwner { require(quantity > 0, ERR_INVALID_AMOUNT); require(mintableLeft() >= quantity, ERR_RUN_OUT); _safeMint(to, quantity); } function setCurrentRoundFromSignature(uint256 nonce, uint8 round, uint8 v, bytes32 r, bytes32 s) public { require(_nonces[nonce] == 0, ERR_DUP_NONCE); require(_recoverAddress(abi.encodePacked(nonce, round), v, r, s) == signerAddress, ERR_INVALID_SIGNATURE); _nonces[nonce] = 1; currentRound = round; emit RoundChanged(round); } function setSignerAddressFromSignature(uint256 nonce, address addr, uint8 v, bytes32 r, bytes32 s) public { require(_nonces[nonce] == 0, ERR_DUP_NONCE); require(_recoverAddress(abi.encodePacked(nonce, addr), v, r, s) == signerAddress, ERR_INVALID_SIGNATURE); _nonces[nonce] = 1; signerAddress = addr; } function transfersFrom( address from, address to, uint256[] calldata tokenIds ) public virtual { for (uint i = 0; i < tokenIds.length; i++) transferFrom(from, to, tokenIds[i]); } function safeTransfersFrom( address from, address to, uint256[] calldata tokenIds ) public virtual { for (uint i = 0; i < tokenIds.length; i++) safeTransferFrom(from, to, tokenIds[i]); } function safeTransfersFrom( address from, address to, uint256[] calldata tokenIds, bytes memory _data ) public virtual { for (uint i = 0; i < tokenIds.length; i++) safeTransferFrom(from, to, tokenIds[i], _data); } function getAllowedRolesInRoundArr(uint8 round) public view returns (int16[] memory) { uint256 len = allowedRolesInRoundArr[allowedRolesInRoundSetId][round].length; int16[] memory ret = new int16[](len); for (uint i = 0; i < len; i++) ret[i] = allowedRolesInRoundArr[allowedRolesInRoundSetId][round][i]; return ret; } function getAllAllowedRolesInRounds() public view returns (RoleInRoundParams[] memory) { uint256 len = 0; for (uint i = 0; i < availableAllowedRounds.length; i++) len += allowedRolesInRoundCount[allowedRolesInRoundSetId][ availableAllowedRounds[i] ]; RoleInRoundParams[] memory ret = new RoleInRoundParams[](len); uint256 index = 0; for (uint i = 0; i < availableAllowedRounds.length; i++) { uint8 round = availableAllowedRounds[i]; for (uint j = 0; j < allowedRolesInRoundCount[allowedRolesInRoundSetId][ availableAllowedRounds[i] ]; j++) { int16 role = allowedRolesInRoundArr[allowedRolesInRoundSetId][round][j]; ret[index].round = round; ret[index].role = role; ret[index].maxMint = allowedRolesInRound[allowedRolesInRoundSetId][round][role].max_mint; ret[index].mintPrice = allowedRolesInRound[allowedRolesInRoundSetId][round][role].mint_price; index++; } } return ret; } function getAllAllowedRolesInRounds() public view returns (RoleInRoundParams[] memory) { uint256 len = 0; for (uint i = 0; i < availableAllowedRounds.length; i++) len += allowedRolesInRoundCount[allowedRolesInRoundSetId][ availableAllowedRounds[i] ]; RoleInRoundParams[] memory ret = new RoleInRoundParams[](len); uint256 index = 0; for (uint i = 0; i < availableAllowedRounds.length; i++) { uint8 round = availableAllowedRounds[i]; for (uint j = 0; j < allowedRolesInRoundCount[allowedRolesInRoundSetId][ availableAllowedRounds[i] ]; j++) { int16 role = allowedRolesInRoundArr[allowedRolesInRoundSetId][round][j]; ret[index].round = round; ret[index].role = role; ret[index].maxMint = allowedRolesInRound[allowedRolesInRoundSetId][round][role].max_mint; ret[index].mintPrice = allowedRolesInRound[allowedRolesInRoundSetId][round][role].mint_price; index++; } } return ret; } function getAllAllowedRolesInRounds() public view returns (RoleInRoundParams[] memory) { uint256 len = 0; for (uint i = 0; i < availableAllowedRounds.length; i++) len += allowedRolesInRoundCount[allowedRolesInRoundSetId][ availableAllowedRounds[i] ]; RoleInRoundParams[] memory ret = new RoleInRoundParams[](len); uint256 index = 0; for (uint i = 0; i < availableAllowedRounds.length; i++) { uint8 round = availableAllowedRounds[i]; for (uint j = 0; j < allowedRolesInRoundCount[allowedRolesInRoundSetId][ availableAllowedRounds[i] ]; j++) { int16 role = allowedRolesInRoundArr[allowedRolesInRoundSetId][round][j]; ret[index].round = round; ret[index].role = role; ret[index].maxMint = allowedRolesInRound[allowedRolesInRoundSetId][round][role].max_mint; ret[index].mintPrice = allowedRolesInRound[allowedRolesInRoundSetId][round][role].mint_price; index++; } } return ret; } function getAllRoundAllocations() public view returns (RoundAllocationParams[] memory) { uint256 len = availableRounds.length; RoundAllocationParams[] memory ret = new RoundAllocationParams[](len); for (uint i = 0; i < len; i++) { ret[i].round = availableRounds[i]; ret[i].allocation = roundAllocations[roundAllocationsSetId][availableRounds[i]]; } return ret; } function getAllRoundAllocations() public view returns (RoundAllocationParams[] memory) { uint256 len = availableRounds.length; RoundAllocationParams[] memory ret = new RoundAllocationParams[](len); for (uint i = 0; i < len; i++) { ret[i].round = availableRounds[i]; ret[i].allocation = roundAllocations[roundAllocationsSetId][availableRounds[i]]; } return ret; } function getAllRoleAllocations() public view returns (RoleAllocationParams[] memory) { uint256 len = availableRoles.length; RoleAllocationParams[] memory ret = new RoleAllocationParams[](len); for (uint i = 0; i < len; i++) { ret[i].role = availableRoles[i]; ret[i].allocation = roleAllocations[roleAllocationsSetId][availableRoles[i]]; } return ret; } function getAllRoleAllocations() public view returns (RoleAllocationParams[] memory) { uint256 len = availableRoles.length; RoleAllocationParams[] memory ret = new RoleAllocationParams[](len); for (uint i = 0; i < len; i++) { ret[i].role = availableRoles[i]; ret[i].allocation = roleAllocations[roleAllocationsSetId][availableRoles[i]]; } return ret; } function mintPriceForCurrentRoundForRole(int16 role) public view returns (uint256) { return allowedRolesInRound[allowedRolesInRoundSetId][currentRound][role].mint_price; } function maxMintableForRole(address addr, int16 role) public view virtual returns (uint256) { uint256 minted = _addressTokenMinted[addr]; uint256 max_mint = 0; if (currentRound == 0) return 0; if (totalMintedInRound[currentRound] >= roundAllocations[roundAllocationsSetId][currentRound]) return 0; if (_addressTokenMintedInRole[addr][role] >= roleAllocations[roleAllocationsSetId][role]) return 0; if (allowedRolesInRound[allowedRolesInRoundSetId][currentRound][role].exists) max_mint = allowedRolesInRound[allowedRolesInRoundSetId][currentRound][role].max_mint; if (minted >= maxMintPerAddress) return 0; if (_addressTokenMintedInRoundByRole[addr][currentRound][role] >= max_mint) return 0; if (totalMintedInRound[currentRound] >= roundAllocations[roundAllocationsSetId][currentRound]) return 0; if (_addressTokenMintedInRole[addr][role] >= roleAllocations[roleAllocationsSetId][role]) return 0; uint256 wallet_quota_left = maxMintPerAddress - minted; uint256 round_quota_left = max_mint - _addressTokenMintedInRoundByRole[addr][currentRound][role]; uint256 round_allocation_quota_left = roundAllocations[roundAllocationsSetId][currentRound] - totalMintedInRound[currentRound]; uint256 role_quota_left = roleAllocations[roleAllocationsSetId][role] - _addressTokenMintedInRole[addr][role]; return min(mintableLeft(), min(min(min(wallet_quota_left, round_quota_left), round_allocation_quota_left), role_quota_left)); } function maxMintableForTxForRole(address addr, int16 role) public view virtual returns (uint256) { uint256 mintable = maxMintableForRole(addr, role); if (mintable > maxMintPerTx) return maxMintPerTx; return mintable; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), 'nonexistent token'); if (bytes(baseURIExtended).length == 0) return ''; string memory extension = ""; if (metdataHasExtension) extension = ".json"; return string(abi.encodePacked(baseURIExtended, Strings.toString(tokenId), extension)); } function totalMinted() public view returns (uint256) { return _totalMinted(); } function mintableLeft() public view returns (uint256) { return MAX_SUPPLY - totalMinted(); } function removeArrayAtInt16Index(int16[] storage array, uint256 index) private { for (uint i = index; i < array.length - 1; i++) array[i] = array[i + 1]; delete array[array.length - 1]; array.pop(); } function removeArrayAtUint8Index(uint8[] storage array, uint256 index) private { for (uint i = index; i < array.length - 1; i++) array[i] = array[i + 1]; delete array[array.length - 1]; array.pop(); } function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } function _recoverAddress(bytes memory data, uint8 v, bytes32 r, bytes32 s) private pure returns (address) { bytes32 msgHash = keccak256(data); bytes32 messageDigest = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", msgHash)); return ecrecover(messageDigest, v, r, s); } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721A) returns (bool) { return super.supportsInterface(interfaceId) || ERC721A.supportsInterface(interfaceId); } function withdraw() public onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } function withdrawToken(address tokenAddress) public onlyOwner { IERC20 tokenContract = IERC20(tokenAddress); tokenContract.transfer(msg.sender, tokenContract.balanceOf(address(this))); } receive() external payable { emit Received(msg.sender, msg.value); } }
11,517,790
[ 1, 2918, 3186, 7224, 23536, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 1716, 278, 381, 6228, 9569, 6982, 50, 4464, 353, 4232, 39, 27, 5340, 37, 1138, 429, 16, 14223, 6914, 16, 868, 8230, 12514, 16709, 1748, 16, 4232, 39, 5540, 11861, 5549, 288, 203, 225, 871, 21066, 12, 2867, 16, 2254, 1769, 203, 225, 871, 11370, 5033, 12, 11890, 28, 1769, 203, 225, 871, 10710, 49, 474, 329, 5033, 12, 11890, 5034, 1769, 203, 203, 203, 225, 533, 3238, 10359, 67, 9347, 67, 26587, 273, 315, 1941, 3553, 14432, 203, 225, 533, 3238, 10359, 67, 30387, 67, 3993, 1441, 273, 315, 30419, 7448, 14432, 203, 225, 533, 3238, 10359, 67, 2124, 11793, 2056, 67, 1584, 3891, 273, 315, 984, 11073, 225, 2437, 14432, 203, 225, 533, 3238, 10359, 67, 17222, 67, 6694, 18605, 273, 315, 13616, 4207, 14432, 203, 225, 533, 3238, 10359, 67, 9347, 67, 2192, 51, 5321, 273, 315, 1941, 3844, 14432, 203, 225, 533, 3238, 10359, 67, 15238, 67, 5069, 273, 315, 1997, 596, 14432, 203, 203, 225, 2254, 5034, 1071, 4552, 67, 13272, 23893, 273, 5958, 2313, 31, 203, 225, 2254, 5034, 1071, 10485, 67, 8412, 67, 734, 273, 404, 31, 203, 225, 533, 3238, 5381, 14275, 67, 1985, 273, 315, 61, 2192, 55, 14432, 203, 225, 533, 3238, 5381, 14275, 67, 22093, 273, 315, 61, 2192, 55, 14432, 203, 203, 203, 225, 2874, 12, 2867, 516, 2254, 5034, 13, 3238, 389, 2867, 1345, 49, 474, 329, 31, 203, 225, 2874, 12, 2867, 516, 2874, 12, 11890, 28, 516, 2874, 12, 474, 2313, 516, 2254, 5034, 20349, 3238, 389, 2867, 2 ]
./partial_match/1/0x00000000000006c7676171937C444f6BDe3D6282/sources/contracts/helpers/PointerLibraries.sol
@dev Reads the bytes31 at `mPtr` in memory.
function readBytes31( MemoryPointer mPtr ) internal pure returns (bytes31 value) { assembly { value := mload(mPtr) } }
4,300,604
[ 1, 7483, 326, 1731, 6938, 622, 1375, 81, 5263, 68, 316, 3778, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 25825, 6938, 12, 203, 3639, 9251, 4926, 312, 5263, 203, 565, 262, 2713, 16618, 1135, 261, 3890, 6938, 460, 13, 288, 203, 3639, 19931, 288, 203, 5411, 460, 519, 312, 945, 12, 81, 5263, 13, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.24; contract BBFarmEvents { event BallotCreatedWithID(uint ballotId); event BBFarmInit(bytes4 namespace); event Sponsorship(uint ballotId, uint value); event Vote(uint indexed ballotId, bytes32 vote, address voter, bytes extra); } library BBLib { using BytesLib for bytes; // ballot meta uint256 constant BB_VERSION = 6; /* 4 deprecated due to insecure vote by proxy 5 deprecated to - add `returns (address)` to submitProxyVote */ // voting settings uint16 constant USE_ETH = 1; // 2^0 uint16 constant USE_SIGNED = 2; // 2^1 uint16 constant USE_NO_ENC = 4; // 2^2 uint16 constant USE_ENC = 8; // 2^3 // ballot settings uint16 constant IS_BINDING = 8192; // 2^13 uint16 constant IS_OFFICIAL = 16384; // 2^14 uint16 constant USE_TESTING = 32768; // 2^15 // other consts uint32 constant MAX_UINT32 = 0xFFFFFFFF; //// ** Storage Variables // struct for ballot struct Vote { bytes32 voteData; bytes32 castTsAndSender; bytes extra; } struct Sponsor { address sender; uint amount; } //// ** Events event CreatedBallot(bytes32 _specHash, uint64 startTs, uint64 endTs, uint16 submissionBits); event SuccessfulVote(address indexed voter, uint voteId); event SeckeyRevealed(bytes32 secretKey); event TestingEnabled(); event DeprecatedContract(); // The big database struct struct DB { // Maps to store ballots, along with corresponding log of voters. // Should only be modified through internal functions mapping (uint256 => Vote) votes; uint256 nVotesCast; // we need replay protection for proxy ballots - this will let us check against a sequence number // note: votes directly from a user ALWAYS take priority b/c they do not have sequence numbers // (sequencing is done by Ethereum itself via the tx nonce). mapping (address => uint32) sequenceNumber; // NOTE - We don't actually want to include the encryption PublicKey because _it's included in the ballotSpec_. // It's better to ensure ppl actually have the ballot spec by not including it in the contract. // Plus we're already storing the hash of the ballotSpec anyway... // Private key to be set after ballot conclusion - curve25519 bytes32 ballotEncryptionSeckey; // packed contains: // 1. Timestamps for start and end of ballot (UTC) // 2. bits used to decide which options are enabled or disabled for submission of ballots uint256 packed; // specHash by which to validate the ballots integrity bytes32 specHash; // extradata if we need it - allows us to upgrade spechash format, etc bytes16 extraData; // allow tracking of sponsorship for this ballot & connection to index Sponsor[] sponsors; IxIface index; // deprecation flag - doesn't actually do anything besides signal that this contract is deprecated; bool deprecated; address ballotOwner; uint256 creationTs; } // ** Modifiers -- note, these are functions here to allow use as a lib function requireBallotClosed(DB storage db) internal view { require(now > BPackedUtils.packedToEndTime(db.packed), "!b-closed"); } function requireBallotOpen(DB storage db) internal view { uint64 _n = uint64(now); uint64 startTs; uint64 endTs; (, startTs, endTs) = BPackedUtils.unpackAll(db.packed); require(_n >= startTs && _n < endTs, "!b-open"); require(db.deprecated == false, "b-deprecated"); } function requireBallotOwner(DB storage db) internal view { require(msg.sender == db.ballotOwner, "!b-owner"); } function requireTesting(DB storage db) internal view { require(isTesting(BPackedUtils.packedToSubmissionBits(db.packed)), "!testing"); } /* Library meta */ function getVersion() external pure returns (uint) { // even though this is constant we want to make sure that it's actually // callable on Ethereum so we don't accidentally package the constant code // in with an SC using BBLib. This function _must_ be external. return BB_VERSION; } /* Functions */ // "Constructor" function - init core params on deploy // timestampts are uint64s to give us plenty of room for millennia function init(DB storage db, bytes32 _specHash, uint256 _packed, IxIface ix, address ballotOwner, bytes16 extraData) external { require(db.specHash == bytes32(0), "b-exists"); db.index = ix; db.ballotOwner = ballotOwner; uint64 startTs; uint64 endTs; uint16 sb; (sb, startTs, endTs) = BPackedUtils.unpackAll(_packed); bool _testing = isTesting(sb); if (_testing) { emit TestingEnabled(); } else { require(endTs > now, "bad-end-time"); // 0x1ff2 is 0001111111110010 in binary // by ANDing with subBits we make sure that only bits in positions 0,2,3,13,14,15 // can be used. these correspond to the option flags at the top, and ETH ballots // that are enc'd or plaintext. require(sb & 0x1ff2 == 0, "bad-sb"); // if we give bad submission bits (e.g. all 0s) then refuse to deploy ballot bool okaySubmissionBits = 1 == (isEthNoEnc(sb) ? 1 : 0) + (isEthWithEnc(sb) ? 1 : 0); require(okaySubmissionBits, "!valid-sb"); // take the max of the start time provided and the blocks timestamp to avoid a DoS against recent token holders // (which someone might be able to do if they could set the timestamp in the past) startTs = startTs > now ? startTs : uint64(now); } require(_specHash != bytes32(0), "null-specHash"); db.specHash = _specHash; db.packed = BPackedUtils.pack(sb, startTs, endTs); db.creationTs = now; if (extraData != bytes16(0)) { db.extraData = extraData; } emit CreatedBallot(db.specHash, startTs, endTs, sb); } /* sponsorship */ function logSponsorship(DB storage db, uint value) internal { db.sponsors.push(Sponsor(msg.sender, value)); } /* getters */ function getVote(DB storage db, uint id) internal view returns (bytes32 voteData, address sender, bytes extra, uint castTs) { return (db.votes[id].voteData, address(db.votes[id].castTsAndSender), db.votes[id].extra, uint(db.votes[id].castTsAndSender) >> 160); } function getSequenceNumber(DB storage db, address voter) internal view returns (uint32) { return db.sequenceNumber[voter]; } function getTotalSponsorship(DB storage db) internal view returns (uint total) { for (uint i = 0; i < db.sponsors.length; i++) { total += db.sponsors[i].amount; } } function getSponsor(DB storage db, uint i) external view returns (address sender, uint amount) { sender = db.sponsors[i].sender; amount = db.sponsors[i].amount; } /* ETH BALLOTS */ // Ballot submission // note: if USE_ENC then curve25519 keys should be generated for // each ballot (then thrown away). // the curve25519 PKs go in the extra param function submitVote(DB storage db, bytes32 voteData, bytes extra) external { _addVote(db, voteData, msg.sender, extra); // set the sequence number to max uint32 to disable proxy submitted ballots // after a voter submits a transaction personally - effectivley disables proxy // ballots. You can _always_ submit a new vote _personally_ with this scheme. if (db.sequenceNumber[msg.sender] != MAX_UINT32) { // using an IF statement here let's us save 4800 gas on repeat votes at the cost of 20k extra gas initially db.sequenceNumber[msg.sender] = MAX_UINT32; } } // Boundaries for constructing the msg we'll validate the signature of function submitProxyVote(DB storage db, bytes32[5] proxyReq, bytes extra) external returns (address voter) { // a proxy vote (where the vote is submitted (i.e. tx fee paid by someone else) // docs for datastructs: https://github.com/secure-vote/tokenvote/blob/master/Docs/DataStructs.md bytes32 r = proxyReq[0]; bytes32 s = proxyReq[1]; uint8 v = uint8(proxyReq[2][0]); // converting to uint248 will truncate the first byte, and we can then convert it to a bytes31. // we truncate the first byte because it's the `v` parm used above bytes31 proxyReq2 = bytes31(uint248(proxyReq[2])); // proxyReq[3] is ballotId - required for verifying sig but not used for anything else bytes32 ballotId = proxyReq[3]; bytes32 voteData = proxyReq[4]; // using abi.encodePacked is much cheaper than making bytes in other ways... bytes memory signed = abi.encodePacked(proxyReq2, ballotId, voteData, extra); bytes32 msgHash = keccak256(signed); // need to be sure we are signing the entire ballot and any extra data that comes with it voter = ecrecover(msgHash, v, r, s); // we need to make sure that this is the most recent vote the voter made, and that it has // not been seen before. NOTE: we've already validated the BBFarm namespace before this, so // we know it's meant for _this_ ballot. uint32 sequence = uint32(proxyReq2); // last 4 bytes of proxyReq2 - the sequence number _proxyReplayProtection(db, voter, sequence); _addVote(db, voteData, voter, extra); } function _addVote(DB storage db, bytes32 voteData, address sender, bytes extra) internal returns (uint256 id) { requireBallotOpen(db); id = db.nVotesCast; db.votes[id].voteData = voteData; // pack the casting ts right next to the sender db.votes[id].castTsAndSender = bytes32(sender) ^ bytes32(now << 160); if (extra.length > 0) { db.votes[id].extra = extra; } db.nVotesCast += 1; emit SuccessfulVote(sender, id); } function _proxyReplayProtection(DB storage db, address voter, uint32 sequence) internal { // we want the replay protection sequence number to be STRICTLY MORE than what // is stored in the mapping. This means we can set sequence to MAX_UINT32 to disable // any future votes. require(db.sequenceNumber[voter] < sequence, "bad-sequence-n"); db.sequenceNumber[voter] = sequence; } /* Admin */ function setEndTime(DB storage db, uint64 newEndTime) external { uint16 sb; uint64 sTs; (sb, sTs,) = BPackedUtils.unpackAll(db.packed); db.packed = BPackedUtils.pack(sb, sTs, newEndTime); } function revealSeckey(DB storage db, bytes32 sk) internal { db.ballotEncryptionSeckey = sk; emit SeckeyRevealed(sk); } /* Submission Bits (Ballot Classifications) */ // do (bits & SETTINGS_MASK) to get just operational bits (as opposed to testing or official flag) uint16 constant SETTINGS_MASK = 0xFFFF ^ USE_TESTING ^ IS_OFFICIAL ^ IS_BINDING; function isEthNoEnc(uint16 submissionBits) pure internal returns (bool) { return checkFlags(submissionBits, USE_ETH | USE_NO_ENC); } function isEthWithEnc(uint16 submissionBits) pure internal returns (bool) { return checkFlags(submissionBits, USE_ETH | USE_ENC); } function isOfficial(uint16 submissionBits) pure internal returns (bool) { return (submissionBits & IS_OFFICIAL) == IS_OFFICIAL; } function isBinding(uint16 submissionBits) pure internal returns (bool) { return (submissionBits & IS_BINDING) == IS_BINDING; } function isTesting(uint16 submissionBits) pure internal returns (bool) { return (submissionBits & USE_TESTING) == USE_TESTING; } function qualifiesAsCommunityBallot(uint16 submissionBits) pure internal returns (bool) { // if submissionBits AND any of the bits that make this _not_ a community // ballot is equal to zero that means none of those bits were active, so // it could be a community ballot return (submissionBits & (IS_BINDING | IS_OFFICIAL | USE_ENC)) == 0; } function checkFlags(uint16 submissionBits, uint16 expected) pure internal returns (bool) { // this should ignore ONLY the testing/flag bits - all other bits are significant uint16 sBitsNoSettings = submissionBits & SETTINGS_MASK; // then we want ONLY expected return sBitsNoSettings == expected; } } library BPackedUtils { // the uint16 ending at 128 bits should be 0s uint256 constant sbMask = 0xffffffffffffffffffffffffffff0000ffffffffffffffffffffffffffffffff; uint256 constant startTimeMask = 0xffffffffffffffffffffffffffffffff0000000000000000ffffffffffffffff; uint256 constant endTimeMask = 0xffffffffffffffffffffffffffffffffffffffffffffffff0000000000000000; function packedToSubmissionBits(uint256 packed) internal pure returns (uint16) { return uint16(packed >> 128); } function packedToStartTime(uint256 packed) internal pure returns (uint64) { return uint64(packed >> 64); } function packedToEndTime(uint256 packed) internal pure returns (uint64) { return uint64(packed); } function unpackAll(uint256 packed) internal pure returns (uint16 submissionBits, uint64 startTime, uint64 endTime) { submissionBits = uint16(packed >> 128); startTime = uint64(packed >> 64); endTime = uint64(packed); } function pack(uint16 sb, uint64 st, uint64 et) internal pure returns (uint256 packed) { return uint256(sb) << 128 | uint256(st) << 64 | uint256(et); } function setSB(uint256 packed, uint16 newSB) internal pure returns (uint256) { return (packed & sbMask) | uint256(newSB) << 128; } // function setStartTime(uint256 packed, uint64 startTime) internal pure returns (uint256) { // return (packed & startTimeMask) | uint256(startTime) << 64; // } // function setEndTime(uint256 packed, uint64 endTime) internal pure returns (uint256) { // return (packed & endTimeMask) | uint256(endTime); // } } interface CommAuctionIface { function getNextPrice(bytes32 democHash) external view returns (uint); function noteBallotDeployed(bytes32 democHash) external; // add more when we need it function upgradeMe(address newSC) external; } library IxLib { /** * Usage: `using IxLib for IxIface` * The idea is to (instead of adding methods that already use * available public info to the index) we can create `internal` * methods in the lib to do this instead (which means the code * is inserted into other contracts inline, without a `delegatecall`. * * For this reason it's crucial to have no methods in IxLib with the * same name as methods in IxIface */ /* Global price and payments data */ function getPayTo(IxIface ix) internal view returns (address) { return ix.getPayments().getPayTo(); } /* Global Ix data */ function getBBFarmFromBallotID(IxIface ix, uint256 ballotId) internal view returns (BBFarmIface) { bytes4 bbNamespace = bytes4(ballotId >> 48); uint8 bbFarmId = ix.getBBFarmID(bbNamespace); return ix.getBBFarm(bbFarmId); } /* Global backend data */ function getGDemocsN(IxIface ix) internal view returns (uint256) { return ix.getBackend().getGDemocsN(); } function getGDemoc(IxIface ix, uint256 n) internal view returns (bytes32) { return ix.getBackend().getGDemoc(n); } function getGErc20ToDemocs(IxIface ix, address erc20) internal view returns (bytes32[] democHashes) { return ix.getBackend().getGErc20ToDemocs(erc20); } /* Democ specific payment/account data */ function accountInGoodStanding(IxIface ix, bytes32 democHash) internal view returns (bool) { return ix.getPayments().accountInGoodStanding(democHash); } function accountPremiumAndInGoodStanding(IxIface ix, bytes32 democHash) internal view returns (bool) { IxPaymentsIface payments = ix.getPayments(); return payments.accountInGoodStanding(democHash) && payments.getPremiumStatus(democHash); } function payForDemocracy(IxIface ix, bytes32 democHash) internal { ix.getPayments().payForDemocracy.value(msg.value)(democHash); } /* Democ getters */ function getDOwner(IxIface ix, bytes32 democHash) internal view returns (address) { return ix.getBackend().getDOwner(democHash); } function isDEditor(IxIface ix, bytes32 democHash, address editor) internal view returns (bool) { return ix.getBackend().isDEditor(democHash, editor); } function getDBallotsN(IxIface ix, bytes32 democHash) internal view returns (uint256) { return ix.getBackend().getDBallotsN(democHash); } function getDBallotID(IxIface ix, bytes32 democHash, uint256 n) internal view returns (uint256) { return ix.getBackend().getDBallotID(democHash, n); } function getDInfo(IxIface ix, bytes32 democHash) internal view returns (address erc20, address admin, uint256 _nBallots) { return ix.getBackend().getDInfo(democHash); } function getDErc20(IxIface ix, bytes32 democHash) internal view returns (address erc20) { return ix.getBackend().getDErc20(democHash); } function getDHash(IxIface ix, bytes13 prefix) internal view returns (bytes32) { return ix.getBackend().getDHash(prefix); } function getDCategoriesN(IxIface ix, bytes32 democHash) internal view returns (uint) { return ix.getBackend().getDCategoriesN(democHash); } function getDCategory(IxIface ix, bytes32 democHash, uint categoryId) internal view returns (bool, bytes32, bool, uint) { return ix.getBackend().getDCategory(democHash, categoryId); } function getDArbitraryData(IxIface ix, bytes32 democHash, bytes key) external view returns (bytes) { return ix.getBackend().getDArbitraryData(democHash, key); } } contract SVBallotConsts { // voting settings uint16 constant USE_ETH = 1; // 2^0 uint16 constant USE_SIGNED = 2; // 2^1 uint16 constant USE_NO_ENC = 4; // 2^2 uint16 constant USE_ENC = 8; // 2^3 // ballot settings uint16 constant IS_BINDING = 8192; // 2^13 uint16 constant IS_OFFICIAL = 16384; // 2^14 uint16 constant USE_TESTING = 32768; // 2^15 } contract safeSend { bool private txMutex3847834; // we want to be able to call outside contracts (e.g. the admin proxy contract) // but reentrency is bad, so here's a mutex. function doSafeSend(address toAddr, uint amount) internal { doSafeSendWData(toAddr, "", amount); } function doSafeSendWData(address toAddr, bytes data, uint amount) internal { require(txMutex3847834 == false, "ss-guard"); txMutex3847834 = true; // we need to use address.call.value(v)() because we want // to be able to send to other contracts, even with no data, // which might use more than 2300 gas in their fallback function. require(toAddr.call.value(amount)(data), "ss-failed"); txMutex3847834 = false; } } contract payoutAllC is safeSend { address private _payTo; event PayoutAll(address payTo, uint value); constructor(address initPayTo) public { // DEV NOTE: you can overwrite _getPayTo if you want to reuse other storage vars assert(initPayTo != address(0)); _payTo = initPayTo; } function _getPayTo() internal view returns (address) { return _payTo; } function _setPayTo(address newPayTo) internal { _payTo = newPayTo; } function payoutAll() external { address a = _getPayTo(); uint bal = address(this).balance; doSafeSend(a, bal); emit PayoutAll(a, bal); } } contract payoutAllCSettable is payoutAllC { constructor (address initPayTo) payoutAllC(initPayTo) public { } function setPayTo(address) external; function getPayTo() external view returns (address) { return _getPayTo(); } } contract owned { address public owner; event OwnerChanged(address newOwner); modifier only_owner() { require(msg.sender == owner, "only_owner: forbidden"); _; } modifier owner_or(address addr) { require(msg.sender == addr || msg.sender == owner, "!owner-or"); _; } constructor() public { owner = msg.sender; } function setOwner(address newOwner) only_owner() external { owner = newOwner; emit OwnerChanged(newOwner); } } contract CanReclaimToken is owned { /** * @dev Reclaim all ERC20Basic compatible tokens * @param token ERC20Basic The address of the token contract */ function reclaimToken(ERC20Interface token) external only_owner { uint256 balance = token.balanceOf(this); require(token.approve(owner, balance)); } } contract CommunityAuctionSimple is owned { // about $1USD at $600usd/eth uint public commBallotPriceWei = 1666666666000000; struct Record { bytes32 democHash; uint ts; } mapping (address => Record[]) public ballotLog; mapping (address => address) public upgrades; function getNextPrice(bytes32) external view returns (uint) { return commBallotPriceWei; } function noteBallotDeployed(bytes32 d) external { require(upgrades[msg.sender] == address(0)); ballotLog[msg.sender].push(Record(d, now)); } function upgradeMe(address newSC) external { require(upgrades[msg.sender] == address(0)); upgrades[msg.sender] = newSC; } function getBallotLogN(address a) external view returns (uint) { return ballotLog[a].length; } function setPriceWei(uint newPrice) only_owner() external { commBallotPriceWei = newPrice; } } contract controlledIface { function controller() external view returns (address); } contract hasAdmins is owned { mapping (uint => mapping (address => bool)) admins; uint public currAdminEpoch = 0; bool public adminsDisabledForever = false; address[] adminLog; event AdminAdded(address indexed newAdmin); event AdminRemoved(address indexed oldAdmin); event AdminEpochInc(); event AdminDisabledForever(); modifier only_admin() { require(adminsDisabledForever == false, "admins must not be disabled"); require(isAdmin(msg.sender), "only_admin: forbidden"); _; } constructor() public { _setAdmin(msg.sender, true); } function isAdmin(address a) view public returns (bool) { return admins[currAdminEpoch][a]; } function getAdminLogN() view external returns (uint) { return adminLog.length; } function getAdminLog(uint n) view external returns (address) { return adminLog[n]; } function upgradeMeAdmin(address newAdmin) only_admin() external { // note: already checked msg.sender has admin with `only_admin` modifier require(msg.sender != owner, "owner cannot upgrade self"); _setAdmin(msg.sender, false); _setAdmin(newAdmin, true); } function setAdmin(address a, bool _givePerms) only_admin() external { require(a != msg.sender && a != owner, "cannot change your own (or owner's) permissions"); _setAdmin(a, _givePerms); } function _setAdmin(address a, bool _givePerms) internal { admins[currAdminEpoch][a] = _givePerms; if (_givePerms) { emit AdminAdded(a); adminLog.push(a); } else { emit AdminRemoved(a); } } // safety feature if admins go bad or something function incAdminEpoch() only_owner() external { currAdminEpoch++; admins[currAdminEpoch][msg.sender] = true; emit AdminEpochInc(); } // this is internal so contracts can all it, but not exposed anywhere in this // contract. function disableAdminForever() internal { currAdminEpoch++; adminsDisabledForever = true; emit AdminDisabledForever(); } } contract EnsOwnerProxy is hasAdmins { bytes32 public ensNode; ENSIface public ens; PublicResolver public resolver; /** * @param _ensNode The node to administer * @param _ens The ENS Registrar * @param _resolver The ENS Resolver */ constructor(bytes32 _ensNode, ENSIface _ens, PublicResolver _resolver) public { ensNode = _ensNode; ens = _ens; resolver = _resolver; } function setAddr(address addr) only_admin() external { _setAddr(addr); } function _setAddr(address addr) internal { resolver.setAddr(ensNode, addr); } function returnToOwner() only_owner() external { ens.setOwner(ensNode, owner); } function fwdToENS(bytes data) only_owner() external { require(address(ens).call(data), "fwding to ens failed"); } function fwdToResolver(bytes data) only_owner() external { require(address(resolver).call(data), "fwding to resolver failed"); } } contract permissioned is owned, hasAdmins { mapping (address => bool) editAllowed; bool public adminLockdown = false; event PermissionError(address editAddr); event PermissionGranted(address editAddr); event PermissionRevoked(address editAddr); event PermissionsUpgraded(address oldSC, address newSC); event SelfUpgrade(address oldSC, address newSC); event AdminLockdown(); modifier only_editors() { require(editAllowed[msg.sender], "only_editors: forbidden"); _; } modifier no_lockdown() { require(adminLockdown == false, "no_lockdown: check failed"); _; } constructor() owned() hasAdmins() public { } function setPermissions(address e, bool _editPerms) no_lockdown() only_admin() external { editAllowed[e] = _editPerms; if (_editPerms) emit PermissionGranted(e); else emit PermissionRevoked(e); } function upgradePermissionedSC(address oldSC, address newSC) no_lockdown() only_admin() external { editAllowed[oldSC] = false; editAllowed[newSC] = true; emit PermissionsUpgraded(oldSC, newSC); } // always allow SCs to upgrade themselves, even after lockdown function upgradeMe(address newSC) only_editors() external { editAllowed[msg.sender] = false; editAllowed[newSC] = true; emit SelfUpgrade(msg.sender, newSC); } function hasPermissions(address a) public view returns (bool) { return editAllowed[a]; } function doLockdown() external only_owner() no_lockdown() { disableAdminForever(); adminLockdown = true; emit AdminLockdown(); } } contract upgradePtr { address ptr = address(0); modifier not_upgraded() { require(ptr == address(0), "upgrade pointer is non-zero"); _; } function getUpgradePointer() view external returns (address) { return ptr; } function doUpgradeInternal(address nextSC) internal { ptr = nextSC; } } interface ERC20Interface { // Get the total token supply function totalSupply() constant external returns (uint256 _totalSupply); // Get the account balance of another account with address _owner function balanceOf(address _owner) constant external returns (uint256 balance); // Send _value amount of tokens to address _to function transfer(address _to, uint256 _value) external returns (bool success); // Send _value amount of tokens from address _from to address _to function transferFrom(address _from, address _to, uint256 _value) external returns (bool success); // Allow _spender to withdraw from your account, multiple times, up to the _value amount. // If this function is called again it overwrites the current allowance with _value. // this function is required for some DEX functionality function approve(address _spender, uint256 _value) external returns (bool success); // Returns the amount which _spender is still allowed to withdraw from _owner function allowance(address _owner, address _spender) constant external returns (uint256 remaining); // Triggered when tokens are transferred. event Transfer(address indexed _from, address indexed _to, uint256 _value); // Triggered whenever approve(address _spender, uint256 _value) is called. event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract ixEvents { event PaymentMade(uint[2] valAndRemainder); event AddedBBFarm(uint8 bbFarmId); event SetBackend(bytes32 setWhat, address newSC); event DeprecatedBBFarm(uint8 bbFarmId); event CommunityBallot(bytes32 democHash, uint256 ballotId); event ManuallyAddedBallot(bytes32 democHash, uint256 ballotId, uint256 packed); // copied from BBFarm - unable to inherit from BBFarmEvents... event BallotCreatedWithID(uint ballotId); event BBFarmInit(bytes4 namespace); } contract ixBackendEvents { event NewDemoc(bytes32 democHash); event ManuallyAddedDemoc(bytes32 democHash, address erc20); event NewBallot(bytes32 indexed democHash, uint ballotN); event DemocOwnerSet(bytes32 indexed democHash, address owner); event DemocEditorSet(bytes32 indexed democHash, address editor, bool canEdit); event DemocEditorsWiped(bytes32 indexed democHash); event DemocErc20Set(bytes32 indexed democHash, address erc20); event DemocDataSet(bytes32 indexed democHash, bytes32 keyHash); event DemocCatAdded(bytes32 indexed democHash, uint catId); event DemocCatDeprecated(bytes32 indexed democHash, uint catId); event DemocCommunityBallotsEnabled(bytes32 indexed democHash, bool enabled); event DemocErc20OwnerClaimDisabled(bytes32 indexed democHash); event DemocClaimed(bytes32 indexed democHash); event EmergencyDemocOwner(bytes32 indexed democHash, address newOwner); } library SafeMath { function subToZero(uint a, uint b) internal pure returns (uint) { if (a < b) { // then (a - b) would overflow return 0; } return a - b; } } contract ixPaymentEvents { event UpgradedToPremium(bytes32 indexed democHash); event GrantedAccountTime(bytes32 indexed democHash, uint additionalSeconds, bytes32 ref); event AccountPayment(bytes32 indexed democHash, uint additionalSeconds); event SetCommunityBallotFee(uint amount); event SetBasicCentsPricePer30Days(uint amount); event SetPremiumMultiplier(uint8 multiplier); event DowngradeToBasic(bytes32 indexed democHash); event UpgradeToPremium(bytes32 indexed democHash); event SetExchangeRate(uint weiPerCent); event FreeExtension(bytes32 democHash); event SetBallotsPer30Days(uint amount); event SetFreeExtension(bytes32 democHash, bool hasFreeExt); event SetDenyPremium(bytes32 democHash, bool isPremiumDenied); event SetPayTo(address payTo); event SetMinorEditsAddr(address minorEditsAddr); event SetMinWeiForDInit(uint amount); } interface hasVersion { function getVersion() external pure returns (uint); } contract BBFarmIface is BBFarmEvents, permissioned, hasVersion, payoutAllC { /* global bbfarm getters */ function getNamespace() external view returns (bytes4); function getBBLibVersion() external view returns (uint256); function getNBallots() external view returns (uint256); /* init a ballot */ // note that the ballotId returned INCLUDES the namespace. function initBallot( bytes32 specHash , uint256 packed , IxIface ix , address bbAdmin , bytes24 extraData ) external returns (uint ballotId); /* Sponsorship of ballots */ function sponsor(uint ballotId) external payable; /* Voting functions */ function submitVote(uint ballotId, bytes32 vote, bytes extra) external; function submitProxyVote(bytes32[5] proxyReq, bytes extra) external; /* Ballot Getters */ function getDetails(uint ballotId, address voter) external view returns ( bool hasVoted , uint nVotesCast , bytes32 secKey , uint16 submissionBits , uint64 startTime , uint64 endTime , bytes32 specHash , bool deprecated , address ballotOwner , bytes16 extraData); function getVote(uint ballotId, uint voteId) external view returns (bytes32 voteData, address sender, bytes extra); function getTotalSponsorship(uint ballotId) external view returns (uint); function getSponsorsN(uint ballotId) external view returns (uint); function getSponsor(uint ballotId, uint sponsorN) external view returns (address sender, uint amount); function getCreationTs(uint ballotId) external view returns (uint); /* Admin on ballots */ function revealSeckey(uint ballotId, bytes32 sk) external; function setEndTime(uint ballotId, uint64 newEndTime) external; // note: testing only function setDeprecated(uint ballotId) external; function setBallotOwner(uint ballotId, address newOwner) external; } contract BBFarm is BBFarmIface { using BBLib for BBLib.DB; using IxLib for IxIface; // namespaces should be unique for each bbFarm bytes4 constant NAMESPACE = 0x00000001; // last 48 bits uint256 constant BALLOT_ID_MASK = 0x00000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; uint constant VERSION = 2; mapping (uint224 => BBLib.DB) dbs; // note - start at 100 to avoid any test for if 0 is a valid ballotId // also gives us some space to play with low numbers if we want. uint nBallots = 0; /* modifiers */ modifier req_namespace(uint ballotId) { // bytes4() will take the _first_ 4 bytes require(bytes4(ballotId >> 224) == NAMESPACE, "bad-namespace"); _; } /* Constructor */ constructor() payoutAllC(msg.sender) public { // this bbFarm requires v5 of BBLib (note: v4 deprecated immediately due to insecure submitProxyVote) // note: even though we can't test for this in coverage, this has stopped me deploying to kovan with the wrong version tho, so I consider it tested :) assert(BBLib.getVersion() == 6); emit BBFarmInit(NAMESPACE); } /* base SCs */ function _getPayTo() internal view returns (address) { return owner; } function getVersion() external pure returns (uint) { return VERSION; } /* global funcs */ function getNamespace() external view returns (bytes4) { return NAMESPACE; } function getBBLibVersion() external view returns (uint256) { return BBLib.getVersion(); } function getNBallots() external view returns (uint256) { return nBallots; } /* db lookup helper */ function getDb(uint ballotId) internal view returns (BBLib.DB storage) { // cut off anything above 224 bits (where the namespace goes) return dbs[uint224(ballotId)]; } /* Init ballot */ function initBallot( bytes32 specHash , uint256 packed , IxIface ix , address bbAdmin , bytes24 extraData ) only_editors() external returns (uint ballotId) { // calculate the ballotId based on the last 224 bits of the specHash. ballotId = uint224(specHash) ^ (uint256(NAMESPACE) << 224); // we need to call the init functions on our libraries getDb(ballotId).init(specHash, packed, ix, bbAdmin, bytes16(uint128(extraData))); nBallots += 1; emit BallotCreatedWithID(ballotId); } /* Sponsorship */ function sponsor(uint ballotId) external payable { BBLib.DB storage db = getDb(ballotId); db.logSponsorship(msg.value); doSafeSend(db.index.getPayTo(), msg.value); emit Sponsorship(ballotId, msg.value); } /* Voting */ function submitVote(uint ballotId, bytes32 vote, bytes extra) req_namespace(ballotId) external { getDb(ballotId).submitVote(vote, extra); emit Vote(ballotId, vote, msg.sender, extra); } function submitProxyVote(bytes32[5] proxyReq, bytes extra) req_namespace(uint256(proxyReq[3])) external { // see https://github.com/secure-vote/tokenvote/blob/master/Docs/DataStructs.md for breakdown of params // pr[3] is the ballotId, and pr[4] is the vote uint ballotId = uint256(proxyReq[3]); address voter = getDb(ballotId).submitProxyVote(proxyReq, extra); bytes32 vote = proxyReq[4]; emit Vote(ballotId, vote, voter, extra); } /* Getters */ // note - this is the maxmimum number of vars we can return with one // function call (taking 2 args) function getDetails(uint ballotId, address voter) external view returns ( bool hasVoted , uint nVotesCast , bytes32 secKey , uint16 submissionBits , uint64 startTime , uint64 endTime , bytes32 specHash , bool deprecated , address ballotOwner , bytes16 extraData) { BBLib.DB storage db = getDb(ballotId); uint packed = db.packed; return ( db.getSequenceNumber(voter) > 0, db.nVotesCast, db.ballotEncryptionSeckey, BPackedUtils.packedToSubmissionBits(packed), BPackedUtils.packedToStartTime(packed), BPackedUtils.packedToEndTime(packed), db.specHash, db.deprecated, db.ballotOwner, db.extraData ); } function getVote(uint ballotId, uint voteId) external view returns (bytes32 voteData, address sender, bytes extra) { (voteData, sender, extra, ) = getDb(ballotId).getVote(voteId); } function getSequenceNumber(uint ballotId, address voter) external view returns (uint32 sequence) { return getDb(ballotId).getSequenceNumber(voter); } function getTotalSponsorship(uint ballotId) external view returns (uint) { return getDb(ballotId).getTotalSponsorship(); } function getSponsorsN(uint ballotId) external view returns (uint) { return getDb(ballotId).sponsors.length; } function getSponsor(uint ballotId, uint sponsorN) external view returns (address sender, uint amount) { return getDb(ballotId).getSponsor(sponsorN); } function getCreationTs(uint ballotId) external view returns (uint) { return getDb(ballotId).creationTs; } /* ADMIN */ // Allow the owner to reveal the secret key after ballot conclusion function revealSeckey(uint ballotId, bytes32 sk) external { BBLib.DB storage db = getDb(ballotId); db.requireBallotOwner(); db.requireBallotClosed(); db.revealSeckey(sk); } // note: testing only. function setEndTime(uint ballotId, uint64 newEndTime) external { BBLib.DB storage db = getDb(ballotId); db.requireBallotOwner(); db.requireTesting(); db.setEndTime(newEndTime); } function setDeprecated(uint ballotId) external { BBLib.DB storage db = getDb(ballotId); db.requireBallotOwner(); db.deprecated = true; } function setBallotOwner(uint ballotId, address newOwner) external { BBLib.DB storage db = getDb(ballotId); db.requireBallotOwner(); db.ballotOwner = newOwner; } } contract IxIface is hasVersion, ixPaymentEvents, ixBackendEvents, ixEvents, SVBallotConsts, owned, CanReclaimToken, upgradePtr, payoutAllC { /* owner functions */ function addBBFarm(BBFarmIface bbFarm) external returns (uint8 bbFarmId); function setABackend(bytes32 toSet, address newSC) external; function deprecateBBFarm(uint8 bbFarmId, BBFarmIface _bbFarm) external; /* global getters */ function getPayments() external view returns (IxPaymentsIface); function getBackend() external view returns (IxBackendIface); function getBBFarm(uint8 bbFarmId) external view returns (BBFarmIface); function getBBFarmID(bytes4 bbNamespace) external view returns (uint8 bbFarmId); function getCommAuction() external view returns (CommAuctionIface); /* init a democ */ function dInit(address defualtErc20, bool disableErc20OwnerClaim) external payable returns (bytes32); /* democ owner / editor functions */ function setDEditor(bytes32 democHash, address editor, bool canEdit) external; function setDNoEditors(bytes32 democHash) external; function setDOwner(bytes32 democHash, address newOwner) external; function dOwnerErc20Claim(bytes32 democHash) external; function setDErc20(bytes32 democHash, address newErc20) external; function dAddCategory(bytes32 democHash, bytes32 categoryName, bool hasParent, uint parent) external; function dDeprecateCategory(bytes32 democHash, uint categoryId) external; function dUpgradeToPremium(bytes32 democHash) external; function dDowngradeToBasic(bytes32 democHash) external; function dSetArbitraryData(bytes32 democHash, bytes key, bytes value) external; function dSetCommunityBallotsEnabled(bytes32 democHash, bool enabled) external; function dDisableErc20OwnerClaim(bytes32 democHash) external; /* democ getters (that used to be here) should be called on either backend or payments directly */ /* use IxLib for convenience functions from other SCs */ /* ballot deployment */ // only ix owner - used for adding past or special ballots function dAddBallot(bytes32 democHash, uint ballotId, uint256 packed) external; function dDeployCommunityBallot(bytes32 democHash, bytes32 specHash, bytes32 extraData, uint128 packedTimes) external payable; function dDeployBallot(bytes32 democHash, bytes32 specHash, bytes32 extraData, uint256 packed) external payable; } contract SVIndex is IxIface { uint256 constant VERSION = 2; // generated from: `address public owner;` bytes4 constant OWNER_SIG = 0x8da5cb5b; // generated from: `address public controller;` bytes4 constant CONTROLLER_SIG = 0xf77c4791; /* backend & other SC storage */ IxBackendIface backend; IxPaymentsIface payments; EnsOwnerProxy public ensOwnerPx; BBFarmIface[] bbFarms; CommAuctionIface commAuction; // mapping from bbFarm namespace to bbFarmId mapping (bytes4 => uint8) bbFarmIdLookup; mapping (uint8 => bool) deprecatedBBFarms; //* MODIFIERS / modifier onlyDemocOwner(bytes32 democHash) { require(msg.sender == backend.getDOwner(democHash), "!d-owner"); _; } modifier onlyDemocEditor(bytes32 democHash) { require(backend.isDEditor(democHash, msg.sender), "!d-editor"); _; } /* FUNCTIONS */ // constructor constructor( IxBackendIface _b , IxPaymentsIface _pay , EnsOwnerProxy _ensOwnerPx , BBFarmIface _bbFarm0 , CommAuctionIface _commAuction ) payoutAllC(msg.sender) public { backend = _b; payments = _pay; ensOwnerPx = _ensOwnerPx; _addBBFarm(0x0, _bbFarm0); commAuction = _commAuction; } /* payoutAllC */ function _getPayTo() internal view returns (address) { return payments.getPayTo(); } /* UPGRADE STUFF */ function doUpgrade(address nextSC) only_owner() not_upgraded() external { doUpgradeInternal(nextSC); backend.upgradeMe(nextSC); payments.upgradeMe(nextSC); ensOwnerPx.setAddr(nextSC); ensOwnerPx.upgradeMeAdmin(nextSC); commAuction.upgradeMe(nextSC); for (uint i = 0; i < bbFarms.length; i++) { bbFarms[i].upgradeMe(nextSC); } } function _addBBFarm(bytes4 bbNamespace, BBFarmIface _bbFarm) internal returns (uint8 bbFarmId) { uint256 bbFarmIdLong = bbFarms.length; require(bbFarmIdLong < 2**8, "too-many-farms"); bbFarmId = uint8(bbFarmIdLong); bbFarms.push(_bbFarm); bbFarmIdLookup[bbNamespace] = bbFarmId; emit AddedBBFarm(bbFarmId); } // adding a new BBFarm function addBBFarm(BBFarmIface bbFarm) only_owner() external returns (uint8 bbFarmId) { bytes4 bbNamespace = bbFarm.getNamespace(); require(bbNamespace != bytes4(0), "bb-farm-namespace"); require(bbFarmIdLookup[bbNamespace] == 0 && bbNamespace != bbFarms[0].getNamespace(), "bb-namespace-used"); bbFarmId = _addBBFarm(bbNamespace, bbFarm); } function setABackend(bytes32 toSet, address newSC) only_owner() external { emit SetBackend(toSet, newSC); if (toSet == bytes32("payments")) { payments = IxPaymentsIface(newSC); } else if (toSet == bytes32("backend")) { backend = IxBackendIface(newSC); } else if (toSet == bytes32("commAuction")) { commAuction = CommAuctionIface(newSC); } else { revert("404"); } } function deprecateBBFarm(uint8 bbFarmId, BBFarmIface _bbFarm) only_owner() external { require(address(_bbFarm) != address(0)); require(bbFarms[bbFarmId] == _bbFarm); deprecatedBBFarms[bbFarmId] = true; emit DeprecatedBBFarm(bbFarmId); } /* Getters for backends */ function getPayments() external view returns (IxPaymentsIface) { return payments; } function getBackend() external view returns (IxBackendIface) { return backend; } function getBBFarm(uint8 bbFarmId) external view returns (BBFarmIface) { return bbFarms[bbFarmId]; } function getBBFarmID(bytes4 bbNamespace) external view returns (uint8 bbFarmId) { return bbFarmIdLookup[bbNamespace]; } function getCommAuction() external view returns (CommAuctionIface) { return commAuction; } //* GLOBAL INFO */ function getVersion() external pure returns (uint256) { return VERSION; } //* DEMOCRACY FUNCTIONS - INDIVIDUAL */ function dInit(address defaultErc20, bool disableErc20OwnerClaim) not_upgraded() external payable returns (bytes32) { require(msg.value >= payments.getMinWeiForDInit()); bytes32 democHash = backend.dInit(defaultErc20, msg.sender, disableErc20OwnerClaim); payments.payForDemocracy.value(msg.value)(democHash); return democHash; } // admin methods function setDEditor(bytes32 democHash, address editor, bool canEdit) onlyDemocOwner(democHash) external { backend.setDEditor(democHash, editor, canEdit); } function setDNoEditors(bytes32 democHash) onlyDemocOwner(democHash) external { backend.setDNoEditors(democHash); } function setDOwner(bytes32 democHash, address newOwner) onlyDemocOwner(democHash) external { backend.setDOwner(democHash, newOwner); } function dOwnerErc20Claim(bytes32 democHash) external { address erc20 = backend.getDErc20(democHash); // test if we can call the erc20.owner() method, etc // also limit gas use to 3000 because we don't know what they'll do with it // during testing both owned and controlled could be called from other contracts for 2525 gas. if (erc20.call.gas(3000)(OWNER_SIG)) { require(msg.sender == owned(erc20).owner.gas(3000)(), "!erc20-owner"); } else if (erc20.call.gas(3000)(CONTROLLER_SIG)) { require(msg.sender == controlledIface(erc20).controller.gas(3000)(), "!erc20-controller"); } else { revert(); } // now we are certain the sender deployed or controls the erc20 backend.setDOwnerFromClaim(democHash, msg.sender); } function setDErc20(bytes32 democHash, address newErc20) onlyDemocOwner(democHash) external { backend.setDErc20(democHash, newErc20); } function dAddCategory(bytes32 democHash, bytes32 catName, bool hasParent, uint parent) onlyDemocEditor(democHash) external { backend.dAddCategory(democHash, catName, hasParent, parent); } function dDeprecateCategory(bytes32 democHash, uint catId) onlyDemocEditor(democHash) external { backend.dDeprecateCategory(democHash, catId); } function dUpgradeToPremium(bytes32 democHash) onlyDemocOwner(democHash) external { payments.upgradeToPremium(democHash); } function dDowngradeToBasic(bytes32 democHash) onlyDemocOwner(democHash) external { payments.downgradeToBasic(democHash); } function dSetArbitraryData(bytes32 democHash, bytes key, bytes value) external { if (msg.sender == backend.getDOwner(democHash)) { backend.dSetArbitraryData(democHash, key, value); } else if (backend.isDEditor(democHash, msg.sender)) { backend.dSetEditorArbitraryData(democHash, key, value); } else { revert(); } } function dSetCommunityBallotsEnabled(bytes32 democHash, bool enabled) onlyDemocOwner(democHash) external { backend.dSetCommunityBallotsEnabled(democHash, enabled); } // this is one way only! function dDisableErc20OwnerClaim(bytes32 democHash) onlyDemocOwner(democHash) external { backend.dDisableErc20OwnerClaim(democHash); } /* Democ Getters - deprecated */ // NOTE: the getters that used to live here just proxied to the backend. // this has been removed to reduce gas costs + size of Ix contract // For SCs you should use IxLib for convenience. // For Offchain use you should query the backend directly (via ix.getBackend()) /* Add and Deploy Ballots */ // manually add a ballot - only the owner can call this // WARNING - it's required that we make ABSOLUTELY SURE that // ballotId is valid and can resolve via the appropriate BBFarm. // this function _DOES NOT_ validate that everything else is done. function dAddBallot(bytes32 democHash, uint ballotId, uint256 packed) only_owner() external { _addBallot(democHash, ballotId, packed, false); emit ManuallyAddedBallot(democHash, ballotId, packed); } function _deployBallot(bytes32 democHash, bytes32 specHash, bytes32 extraData, uint packed, bool checkLimit, bool alreadySentTx) internal returns (uint ballotId) { require(BBLib.isTesting(BPackedUtils.packedToSubmissionBits(packed)) == false, "b-testing"); // the most significant byte of extraData signals the bbFarm to use. uint8 bbFarmId = uint8(extraData[0]); require(deprecatedBBFarms[bbFarmId] == false, "bb-dep"); BBFarmIface _bbFarm = bbFarms[bbFarmId]; // anything that isn't a community ballot counts towards the basic limit. // we want to check in cases where // the ballot doesn't qualify as a community ballot // OR (the ballot qualifies as a community ballot // AND the admins have _disabled_ community ballots). bool countTowardsLimit = checkLimit; bool performedSend; if (checkLimit) { uint64 endTime = BPackedUtils.packedToEndTime(packed); (countTowardsLimit, performedSend) = _basicBallotLimitOperations(democHash, _bbFarm); _accountOkayChecks(democHash, endTime); } if (!performedSend && msg.value > 0 && alreadySentTx == false) { // refund if we haven't send value anywhere (which might happen if someone accidentally pays us) doSafeSend(msg.sender, msg.value); } ballotId = _bbFarm.initBallot( specHash, packed, this, msg.sender, // we are certain that the first 8 bytes are for index use only. // truncating extraData like this means we can occasionally // save on gas. we need to use uint192 first because that will take // the _last_ 24 bytes of extraData. bytes24(uint192(extraData))); _addBallot(democHash, ballotId, packed, countTowardsLimit); } function dDeployCommunityBallot(bytes32 democHash, bytes32 specHash, bytes32 extraData, uint128 packedTimes) external payable { uint price = commAuction.getNextPrice(democHash); require(msg.value >= price, "!cb-fee"); doSafeSend(payments.getPayTo(), price); doSafeSend(msg.sender, msg.value - price); bool canProceed = backend.getDCommBallotsEnabled(democHash) || !payments.accountInGoodStanding(democHash); require(canProceed, "!cb-enabled"); uint256 packed = BPackedUtils.setSB(uint256(packedTimes), (USE_ETH | USE_NO_ENC)); uint ballotId = _deployBallot(democHash, specHash, extraData, packed, false, true); commAuction.noteBallotDeployed(democHash); emit CommunityBallot(democHash, ballotId); } // only way a democ admin can deploy a ballot function dDeployBallot(bytes32 democHash, bytes32 specHash, bytes32 extraData, uint256 packed) onlyDemocEditor(democHash) external payable { _deployBallot(democHash, specHash, extraData, packed, true, false); } // internal logic around adding a ballot function _addBallot(bytes32 democHash, uint256 ballotId, uint256 packed, bool countTowardsLimit) internal { // backend handles events backend.dAddBallot(democHash, ballotId, packed, countTowardsLimit); } // check an account has paid up enough for this ballot function _accountOkayChecks(bytes32 democHash, uint64 endTime) internal view { // if the ballot is marked as official require the democracy is paid up to // some relative amount - exclude NFP accounts from this check uint secsLeft = payments.getSecondsRemaining(democHash); // must be positive due to ending in future check uint256 secsToEndTime = endTime - now; // require ballots end no more than twice the time left on the democracy require(secsLeft * 2 > secsToEndTime, "unpaid"); } function _basicBallotLimitOperations(bytes32 democHash, BBFarmIface _bbFarm) internal returns (bool shouldCount, bool performedSend) { // if we're an official ballot and the democ is basic, ensure the democ // isn't over the ballots/mo limit if (payments.getPremiumStatus(democHash) == false) { uint nBallotsAllowed = payments.getBasicBallotsPer30Days(); uint nBallotsBasicCounted = backend.getDCountedBasicBallotsN(democHash); // if the democ has less than nBallotsAllowed then it's guarenteed to be okay if (nBallotsAllowed > nBallotsBasicCounted) { // and we should count this ballot return (true, false); } // we want to check the creation timestamp of the nth most recent ballot // where n is the # of ballots allowed per month. Note: there isn't an off // by 1 error here because if 1 ballots were allowed per month then we'd want // to look at the most recent ballot, so nBallotsBasicCounted-1 in this case. // similarly, if X ballots were allowed per month we want to look at // nBallotsBasicCounted-X. There would thus be (X-1) ballots that are _more_ // recent than the one we're looking for. uint earlyBallotId = backend.getDCountedBasicBallotID(democHash, nBallotsBasicCounted - nBallotsAllowed); uint earlyBallotTs = _bbFarm.getCreationTs(earlyBallotId); // if the earlyBallot was created more than 30 days in the past we should // count the new ballot if (earlyBallotTs < now - 30 days) { return (true, false); } // at this point it may be the case that we shouldn't allow the ballot // to be created. (It's an official ballot for a basic tier democracy // where the Nth most recent ballot was created within the last 30 days.) // We should now check for payment uint extraBallotFee = payments.getBasicExtraBallotFeeWei(); require(msg.value >= extraBallotFee, "!extra-b-fee"); // now that we know they've paid the fee, we should send Eth to `payTo` // and return the remainder. uint remainder = msg.value - extraBallotFee; doSafeSend(address(payments), extraBallotFee); doSafeSend(msg.sender, remainder); emit PaymentMade([extraBallotFee, remainder]); // only in this case (for basic) do we want to return false - don't count towards the // limit because it's been paid for here. return (false, true); } else { // if we're premium we don't count ballots return (false, false); } } } contract IxBackendIface is hasVersion, ixBackendEvents, permissioned, payoutAllC { /* global getters */ function getGDemocsN() external view returns (uint); function getGDemoc(uint id) external view returns (bytes32); function getGErc20ToDemocs(address erc20) external view returns (bytes32[] democHashes); /* owner functions */ function dAdd(bytes32 democHash, address erc20, bool disableErc20OwnerClaim) external; function emergencySetDOwner(bytes32 democHash, address newOwner) external; /* democ admin */ function dInit(address defaultErc20, address initOwner, bool disableErc20OwnerClaim) external returns (bytes32 democHash); function setDOwner(bytes32 democHash, address newOwner) external; function setDOwnerFromClaim(bytes32 democHash, address newOwner) external; function setDEditor(bytes32 democHash, address editor, bool canEdit) external; function setDNoEditors(bytes32 democHash) external; function setDErc20(bytes32 democHash, address newErc20) external; function dSetArbitraryData(bytes32 democHash, bytes key, bytes value) external; function dSetEditorArbitraryData(bytes32 democHash, bytes key, bytes value) external; function dAddCategory(bytes32 democHash, bytes32 categoryName, bool hasParent, uint parent) external; function dDeprecateCategory(bytes32 democHash, uint catId) external; function dSetCommunityBallotsEnabled(bytes32 democHash, bool enabled) external; function dDisableErc20OwnerClaim(bytes32 democHash) external; /* actually add a ballot */ function dAddBallot(bytes32 democHash, uint ballotId, uint256 packed, bool countTowardsLimit) external; /* global democ getters */ function getDOwner(bytes32 democHash) external view returns (address); function isDEditor(bytes32 democHash, address editor) external view returns (bool); function getDHash(bytes13 prefix) external view returns (bytes32); function getDInfo(bytes32 democHash) external view returns (address erc20, address owner, uint256 nBallots); function getDErc20(bytes32 democHash) external view returns (address); function getDArbitraryData(bytes32 democHash, bytes key) external view returns (bytes value); function getDEditorArbitraryData(bytes32 democHash, bytes key) external view returns (bytes value); function getDBallotsN(bytes32 democHash) external view returns (uint256); function getDBallotID(bytes32 democHash, uint n) external view returns (uint ballotId); function getDCountedBasicBallotsN(bytes32 democHash) external view returns (uint256); function getDCountedBasicBallotID(bytes32 democHash, uint256 n) external view returns (uint256); function getDCategoriesN(bytes32 democHash) external view returns (uint); function getDCategory(bytes32 democHash, uint catId) external view returns (bool deprecated, bytes32 name, bool hasParent, uint parent); function getDCommBallotsEnabled(bytes32 democHash) external view returns (bool); function getDErc20OwnerClaimEnabled(bytes32 democHash) external view returns (bool); } contract SVIndexBackend is IxBackendIface { uint constant VERSION = 2; struct Democ { address erc20; address owner; bool communityBallotsDisabled; bool erc20OwnerClaimDisabled; uint editorEpoch; mapping (uint => mapping (address => bool)) editors; uint256[] allBallots; uint256[] includedBasicBallots; // the IDs of official ballots } struct BallotRef { bytes32 democHash; uint ballotId; } struct Category { bool deprecated; bytes32 name; bool hasParent; uint parent; } struct CategoriesIx { uint nCategories; mapping(uint => Category) categories; } mapping (bytes32 => Democ) democs; mapping (bytes32 => CategoriesIx) democCategories; mapping (bytes13 => bytes32) democPrefixToHash; mapping (address => bytes32[]) erc20ToDemocs; bytes32[] democList; // allows democ admins to store arbitrary data // this lets us (for example) set particular keys to signal cerain // things to client apps s.t. the admin can turn them on and off. // arbitraryData[democHash][key] mapping (bytes32 => mapping (bytes32 => bytes)) arbitraryData; /* constructor */ constructor() payoutAllC(msg.sender) public { // do nothing } /* base contract overloads */ function _getPayTo() internal view returns (address) { return owner; } function getVersion() external pure returns (uint) { return VERSION; } /* GLOBAL INFO */ function getGDemocsN() external view returns (uint) { return democList.length; } function getGDemoc(uint id) external view returns (bytes32) { return democList[id]; } function getGErc20ToDemocs(address erc20) external view returns (bytes32[] democHashes) { return erc20ToDemocs[erc20]; } /* DEMOCRACY ADMIN FUNCTIONS */ function _addDemoc(bytes32 democHash, address erc20, address initOwner, bool disableErc20OwnerClaim) internal { democList.push(democHash); Democ storage d = democs[democHash]; d.erc20 = erc20; if (disableErc20OwnerClaim) { d.erc20OwnerClaimDisabled = true; } // this should never trigger if we have a good security model - entropy for 13 bytes ~ 2^(8*13) ~ 10^31 assert(democPrefixToHash[bytes13(democHash)] == bytes32(0)); democPrefixToHash[bytes13(democHash)] = democHash; erc20ToDemocs[erc20].push(democHash); _setDOwner(democHash, initOwner); emit NewDemoc(democHash); } /* owner democ admin functions */ function dAdd(bytes32 democHash, address erc20, bool disableErc20OwnerClaim) only_owner() external { _addDemoc(democHash, erc20, msg.sender, disableErc20OwnerClaim); emit ManuallyAddedDemoc(democHash, erc20); } /* Preferably for emergencies only */ function emergencySetDOwner(bytes32 democHash, address newOwner) only_owner() external { _setDOwner(democHash, newOwner); emit EmergencyDemocOwner(democHash, newOwner); } /* user democ admin functions */ function dInit(address defaultErc20, address initOwner, bool disableErc20OwnerClaim) only_editors() external returns (bytes32 democHash) { // generating the democHash in this way guarentees it'll be unique/hard-to-brute-force // (particularly because prevBlockHash and now are part of the hash) democHash = keccak256(abi.encodePacked(democList.length, blockhash(block.number-1), defaultErc20, now)); _addDemoc(democHash, defaultErc20, initOwner, disableErc20OwnerClaim); } function _setDOwner(bytes32 democHash, address newOwner) internal { Democ storage d = democs[democHash]; uint epoch = d.editorEpoch; d.owner = newOwner; // unset prev owner as editor - does little if one was not set d.editors[epoch][d.owner] = false; // make new owner an editor too d.editors[epoch][newOwner] = true; emit DemocOwnerSet(democHash, newOwner); } function setDOwner(bytes32 democHash, address newOwner) only_editors() external { _setDOwner(democHash, newOwner); } function setDOwnerFromClaim(bytes32 democHash, address newOwner) only_editors() external { Democ storage d = democs[democHash]; // make sure that the owner claim is enabled (i.e. the disabled flag is false) require(d.erc20OwnerClaimDisabled == false, "!erc20-claim"); // set owner and editor d.owner = newOwner; d.editors[d.editorEpoch][newOwner] = true; // disable the ability to claim now that it's done d.erc20OwnerClaimDisabled = true; emit DemocOwnerSet(democHash, newOwner); emit DemocClaimed(democHash); } function setDEditor(bytes32 democHash, address editor, bool canEdit) only_editors() external { Democ storage d = democs[democHash]; d.editors[d.editorEpoch][editor] = canEdit; emit DemocEditorSet(democHash, editor, canEdit); } function setDNoEditors(bytes32 democHash) only_editors() external { democs[democHash].editorEpoch += 1; emit DemocEditorsWiped(democHash); } function setDErc20(bytes32 democHash, address newErc20) only_editors() external { democs[democHash].erc20 = newErc20; erc20ToDemocs[newErc20].push(democHash); emit DemocErc20Set(democHash, newErc20); } function dSetArbitraryData(bytes32 democHash, bytes key, bytes value) only_editors() external { bytes32 k = keccak256(key); arbitraryData[democHash][k] = value; emit DemocDataSet(democHash, k); } function dSetEditorArbitraryData(bytes32 democHash, bytes key, bytes value) only_editors() external { bytes32 k = keccak256(_calcEditorKey(key)); arbitraryData[democHash][k] = value; emit DemocDataSet(democHash, k); } function dAddCategory(bytes32 democHash, bytes32 name, bool hasParent, uint parent) only_editors() external { uint catId = democCategories[democHash].nCategories; democCategories[democHash].categories[catId].name = name; if (hasParent) { democCategories[democHash].categories[catId].hasParent = true; democCategories[democHash].categories[catId].parent = parent; } democCategories[democHash].nCategories += 1; emit DemocCatAdded(democHash, catId); } function dDeprecateCategory(bytes32 democHash, uint catId) only_editors() external { democCategories[democHash].categories[catId].deprecated = true; emit DemocCatDeprecated(democHash, catId); } function dSetCommunityBallotsEnabled(bytes32 democHash, bool enabled) only_editors() external { democs[democHash].communityBallotsDisabled = !enabled; emit DemocCommunityBallotsEnabled(democHash, enabled); } function dDisableErc20OwnerClaim(bytes32 democHash) only_editors() external { democs[democHash].erc20OwnerClaimDisabled = true; emit DemocErc20OwnerClaimDisabled(democHash); } //* ADD BALLOT TO RECORD */ function _commitBallot(bytes32 democHash, uint ballotId, uint256 packed, bool countTowardsLimit) internal { uint16 subBits; subBits = BPackedUtils.packedToSubmissionBits(packed); uint localBallotId = democs[democHash].allBallots.length; democs[democHash].allBallots.push(ballotId); // do this for anything that doesn't qualify as a community ballot if (countTowardsLimit) { democs[democHash].includedBasicBallots.push(ballotId); } emit NewBallot(democHash, localBallotId); } // what SVIndex uses to add a ballot function dAddBallot(bytes32 democHash, uint ballotId, uint256 packed, bool countTowardsLimit) only_editors() external { _commitBallot(democHash, ballotId, packed, countTowardsLimit); } /* democ getters */ function getDOwner(bytes32 democHash) external view returns (address) { return democs[democHash].owner; } function isDEditor(bytes32 democHash, address editor) external view returns (bool) { Democ storage d = democs[democHash]; // allow either an editor or always the owner return d.editors[d.editorEpoch][editor] || editor == d.owner; } function getDHash(bytes13 prefix) external view returns (bytes32) { return democPrefixToHash[prefix]; } function getDInfo(bytes32 democHash) external view returns (address erc20, address owner, uint256 nBallots) { return (democs[democHash].erc20, democs[democHash].owner, democs[democHash].allBallots.length); } function getDErc20(bytes32 democHash) external view returns (address) { return democs[democHash].erc20; } function getDArbitraryData(bytes32 democHash, bytes key) external view returns (bytes) { return arbitraryData[democHash][keccak256(key)]; } function getDEditorArbitraryData(bytes32 democHash, bytes key) external view returns (bytes) { return arbitraryData[democHash][keccak256(_calcEditorKey(key))]; } function getDBallotsN(bytes32 democHash) external view returns (uint256) { return democs[democHash].allBallots.length; } function getDBallotID(bytes32 democHash, uint256 n) external view returns (uint ballotId) { return democs[democHash].allBallots[n]; } function getDCountedBasicBallotsN(bytes32 democHash) external view returns (uint256) { return democs[democHash].includedBasicBallots.length; } function getDCountedBasicBallotID(bytes32 democHash, uint256 n) external view returns (uint256) { return democs[democHash].includedBasicBallots[n]; } function getDCategoriesN(bytes32 democHash) external view returns (uint) { return democCategories[democHash].nCategories; } function getDCategory(bytes32 democHash, uint catId) external view returns (bool deprecated, bytes32 name, bool hasParent, uint256 parent) { deprecated = democCategories[democHash].categories[catId].deprecated; name = democCategories[democHash].categories[catId].name; hasParent = democCategories[democHash].categories[catId].hasParent; parent = democCategories[democHash].categories[catId].parent; } function getDCommBallotsEnabled(bytes32 democHash) external view returns (bool) { return !democs[democHash].communityBallotsDisabled; } function getDErc20OwnerClaimEnabled(bytes32 democHash) external view returns (bool) { return !democs[democHash].erc20OwnerClaimDisabled; } /* util for calculating editor key */ function _calcEditorKey(bytes key) internal pure returns (bytes) { return abi.encodePacked("editor.", key); } } contract IxPaymentsIface is hasVersion, ixPaymentEvents, permissioned, CanReclaimToken, payoutAllCSettable { /* in emergency break glass */ function emergencySetOwner(address newOwner) external; /* financial calcluations */ function weiBuysHowManySeconds(uint amount) public view returns (uint secs); function weiToCents(uint w) public view returns (uint); function centsToWei(uint c) public view returns (uint); /* account management */ function payForDemocracy(bytes32 democHash) external payable; function doFreeExtension(bytes32 democHash) external; function downgradeToBasic(bytes32 democHash) external; function upgradeToPremium(bytes32 democHash) external; /* account status - getters */ function accountInGoodStanding(bytes32 democHash) external view returns (bool); function getSecondsRemaining(bytes32 democHash) external view returns (uint); function getPremiumStatus(bytes32 democHash) external view returns (bool); function getFreeExtension(bytes32 democHash) external view returns (bool); function getAccount(bytes32 democHash) external view returns (bool isPremium, uint lastPaymentTs, uint paidUpTill, bool hasFreeExtension); function getDenyPremium(bytes32 democHash) external view returns (bool); /* admin utils for accounts */ function giveTimeToDemoc(bytes32 democHash, uint additionalSeconds, bytes32 ref) external; /* admin setters global */ function setPayTo(address) external; function setMinorEditsAddr(address) external; function setBasicCentsPricePer30Days(uint amount) external; function setBasicBallotsPer30Days(uint amount) external; function setPremiumMultiplier(uint8 amount) external; function setWeiPerCent(uint) external; function setFreeExtension(bytes32 democHash, bool hasFreeExt) external; function setDenyPremium(bytes32 democHash, bool isPremiumDenied) external; function setMinWeiForDInit(uint amount) external; /* global getters */ function getBasicCentsPricePer30Days() external view returns(uint); function getBasicExtraBallotFeeWei() external view returns (uint); function getBasicBallotsPer30Days() external view returns (uint); function getPremiumMultiplier() external view returns (uint8); function getPremiumCentsPricePer30Days() external view returns (uint); function getWeiPerCent() external view returns (uint weiPerCent); function getUsdEthExchangeRate() external view returns (uint centsPerEth); function getMinWeiForDInit() external view returns (uint); /* payments stuff */ function getPaymentLogN() external view returns (uint); function getPaymentLog(uint n) external view returns (bool _external, bytes32 _democHash, uint _seconds, uint _ethValue); } contract SVPayments is IxPaymentsIface { uint constant VERSION = 2; struct Account { bool isPremium; uint lastPaymentTs; uint paidUpTill; uint lastUpgradeTs; // timestamp of the last time it was upgraded to premium } struct PaymentLog { bool _external; bytes32 _democHash; uint _seconds; uint _ethValue; } // this is an address that's only allowed to make minor edits // e.g. setExchangeRate, setDenyPremium, giveTimeToDemoc address public minorEditsAddr; // payment details uint basicCentsPricePer30Days = 125000; // $1250/mo uint basicBallotsPer30Days = 10; uint8 premiumMultiplier = 5; uint weiPerCent = 0.000016583747 ether; // $603, 4th June 2018 uint minWeiForDInit = 1; // minimum 1 wei - match existing behaviour in SVIndex mapping (bytes32 => Account) accounts; PaymentLog[] payments; // can set this on freeExtension democs to deny them premium upgrades mapping (bytes32 => bool) denyPremium; // this is used for non-profits or organisations that have perpetual licenses, etc mapping (bytes32 => bool) freeExtension; /* BREAK GLASS IN CASE OF EMERGENCY */ // this is included here because something going wrong with payments is possibly // the absolute worst case. Note: does this have negligable benefit if the other // contracts are compromised? (e.g. by a leaked privkey) address public emergencyAdmin; function emergencySetOwner(address newOwner) external { require(msg.sender == emergencyAdmin, "!emergency-owner"); owner = newOwner; } /* END BREAK GLASS */ constructor(address _emergencyAdmin) payoutAllCSettable(msg.sender) public { emergencyAdmin = _emergencyAdmin; assert(_emergencyAdmin != address(0)); } /* base SCs */ function getVersion() external pure returns (uint) { return VERSION; } function() payable public { _getPayTo().transfer(msg.value); } function _modAccountBalance(bytes32 democHash, uint additionalSeconds) internal { uint prevPaidTill = accounts[democHash].paidUpTill; if (prevPaidTill < now) { prevPaidTill = now; } accounts[democHash].paidUpTill = prevPaidTill + additionalSeconds; accounts[democHash].lastPaymentTs = now; } /* Financial Calculations */ function weiBuysHowManySeconds(uint amount) public view returns (uint) { uint centsPaid = weiToCents(amount); // multiply by 10**18 to ensure we make rounding errors insignificant uint monthsOffsetPaid = ((10 ** 18) * centsPaid) / basicCentsPricePer30Days; uint secondsOffsetPaid = monthsOffsetPaid * (30 days); uint additionalSeconds = secondsOffsetPaid / (10 ** 18); return additionalSeconds; } function weiToCents(uint w) public view returns (uint) { return w / weiPerCent; } function centsToWei(uint c) public view returns (uint) { return c * weiPerCent; } /* account management */ function payForDemocracy(bytes32 democHash) external payable { require(msg.value > 0, "need to send some ether to make payment"); uint additionalSeconds = weiBuysHowManySeconds(msg.value); if (accounts[democHash].isPremium) { additionalSeconds /= premiumMultiplier; } if (additionalSeconds >= 1) { _modAccountBalance(democHash, additionalSeconds); } payments.push(PaymentLog(false, democHash, additionalSeconds, msg.value)); emit AccountPayment(democHash, additionalSeconds); _getPayTo().transfer(msg.value); } function doFreeExtension(bytes32 democHash) external { require(freeExtension[democHash], "!free"); uint newPaidUpTill = now + 60 days; accounts[democHash].paidUpTill = newPaidUpTill; emit FreeExtension(democHash); } function downgradeToBasic(bytes32 democHash) only_editors() external { require(accounts[democHash].isPremium, "!premium"); accounts[democHash].isPremium = false; // convert premium minutes to basic uint paidTill = accounts[democHash].paidUpTill; uint timeRemaining = SafeMath.subToZero(paidTill, now); // if we have time remaining: convert it if (timeRemaining > 0) { // prevent accounts from downgrading if they have time remaining // and upgraded less than 24hrs ago require(accounts[democHash].lastUpgradeTs < (now - 24 hours), "downgrade-too-soon"); timeRemaining *= premiumMultiplier; accounts[democHash].paidUpTill = now + timeRemaining; } emit DowngradeToBasic(democHash); } function upgradeToPremium(bytes32 democHash) only_editors() external { require(denyPremium[democHash] == false, "upgrade-denied"); require(!accounts[democHash].isPremium, "!basic"); accounts[democHash].isPremium = true; // convert basic minutes to premium minutes uint paidTill = accounts[democHash].paidUpTill; uint timeRemaining = SafeMath.subToZero(paidTill, now); // if we have time remaning then convert it - otherwise don't need to do anything if (timeRemaining > 0) { timeRemaining /= premiumMultiplier; accounts[democHash].paidUpTill = now + timeRemaining; } accounts[democHash].lastUpgradeTs = now; emit UpgradedToPremium(democHash); } /* account status - getters */ function accountInGoodStanding(bytes32 democHash) external view returns (bool) { return accounts[democHash].paidUpTill >= now; } function getSecondsRemaining(bytes32 democHash) external view returns (uint) { return SafeMath.subToZero(accounts[democHash].paidUpTill, now); } function getPremiumStatus(bytes32 democHash) external view returns (bool) { return accounts[democHash].isPremium; } function getFreeExtension(bytes32 democHash) external view returns (bool) { return freeExtension[democHash]; } function getAccount(bytes32 democHash) external view returns (bool isPremium, uint lastPaymentTs, uint paidUpTill, bool hasFreeExtension) { isPremium = accounts[democHash].isPremium; lastPaymentTs = accounts[democHash].lastPaymentTs; paidUpTill = accounts[democHash].paidUpTill; hasFreeExtension = freeExtension[democHash]; } function getDenyPremium(bytes32 democHash) external view returns (bool) { return denyPremium[democHash]; } /* admin utils for accounts */ function giveTimeToDemoc(bytes32 democHash, uint additionalSeconds, bytes32 ref) owner_or(minorEditsAddr) external { _modAccountBalance(democHash, additionalSeconds); payments.push(PaymentLog(true, democHash, additionalSeconds, 0)); emit GrantedAccountTime(democHash, additionalSeconds, ref); } /* admin setters global */ function setPayTo(address newPayTo) only_owner() external { _setPayTo(newPayTo); emit SetPayTo(newPayTo); } function setMinorEditsAddr(address a) only_owner() external { minorEditsAddr = a; emit SetMinorEditsAddr(a); } function setBasicCentsPricePer30Days(uint amount) only_owner() external { basicCentsPricePer30Days = amount; emit SetBasicCentsPricePer30Days(amount); } function setBasicBallotsPer30Days(uint amount) only_owner() external { basicBallotsPer30Days = amount; emit SetBallotsPer30Days(amount); } function setPremiumMultiplier(uint8 m) only_owner() external { premiumMultiplier = m; emit SetPremiumMultiplier(m); } function setWeiPerCent(uint wpc) owner_or(minorEditsAddr) external { weiPerCent = wpc; emit SetExchangeRate(wpc); } function setFreeExtension(bytes32 democHash, bool hasFreeExt) owner_or(minorEditsAddr) external { freeExtension[democHash] = hasFreeExt; emit SetFreeExtension(democHash, hasFreeExt); } function setDenyPremium(bytes32 democHash, bool isPremiumDenied) owner_or(minorEditsAddr) external { denyPremium[democHash] = isPremiumDenied; emit SetDenyPremium(democHash, isPremiumDenied); } function setMinWeiForDInit(uint amount) owner_or(minorEditsAddr) external { minWeiForDInit = amount; emit SetMinWeiForDInit(amount); } /* global getters */ function getBasicCentsPricePer30Days() external view returns (uint) { return basicCentsPricePer30Days; } function getBasicExtraBallotFeeWei() external view returns (uint) { return centsToWei(basicCentsPricePer30Days / basicBallotsPer30Days); } function getBasicBallotsPer30Days() external view returns (uint) { return basicBallotsPer30Days; } function getPremiumMultiplier() external view returns (uint8) { return premiumMultiplier; } function getPremiumCentsPricePer30Days() external view returns (uint) { return _premiumPricePer30Days(); } function _premiumPricePer30Days() internal view returns (uint) { return uint(premiumMultiplier) * basicCentsPricePer30Days; } function getWeiPerCent() external view returns (uint) { return weiPerCent; } function getUsdEthExchangeRate() external view returns (uint) { // this returns cents per ether return 1 ether / weiPerCent; } function getMinWeiForDInit() external view returns (uint) { return minWeiForDInit; } /* payments stuff */ function getPaymentLogN() external view returns (uint) { return payments.length; } function getPaymentLog(uint n) external view returns (bool _external, bytes32 _democHash, uint _seconds, uint _ethValue) { _external = payments[n]._external; _democHash = payments[n]._democHash; _seconds = payments[n]._seconds; _ethValue = payments[n]._ethValue; } } interface SvEnsIface { // Logged when the owner of a node assigns a new owner to a subnode. event NewOwner(bytes32 indexed node, bytes32 indexed label, address owner); // Logged when the owner of a node transfers ownership to a new account. event Transfer(bytes32 indexed node, address owner); // Logged when the resolver for a node changes. event NewResolver(bytes32 indexed node, address resolver); // Logged when the TTL of a node changes event NewTTL(bytes32 indexed node, uint64 ttl); function setSubnodeOwner(bytes32 node, bytes32 label, address owner) external returns (bytes32); function setResolver(bytes32 node, address resolver) external; function setOwner(bytes32 node, address owner) external; function setTTL(bytes32 node, uint64 ttl) external; function owner(bytes32 node) external view returns (address); function resolver(bytes32 node) external view returns (address); function ttl(bytes32 node) external view returns (uint64); } interface ENSIface { // Logged when the owner of a node assigns a new owner to a subnode. event NewOwner(bytes32 indexed node, bytes32 indexed label, address owner); // Logged when the owner of a node transfers ownership to a new account. event Transfer(bytes32 indexed node, address owner); // Logged when the resolver for a node changes. event NewResolver(bytes32 indexed node, address resolver); // Logged when the TTL of a node changes event NewTTL(bytes32 indexed node, uint64 ttl); function setSubnodeOwner(bytes32 node, bytes32 label, address owner) external; function setResolver(bytes32 node, address resolver) external; function setOwner(bytes32 node, address owner) external; function setTTL(bytes32 node, uint64 ttl) external; function owner(bytes32 node) external view returns (address); function resolver(bytes32 node) external view returns (address); function ttl(bytes32 node) external view returns (uint64); } contract PublicResolver { bytes4 constant INTERFACE_META_ID = 0x01ffc9a7; bytes4 constant ADDR_INTERFACE_ID = 0x3b3b57de; bytes4 constant CONTENT_INTERFACE_ID = 0xd8389dc5; bytes4 constant NAME_INTERFACE_ID = 0x691f3431; bytes4 constant ABI_INTERFACE_ID = 0x2203ab56; bytes4 constant PUBKEY_INTERFACE_ID = 0xc8690233; bytes4 constant TEXT_INTERFACE_ID = 0x59d1d43c; event AddrChanged(bytes32 indexed node, address a); event ContentChanged(bytes32 indexed node, bytes32 hash); event NameChanged(bytes32 indexed node, string name); event ABIChanged(bytes32 indexed node, uint256 indexed contentType); event PubkeyChanged(bytes32 indexed node, bytes32 x, bytes32 y); event TextChanged(bytes32 indexed node, string indexedKey, string key); struct PublicKey { bytes32 x; bytes32 y; } struct Record { address addr; bytes32 content; string name; PublicKey pubkey; mapping(string=>string) text; mapping(uint256=>bytes) abis; } ENSIface ens; mapping (bytes32 => Record) records; modifier only_owner(bytes32 node) { require(ens.owner(node) == msg.sender); _; } /** * Constructor. * @param ensAddr The ENS registrar contract. */ constructor(ENSIface ensAddr) public { ens = ensAddr; } /** * Sets the address associated with an ENS node. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param addr The address to set. */ function setAddr(bytes32 node, address addr) public only_owner(node) { records[node].addr = addr; emit AddrChanged(node, addr); } /** * Sets the content hash associated with an ENS node. * May only be called by the owner of that node in the ENS registry. * Note that this resource type is not standardized, and will likely change * in future to a resource type based on multihash. * @param node The node to update. * @param hash The content hash to set */ function setContent(bytes32 node, bytes32 hash) public only_owner(node) { records[node].content = hash; emit ContentChanged(node, hash); } /** * Sets the name associated with an ENS node, for reverse records. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param name The name to set. */ function setName(bytes32 node, string name) public only_owner(node) { records[node].name = name; emit NameChanged(node, name); } /** * Sets the ABI associated with an ENS node. * Nodes may have one ABI of each content type. To remove an ABI, set it to * the empty string. * @param node The node to update. * @param contentType The content type of the ABI * @param data The ABI data. */ function setABI(bytes32 node, uint256 contentType, bytes data) public only_owner(node) { // Content types must be powers of 2 require(((contentType - 1) & contentType) == 0); records[node].abis[contentType] = data; emit ABIChanged(node, contentType); } /** * Sets the SECP256k1 public key associated with an ENS node. * @param node The ENS node to query * @param x the X coordinate of the curve point for the public key. * @param y the Y coordinate of the curve point for the public key. */ function setPubkey(bytes32 node, bytes32 x, bytes32 y) public only_owner(node) { records[node].pubkey = PublicKey(x, y); emit PubkeyChanged(node, x, y); } /** * Sets the text data associated with an ENS node and key. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param key The key to set. * @param value The text data value to set. */ function setText(bytes32 node, string key, string value) public only_owner(node) { records[node].text[key] = value; emit TextChanged(node, key, key); } /** * Returns the text data associated with an ENS node and key. * @param node The ENS node to query. * @param key The text data key to query. * @return The associated text data. */ function text(bytes32 node, string key) public view returns (string) { return records[node].text[key]; } /** * Returns the SECP256k1 public key associated with an ENS node. * Defined in EIP 619. * @param node The ENS node to query * @return x, y the X and Y coordinates of the curve point for the public key. */ function pubkey(bytes32 node) public view returns (bytes32 x, bytes32 y) { return (records[node].pubkey.x, records[node].pubkey.y); } /** * Returns the ABI associated with an ENS node. * Defined in EIP205. * @param node The ENS node to query * @param contentTypes A bitwise OR of the ABI formats accepted by the caller. * @return contentType The content type of the return value * @return data The ABI data */ function ABI(bytes32 node, uint256 contentTypes) public view returns (uint256 contentType, bytes data) { Record storage record = records[node]; for (contentType = 1; contentType <= contentTypes; contentType <<= 1) { if ((contentType & contentTypes) != 0 && record.abis[contentType].length > 0) { data = record.abis[contentType]; return; } } contentType = 0; } /** * Returns the name associated with an ENS node, for reverse records. * Defined in EIP181. * @param node The ENS node to query. * @return The associated name. */ function name(bytes32 node) public view returns (string) { return records[node].name; } /** * Returns the content hash associated with an ENS node. * Note that this resource type is not standardized, and will likely change * in future to a resource type based on multihash. * @param node The ENS node to query. * @return The associated content hash. */ function content(bytes32 node) public view returns (bytes32) { return records[node].content; } /** * Returns the address associated with an ENS node. * @param node The ENS node to query. * @return The associated address. */ function addr(bytes32 node) public view returns (address) { return records[node].addr; } /** * Returns true if the resolver implements the interface specified by the provided hash. * @param interfaceID The ID of the interface to check for. * @return True if the contract implements the requested interface. */ function supportsInterface(bytes4 interfaceID) public pure returns (bool) { return interfaceID == ADDR_INTERFACE_ID || interfaceID == CONTENT_INTERFACE_ID || interfaceID == NAME_INTERFACE_ID || interfaceID == ABI_INTERFACE_ID || interfaceID == PUBKEY_INTERFACE_ID || interfaceID == TEXT_INTERFACE_ID || interfaceID == INTERFACE_META_ID; } } library BytesLib { function concat(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bytes) { bytes memory tempBytes; assembly { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // Store the length of the first bytes array at the beginning of // the memory for tempBytes. let length := mload(_preBytes) mstore(tempBytes, length) // Maintain a memory counter for the current write location in the // temp bytes array by adding the 32 bytes for the array length to // the starting location. let mc := add(tempBytes, 0x20) // Stop copying when the memory counter reaches the length of the // first bytes array. let end := add(mc, length) for { // Initialize a copy counter to the start of the _preBytes data, // 32 bytes into its memory. let cc := add(_preBytes, 0x20) } lt(mc, end) { // Increase both counters by 32 bytes each iteration. mc := add(mc, 0x20) cc := add(cc, 0x20) } { // Write the _preBytes data into the tempBytes memory 32 bytes // at a time. mstore(mc, mload(cc)) } // Add the length of _postBytes to the current length of tempBytes // and store it as the new length in the first 32 bytes of the // tempBytes memory. length := mload(_postBytes) mstore(tempBytes, add(length, mload(tempBytes))) // Move the memory counter back from a multiple of 0x20 to the // actual end of the _preBytes data. mc := end // Stop copying when the memory counter reaches the new combined // length of the arrays. end := add(mc, length) for { let cc := add(_postBytes, 0x20) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } // Update the free-memory pointer by padding our last write location // to 32 bytes: add 31 bytes to the end of tempBytes to move to the // next 32 byte block, then round down to the nearest multiple of // 32. If the sum of the length of the two arrays is zero then add // one before rounding down to leave a blank 32 bytes (the length block with 0). mstore(0x40, and( add(add(end, iszero(add(length, mload(_preBytes)))), 31), not(31) // Round down to the nearest 32 bytes. )) } return tempBytes; } function concatStorage(bytes storage _preBytes, bytes memory _postBytes) internal { assembly { // Read the first 32 bytes of _preBytes storage, which is the length // of the array. (We don't need to use the offset into the slot // because arrays use the entire slot.) let fslot := sload(_preBytes_slot) // Arrays of 31 bytes or less have an even value in their slot, // while longer arrays have an odd value. The actual length is // the slot divided by two for odd values, and the lowest order // byte divided by two for even values. // If the slot is even, bitwise and the slot with 255 and divide by // two to get the length. If the slot is odd, bitwise and the slot // with -1 and divide by two. let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2) let mlength := mload(_postBytes) let newlength := add(slength, mlength) // slength can contain both the length and contents of the array // if length < 32 bytes so let's prepare for that // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage switch add(lt(slength, 32), lt(newlength, 32)) case 2 { // Since the new array still fits in the slot, we just need to // update the contents of the slot. // uint256(bytes_storage) = uint256(bytes_storage) + uint256(bytes_memory) + new_length sstore( _preBytes_slot, // all the modifications to the slot are inside this // next block add( // we can just add to the slot contents because the // bytes we want to change are the LSBs fslot, add( mul( div( // load the bytes from memory mload(add(_postBytes, 0x20)), // zero all bytes to the right exp(0x100, sub(32, mlength)) ), // and now shift left the number of bytes to // leave space for the length in the slot exp(0x100, sub(32, newlength)) ), // increase length by the double of the memory // bytes length mul(mlength, 2) ) ) ) } case 1 { // The stored value fits in the slot, but the combined value // will exceed it. // get the keccak hash to get the contents of the array mstore(0x0, _preBytes_slot) let sc := add(keccak256(0x0, 0x20), div(slength, 32)) // save new length sstore(_preBytes_slot, add(mul(newlength, 2), 1)) // The contents of the _postBytes array start 32 bytes into // the structure. Our first read should obtain the `submod` // bytes that can fit into the unused space in the last word // of the stored array. To get this, we read 32 bytes starting // from `submod`, so the data we read overlaps with the array // contents by `submod` bytes. Masking the lowest-order // `submod` bytes allows us to add that value directly to the // stored value. let submod := sub(32, slength) let mc := add(_postBytes, submod) let end := add(_postBytes, mlength) let mask := sub(exp(0x100, submod), 1) sstore( sc, add( and( fslot, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00 ), and(mload(mc), mask) ) ) for { mc := add(mc, 0x20) sc := add(sc, 1) } lt(mc, end) { sc := add(sc, 1) mc := add(mc, 0x20) } { sstore(sc, mload(mc)) } mask := exp(0x100, sub(mc, end)) sstore(sc, mul(div(mload(mc), mask), mask)) } default { // get the keccak hash to get the contents of the array mstore(0x0, _preBytes_slot) // Start copying to the last used word of the stored array. let sc := add(keccak256(0x0, 0x20), div(slength, 32)) // save new length sstore(_preBytes_slot, add(mul(newlength, 2), 1)) // Copy over the first `submod` bytes of the new data as in // case 1 above. let slengthmod := mod(slength, 32) let mlengthmod := mod(mlength, 32) let submod := sub(32, slengthmod) let mc := add(_postBytes, submod) let end := add(_postBytes, mlength) let mask := sub(exp(0x100, submod), 1) sstore(sc, add(sload(sc), and(mload(mc), mask))) for { sc := add(sc, 1) mc := add(mc, 0x20) } lt(mc, end) { sc := add(sc, 1) mc := add(mc, 0x20) } { sstore(sc, mload(mc)) } mask := exp(0x100, sub(mc, end)) sstore(sc, mul(div(mload(mc), mask), mask)) } } } function slice(bytes _bytes, uint _start, uint _length) internal pure returns (bytes) { require(_bytes.length >= (_start + _length)); bytes memory tempBytes; assembly { switch iszero(_length) case 0 { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // The first word of the slice result is potentially a partial // word read from the original array. To read it, we calculate // the length of that partial word and start copying that many // bytes into the array. The first word we copy will start with // data we don't care about, but the last `lengthmod` bytes will // land at the beginning of the contents of the new array. When // we're done copying, we overwrite the full first word with // the actual length of the slice. let lengthmod := and(_length, 31) // The multiplication in the next line is necessary // because when slicing multiples of 32 bytes (lengthmod == 0) // the following copy loop was copying the origin's length // and then ending prematurely not copying everything it should. let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod))) let end := add(mc, _length) for { // The multiplication in the next line has the same exact purpose // as the one above. let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(tempBytes, _length) //update free-memory pointer //allocating the array padded to 32 bytes like the compiler does now mstore(0x40, and(add(mc, 31), not(31))) } //if we want a zero-length slice let's just return a zero-length array default { tempBytes := mload(0x40) mstore(0x40, add(tempBytes, 0x20)) } } return tempBytes; } function toAddress(bytes _bytes, uint _start) internal pure returns (address) { require(_bytes.length >= (_start + 20)); address tempAddress; assembly { tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000) } return tempAddress; } function toUint(bytes _bytes, uint _start) internal pure returns (uint256) { require(_bytes.length >= (_start + 32)); uint256 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x20), _start)) } return tempUint; } function equal(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) { bool success = true; assembly { let length := mload(_preBytes) // if lengths don't match the arrays are not equal switch eq(length, mload(_postBytes)) case 1 { // cb is a circuit breaker in the for loop since there's // no said feature for inline assembly loops // cb = 1 - don't breaker // cb = 0 - break let cb := 1 let mc := add(_preBytes, 0x20) let end := add(mc, length) for { let cc := add(_postBytes, 0x20) // the next line is the loop condition: // while(uint(mc < end) + cb == 2) } eq(add(lt(mc, end), cb), 2) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { // if any of these checks fails then arrays are not equal if iszero(eq(mload(mc), mload(cc))) { // unsuccess: success := 0 cb := 0 } } } default { // unsuccess: success := 0 } } return success; } function equalStorage(bytes storage _preBytes, bytes memory _postBytes) internal view returns (bool) { bool success = true; assembly { // we know _preBytes_offset is 0 let fslot := sload(_preBytes_slot) // Decode the length of the stored array like in concatStorage(). let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2) let mlength := mload(_postBytes) // if lengths don't match the arrays are not equal switch eq(slength, mlength) case 1 { // slength can contain both the length and contents of the array // if length < 32 bytes so let's prepare for that // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage if iszero(iszero(slength)) { switch lt(slength, 32) case 1 { // blank the last byte which is the length fslot := mul(div(fslot, 0x100), 0x100) if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) { // unsuccess: success := 0 } } default { // cb is a circuit breaker in the for loop since there's // no said feature for inline assembly loops // cb = 1 - don't breaker // cb = 0 - break let cb := 1 // get the keccak hash to get the contents of the array mstore(0x0, _preBytes_slot) let sc := keccak256(0x0, 0x20) let mc := add(_postBytes, 0x20) let end := add(mc, mlength) // the next line is the loop condition: // while(uint(mc < end) + cb == 2) for {} eq(add(lt(mc, end), cb), 2) { sc := add(sc, 1) mc := add(mc, 0x20) } { if iszero(eq(sload(sc), mload(mc))) { // unsuccess: success := 0 cb := 0 } } } } } default { // unsuccess: success := 0 } } return success; } }
note: already checked msg.sender has admin with `only_admin` modifier
function upgradeMeAdmin(address newAdmin) only_admin() external { require(msg.sender != owner, "owner cannot upgrade self"); _setAdmin(msg.sender, false); _setAdmin(newAdmin, true); }
296,352
[ 1, 7652, 30, 1818, 5950, 1234, 18, 15330, 711, 3981, 598, 1375, 3700, 67, 3666, 68, 9606, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 8400, 4667, 4446, 12, 2867, 394, 4446, 13, 1338, 67, 3666, 1435, 3903, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 480, 3410, 16, 315, 8443, 2780, 8400, 365, 8863, 203, 3639, 389, 542, 4446, 12, 3576, 18, 15330, 16, 629, 1769, 203, 3639, 389, 542, 4446, 12, 2704, 4446, 16, 638, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x7d9CCd94ba18CdE4FBE93F918018B4A9FAa99893/sources/contracts/LiveMintArtist.sol
Returns [Address] => BRT Minter Role Mapping
mapping(address => bool) public Role;
17,096,864
[ 1, 1356, 306, 1887, 65, 516, 605, 12185, 490, 2761, 6204, 9408, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 12, 2867, 516, 1426, 13, 1071, 6204, 31, 27573, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x0c9663115b36Fa95D18E71D59054117BCb0342Ef/sources/contracts/XtremePixels.sol
============ INTERNAL ============
function _mintRandomly(address to, uint256 amount) internal { _mintRandom(to, amount); }
3,140,560
[ 1, 14468, 18139, 422, 1432, 631, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 81, 474, 8529, 715, 12, 2867, 358, 16, 2254, 5034, 3844, 13, 2713, 288, 203, 3639, 389, 81, 474, 8529, 12, 869, 16, 3844, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/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 { 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; } uint256[49] private __gap; } // 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: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/ContextUpgradeable.sol"; import "./ERC20Upgradeable.sol"; import "../../proxy/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 initializer { __Context_init_unchained(); __ERC20Burnable_init_unchained(); } function __ERC20Burnable_init_unchained() internal initializer { } using SafeMathUpgradeable for uint256; /** * @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 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } uint256[50] private __gap; } // 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; } // 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.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; 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: MIT pragma solidity >=0.6.0 <0.8.0; import "./ContextUpgradeable.sol"; import "../proxy/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 initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _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 pragma solidity >=0.6.0 <0.8.0; import "../proxy/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.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.0 <0.8.0; /** * @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for * deploying minimal proxy contracts, also known as "clones". * * > To simply and cheaply clone contract functionality in an immutable way, this standard specifies * > a minimal bytecode implementation that delegates all calls to a known, fixed address. * * The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2` * (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the * deterministic method. * * _Available since v3.4._ */ library Clones { /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `master`. * * This function uses the create opcode, which should never revert. */ function clone(address master) internal returns (address instance) { // solhint-disable-next-line no-inline-assembly assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, master)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create(0, ptr, 0x37) } require(instance != address(0), "ERC1167: create failed"); } /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `master`. * * This function uses the create2 opcode and a `salt` to deterministically deploy * the clone. Using the same `master` and `salt` multiple time will revert, since * the clones cannot be deployed twice at the same address. */ function cloneDeterministic(address master, bytes32 salt) internal returns (address instance) { // solhint-disable-next-line no-inline-assembly assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, master)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create2(0, ptr, 0x37, salt) } require(instance != address(0), "ERC1167: create2 failed"); } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress(address master, bytes32 salt, address deployer) internal pure returns (address predicted) { // solhint-disable-next-line no-inline-assembly assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, master)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf3ff00000000000000000000000000000000) mstore(add(ptr, 0x38), shl(0x60, deployer)) mstore(add(ptr, 0x4c), salt) mstore(add(ptr, 0x6c), keccak256(ptr, 0x37)) predicted := keccak256(add(ptr, 0x37), 0x55) } } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress(address master, bytes32 salt) internal view returns (address predicted) { return predictDeterministicAddress(master, salt, address(this)); } } // 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; /** * @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); } /** * @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.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.12; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./SwapUtils.sol"; /** * @title AmplificationUtils library * @notice A library to calculate and ramp the A parameter of a given `SwapUtils.Swap` struct. * This library assumes the struct is fully validated. */ library AmplificationUtils { using SafeMath for uint256; event RampA( uint256 oldA, uint256 newA, uint256 initialTime, uint256 futureTime ); event StopRampA(uint256 currentA, uint256 time); // Constant values used in ramping A calculations uint256 public constant A_PRECISION = 100; uint256 public constant MAX_A = 10**6; uint256 private constant MAX_A_CHANGE = 2; uint256 private constant MIN_RAMP_TIME = 14 days; /** * @notice Return A, the amplification coefficient * n * (n - 1) * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter */ function getA(SwapUtils.Swap storage self) external view returns (uint256) { return _getAPrecise(self).div(A_PRECISION); } /** * @notice Return A in its raw precision * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter in its raw precision form */ function getAPrecise(SwapUtils.Swap storage self) external view returns (uint256) { return _getAPrecise(self); } /** * @notice Return A in its raw precision * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter in its raw precision form */ function _getAPrecise(SwapUtils.Swap storage self) internal view returns (uint256) { uint256 t1 = self.futureATime; // time when ramp is finished uint256 a1 = self.futureA; // final A value when ramp is finished if (block.timestamp < t1) { uint256 t0 = self.initialATime; // time when ramp is started uint256 a0 = self.initialA; // initial A value when ramp is started if (a1 > a0) { // a0 + (a1 - a0) * (block.timestamp - t0) / (t1 - t0) return a0.add( a1.sub(a0).mul(block.timestamp.sub(t0)).div(t1.sub(t0)) ); } else { // a0 - (a0 - a1) * (block.timestamp - t0) / (t1 - t0) return a0.sub( a0.sub(a1).mul(block.timestamp.sub(t0)).div(t1.sub(t0)) ); } } else { return a1; } } /** * @notice Start ramping up or down A parameter towards given futureA_ and futureTime_ * Checks if the change is too rapid, and commits the new A value only when it falls under * the limit range. * @param self Swap struct to update * @param futureA_ the new A to ramp towards * @param futureTime_ timestamp when the new A should be reached */ function rampA( SwapUtils.Swap storage self, uint256 futureA_, uint256 futureTime_ ) external { require( block.timestamp >= self.initialATime.add(1 days), "Wait 1 day before starting ramp" ); require( futureTime_ >= block.timestamp.add(MIN_RAMP_TIME), "Insufficient ramp time" ); require( futureA_ > 0 && futureA_ < MAX_A, "futureA_ must be > 0 and < MAX_A" ); uint256 initialAPrecise = _getAPrecise(self); uint256 futureAPrecise = futureA_.mul(A_PRECISION); if (futureAPrecise < initialAPrecise) { require( futureAPrecise.mul(MAX_A_CHANGE) >= initialAPrecise, "futureA_ is too small" ); } else { require( futureAPrecise <= initialAPrecise.mul(MAX_A_CHANGE), "futureA_ is too large" ); } self.initialA = initialAPrecise; self.futureA = futureAPrecise; self.initialATime = block.timestamp; self.futureATime = futureTime_; emit RampA( initialAPrecise, futureAPrecise, block.timestamp, futureTime_ ); } /** * @notice Stops ramping A immediately. Once this function is called, rampA() * cannot be called for another 24 hours * @param self Swap struct to update */ function stopRampA(SwapUtils.Swap storage self) external { require(self.futureATime > block.timestamp, "Ramp is already stopped"); uint256 currentA = _getAPrecise(self); self.initialA = currentA; self.futureA = currentA; self.initialATime = block.timestamp; self.futureATime = block.timestamp; emit StopRampA(currentA, block.timestamp); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20BurnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "./interfaces/ISwap.sol"; /** * @title Liquidity Provider Token * @notice This token is an ERC20 detailed token with added capability to be minted by the owner. * It is used to represent user's shares when providing liquidity to swap contracts. * @dev Only Swap contracts should initialize and own LPToken contracts. */ contract LPToken is ERC20BurnableUpgradeable, OwnableUpgradeable { using SafeMathUpgradeable for uint256; /** * @notice Initializes this LPToken contract with the given name and symbol * @dev The caller of this function will become the owner. A Swap contract should call this * in its initializer function. * @param name name of this token * @param symbol symbol of this token */ function initialize(string memory name, string memory symbol) external initializer returns (bool) { __Context_init_unchained(); __ERC20_init_unchained(name, symbol); __Ownable_init_unchained(); return true; } /** * @notice Mints the given amount of LPToken to the recipient. * @dev only owner can call this mint function * @param recipient address of account to receive the tokens * @param amount amount of tokens to mint */ function mint(address recipient, uint256 amount) external onlyOwner { require(amount != 0, "LPToken: cannot mint 0"); _mint(recipient, amount); } /** * @dev Overrides ERC20._beforeTokenTransfer() which get called on every transfers including * minting and burning. This ensures that Swap.updateUserWithdrawFees are called everytime. * This assumes the owner is set to a Swap contract's address. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override(ERC20Upgradeable) { super._beforeTokenTransfer(from, to, amount); require(to != address(this), "LPToken: cannot send to itself"); ISwap(owner()).updateUserWithdrawFee(to, amount); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; /** * @title MathUtils library * @notice A library to be used in conjunction with SafeMath. Contains functions for calculating * differences between two uint256. */ library MathUtils { /** * @notice Compares a and b and returns true if the difference between a and b * is less than 1 or equal to each other. * @param a uint256 to compare with * @param b uint256 to compare with * @return True if the difference between a and b is less than 1 or equal, * otherwise return false */ function within1(uint256 a, uint256 b) internal pure returns (bool) { return (difference(a, b) <= 1); } /** * @notice Calculates absolute difference between a and b * @param a uint256 to compare with * @param b uint256 to compare with * @return Difference between a and b */ function difference(uint256 a, uint256 b) internal pure returns (uint256) { if (a > b) { return a - b; } return b - a; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol"; /** * @title OwnerPausable * @notice An ownable contract allows the owner to pause and unpause the * contract without a delay. * @dev Only methods using the provided modifiers will be paused. */ abstract contract OwnerPausableUpgradeable is OwnableUpgradeable, PausableUpgradeable { function __OwnerPausable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); __Pausable_init_unchained(); } /** * @notice Pause the contract. Revert if already paused. */ function pause() external onlyOwner { PausableUpgradeable._pause(); } /** * @notice Unpause the contract. Revert if already unpaused. */ function unpause() external onlyOwner { PausableUpgradeable._unpause(); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/proxy/Clones.sol"; import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol"; import "./OwnerPausableUpgradeable.sol"; import "./SwapUtils.sol"; import "./AmplificationUtils.sol"; /** * @title Swap - A StableSwap implementation in solidity. * @notice This contract is responsible for custody of closely pegged assets (eg. group of stablecoins) * and automatic market making system. Users become an LP (Liquidity Provider) by depositing their tokens * in desired ratios for an exchange of the pool token that represents their share of the pool. * Users can burn pool tokens and withdraw their share of token(s). * * Each time a swap between the pooled tokens happens, a set fee incurs which effectively gets * distributed to the LPs. * * In case of emergencies, admin can pause additional deposits, swaps, or single-asset withdraws - which * stops the ratio of the tokens in the pool from changing. * Users can always withdraw their tokens via multi-asset withdraws. * * @dev Most of the logic is stored as a library `SwapUtils` for the sake of reducing contract's * deployment size. */ contract Swap is OwnerPausableUpgradeable, ReentrancyGuardUpgradeable { using SafeERC20 for IERC20; using SafeMath for uint256; using SwapUtils for SwapUtils.Swap; using AmplificationUtils for SwapUtils.Swap; // Struct storing data responsible for automatic market maker functionalities. In order to // access this data, this contract uses SwapUtils library. For more details, see SwapUtils.sol SwapUtils.Swap public swapStorage; // Maps token address to an index in the pool. Used to prevent duplicate tokens in the pool. // getTokenIndex function also relies on this mapping to retrieve token index. mapping(address => uint8) private tokenIndexes; /*** EVENTS ***/ // events replicated from SwapUtils to make the ABI easier for dumb // clients event TokenSwap( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event AddLiquidity( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event RemoveLiquidity( address indexed provider, uint256[] tokenAmounts, uint256 lpTokenSupply ); event RemoveLiquidityOne( address indexed provider, uint256 lpTokenAmount, uint256 lpTokenSupply, uint256 boughtId, uint256 tokensBought ); event RemoveLiquidityImbalance( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event NewAdminFee(uint256 newAdminFee); event NewSwapFee(uint256 newSwapFee); event NewWithdrawFee(uint256 newWithdrawFee); event RampA( uint256 oldA, uint256 newA, uint256 initialTime, uint256 futureTime ); event StopRampA(uint256 currentA, uint256 time); /** * @notice Initializes this Swap contract with the given parameters. * This will also clone a LPToken contract that represents users' * LP positions. The owner of LPToken will be this contract - which means * only this contract is allowed to mint/burn tokens. * * @param _pooledTokens an array of ERC20s this pool will accept * @param decimals the decimals to use for each pooled token, * eg 8 for WBTC. Cannot be larger than POOL_PRECISION_DECIMALS * @param lpTokenName the long-form name of the token to be deployed * @param lpTokenSymbol the short symbol for the token to be deployed * @param _a the amplification coefficient * n * (n - 1). See the * StableSwap paper for details * @param _fee default swap fee to be initialized with * @param _adminFee default adminFee to be initialized with * @param _withdrawFee default withdrawFee to be initialized with * @param lpTokenTargetAddress the address of an existing LPToken contract to use as a target */ function initialize( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, uint256 _withdrawFee, address lpTokenTargetAddress ) public virtual initializer { __OwnerPausable_init(); __ReentrancyGuard_init(); // Check _pooledTokens and precisions parameter require(_pooledTokens.length > 1, "_pooledTokens.length <= 1"); require(_pooledTokens.length <= 32, "_pooledTokens.length > 32"); require( _pooledTokens.length == decimals.length, "_pooledTokens decimals mismatch" ); uint256[] memory precisionMultipliers = new uint256[](decimals.length); for (uint8 i = 0; i < _pooledTokens.length; i++) { if (i > 0) { // Check if index is already used. Check if 0th element is a duplicate. require( tokenIndexes[address(_pooledTokens[i])] == 0 && _pooledTokens[0] != _pooledTokens[i], "Duplicate tokens" ); } require( address(_pooledTokens[i]) != address(0), "The 0 address isn't an ERC-20" ); require( decimals[i] <= SwapUtils.POOL_PRECISION_DECIMALS, "Token decimals exceeds max" ); precisionMultipliers[i] = 10 ** uint256(SwapUtils.POOL_PRECISION_DECIMALS).sub( uint256(decimals[i]) ); tokenIndexes[address(_pooledTokens[i])] = i; } // Check _a, _fee, _adminFee, _withdrawFee parameters require(_a < AmplificationUtils.MAX_A, "_a exceeds maximum"); require(_fee < SwapUtils.MAX_SWAP_FEE, "_fee exceeds maximum"); require( _adminFee < SwapUtils.MAX_ADMIN_FEE, "_adminFee exceeds maximum" ); require( _withdrawFee < SwapUtils.MAX_WITHDRAW_FEE, "_withdrawFee exceeds maximum" ); // Clone and initialize a LPToken contract LPToken lpToken = LPToken(Clones.clone(lpTokenTargetAddress)); require( lpToken.initialize(lpTokenName, lpTokenSymbol), "could not init lpToken clone" ); // Initialize swapStorage struct swapStorage.lpToken = lpToken; swapStorage.pooledTokens = _pooledTokens; swapStorage.tokenPrecisionMultipliers = precisionMultipliers; swapStorage.balances = new uint256[](_pooledTokens.length); swapStorage.initialA = _a.mul(AmplificationUtils.A_PRECISION); swapStorage.futureA = _a.mul(AmplificationUtils.A_PRECISION); // swapStorage.initialATime = 0; // swapStorage.futureATime = 0; swapStorage.swapFee = _fee; swapStorage.adminFee = _adminFee; swapStorage.defaultWithdrawFee = _withdrawFee; } /*** MODIFIERS ***/ /** * @notice Modifier to check deadline against current timestamp * @param deadline latest timestamp to accept this transaction */ modifier deadlineCheck(uint256 deadline) { require(block.timestamp <= deadline, "Deadline not met"); _; } /*** VIEW FUNCTIONS ***/ /** * @notice Return A, the amplification coefficient * n * (n - 1) * @dev See the StableSwap paper for details * @return A parameter */ function getA() external view virtual returns (uint256) { return swapStorage.getA(); } /** * @notice Return A in its raw precision form * @dev See the StableSwap paper for details * @return A parameter in its raw precision form */ function getAPrecise() external view virtual returns (uint256) { return swapStorage.getAPrecise(); } /** * @notice Return address of the pooled token at given index. Reverts if tokenIndex is out of range. * @param index the index of the token * @return address of the token at given index */ function getToken(uint8 index) public view virtual returns (IERC20) { require(index < swapStorage.pooledTokens.length, "Out of range"); return swapStorage.pooledTokens[index]; } /** * @notice Return the index of the given token address. Reverts if no matching * token is found. * @param tokenAddress address of the token * @return the index of the given token address */ function getTokenIndex(address tokenAddress) public view virtual returns (uint8) { uint8 index = tokenIndexes[tokenAddress]; require( address(getToken(index)) == tokenAddress, "Token does not exist" ); return index; } /** * @notice Return timestamp of last deposit of given address * @return timestamp of the last deposit made by the given address */ function getDepositTimestamp(address user) external view virtual returns (uint256) { return swapStorage.getDepositTimestamp(user); } /** * @notice Return current balance of the pooled token at given index * @param index the index of the token * @return current balance of the pooled token at given index with token's native precision */ function getTokenBalance(uint8 index) external view virtual returns (uint256) { require(index < swapStorage.pooledTokens.length, "Index out of range"); return swapStorage.balances[index]; } /** * @notice Get the virtual price, to help calculate profit * @return the virtual price, scaled to the POOL_PRECISION_DECIMALS */ function getVirtualPrice() external view virtual returns (uint256) { return swapStorage.getVirtualPrice(); } /** * @notice Calculate amount of tokens you receive on swap * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell. If the token charges * a fee on transfers, use the amount that gets transferred after the fee. * @return amount of tokens the user will receive */ function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view virtual returns (uint256) { return swapStorage.calculateSwap(tokenIndexFrom, tokenIndexTo, dx); } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param account address that is depositing or withdrawing tokens * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return token amount the user will receive */ function calculateTokenAmount( address account, uint256[] calldata amounts, bool deposit ) external view virtual returns (uint256) { return swapStorage.calculateTokenAmount(account, amounts, deposit); } /** * @notice A simple method to calculate amount of each underlying * tokens that is returned upon burning given amount of LP tokens * @param account the address that is withdrawing tokens * @param amount the amount of LP tokens that would be burned on withdrawal * @return array of token balances that the user will receive */ function calculateRemoveLiquidity(address account, uint256 amount) external view virtual returns (uint256[] memory) { return swapStorage.calculateRemoveLiquidity(account, amount); } /** * @notice Calculate the amount of underlying token available to withdraw * when withdrawing via only single token * @param account the address that is withdrawing tokens * @param tokenAmount the amount of LP token to burn * @param tokenIndex index of which token will be withdrawn * @return availableTokenAmount calculated amount of underlying token * available to withdraw */ function calculateRemoveLiquidityOneToken( address account, uint256 tokenAmount, uint8 tokenIndex ) external view virtual returns (uint256 availableTokenAmount) { return swapStorage.calculateWithdrawOneToken( account, tokenAmount, tokenIndex ); } /** * @notice Calculate the fee that is applied when the given user withdraws. The withdraw fee * decays linearly over period of 4 weeks. For example, depositing and withdrawing right away * will charge you the full amount of withdraw fee. But withdrawing after 4 weeks will charge you * no additional fees. * @dev returned value should be divided by FEE_DENOMINATOR to convert to correct decimals * @param user address you want to calculate withdraw fee of * @return current withdraw fee of the user */ function calculateCurrentWithdrawFee(address user) external view virtual returns (uint256) { return swapStorage.calculateCurrentWithdrawFee(user); } /** * @notice This function reads the accumulated amount of admin fees of the token with given index * @param index Index of the pooled token * @return admin's token balance in the token's precision */ function getAdminBalance(uint256 index) external view virtual returns (uint256) { return swapStorage.getAdminBalance(index); } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice Swap two tokens using this pool * @param tokenIndexFrom the token the user wants to swap from * @param tokenIndexTo the token the user wants to swap to * @param dx the amount of tokens the user wants to swap from * @param minDy the min amount the user would like to receive, or revert. * @param deadline latest timestamp to accept this transaction */ function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.swap(tokenIndexFrom, tokenIndexTo, dx, minDy); } /** * @notice Add liquidity to the pool with the given amounts of tokens * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * @param deadline latest timestamp to accept this transaction * @return amount of LP token user minted and received */ function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.addLiquidity(amounts, minToMint); } /** * @notice Burn LP tokens to remove liquidity from the pool. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @dev Liquidity can always be removed, even when the pool is paused. * @param amount the amount of LP tokens to burn * @param minAmounts the minimum amounts of each token in the pool * acceptable for this burn. Useful as a front-running mitigation * @param deadline latest timestamp to accept this transaction * @return amounts of tokens user received */ function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external virtual nonReentrant deadlineCheck(deadline) returns (uint256[] memory) { return swapStorage.removeLiquidity(amount, minAmounts); } /** * @notice Remove liquidity from the pool all in one token. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param tokenAmount the amount of the token you want to receive * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @param deadline latest timestamp to accept this transaction * @return amount of chosen token user received */ function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.removeLiquidityOneToken( tokenAmount, tokenIndex, minAmount ); } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @param deadline latest timestamp to accept this transaction * @return amount of LP tokens burned */ function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.removeLiquidityImbalance(amounts, maxBurnAmount); } /*** ADMIN FUNCTIONS ***/ /** * @notice Updates the user withdraw fee. This function can only be called by * the pool token. Should be used to update the withdraw fee on transfer of pool tokens. * Transferring your pool token will reset the 4 weeks period. If the recipient is already * holding some pool tokens, the withdraw fee will be discounted in respective amounts. * @param recipient address of the recipient of pool token * @param transferAmount amount of pool token to transfer */ function updateUserWithdrawFee(address recipient, uint256 transferAmount) external { require( msg.sender == address(swapStorage.lpToken), "Only callable by pool token" ); swapStorage.updateUserWithdrawFee(recipient, transferAmount); } /** * @notice Withdraw all admin fees to the contract owner */ function withdrawAdminFees() external onlyOwner { swapStorage.withdrawAdminFees(owner()); } /** * @notice Update the admin fee. Admin fee takes portion of the swap fee. * @param newAdminFee new admin fee to be applied on future transactions */ function setAdminFee(uint256 newAdminFee) external onlyOwner { swapStorage.setAdminFee(newAdminFee); } /** * @notice Update the swap fee to be applied on swaps * @param newSwapFee new swap fee to be applied on future transactions */ function setSwapFee(uint256 newSwapFee) external onlyOwner { swapStorage.setSwapFee(newSwapFee); } /** * @notice Update the withdraw fee. This fee decays linearly over 4 weeks since * user's last deposit. * @param newWithdrawFee new withdraw fee to be applied on future deposits */ function setDefaultWithdrawFee(uint256 newWithdrawFee) external onlyOwner { swapStorage.setDefaultWithdrawFee(newWithdrawFee); } /** * @notice Start ramping up or down A parameter towards given futureA and futureTime * Checks if the change is too rapid, and commits the new A value only when it falls under * the limit range. * @param futureA the new A to ramp towards * @param futureTime timestamp when the new A should be reached */ function rampA(uint256 futureA, uint256 futureTime) external onlyOwner { swapStorage.rampA(futureA, futureTime); } /** * @notice Stop ramping A immediately. Reverts if ramp A is already stopped. */ function stopRampA() external onlyOwner { swapStorage.stopRampA(); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./AmplificationUtils.sol"; import "./LPToken.sol"; import "./MathUtils.sol"; /** * @title SwapUtils library * @notice A library to be used within Swap.sol. Contains functions responsible for custody and AMM functionalities. * @dev Contracts relying on this library must initialize SwapUtils.Swap struct then use this library * for SwapUtils.Swap struct. Note that this library contains both functions called by users and admins. * Admin functions should be protected within contracts using this library. */ library SwapUtils { using SafeERC20 for IERC20; using SafeMath for uint256; using MathUtils for uint256; /*** EVENTS ***/ event TokenSwap( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event AddLiquidity( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event RemoveLiquidity( address indexed provider, uint256[] tokenAmounts, uint256 lpTokenSupply ); event RemoveLiquidityOne( address indexed provider, uint256 lpTokenAmount, uint256 lpTokenSupply, uint256 boughtId, uint256 tokensBought ); event RemoveLiquidityImbalance( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event NewAdminFee(uint256 newAdminFee); event NewSwapFee(uint256 newSwapFee); event NewWithdrawFee(uint256 newWithdrawFee); struct Swap { // variables around the ramp management of A, // the amplification coefficient * n * (n - 1) // see https://www.curve.fi/stableswap-paper.pdf for details uint256 initialA; uint256 futureA; uint256 initialATime; uint256 futureATime; // fee calculation uint256 swapFee; uint256 adminFee; uint256 defaultWithdrawFee; LPToken lpToken; // contract references for all tokens being pooled IERC20[] pooledTokens; // multipliers for each pooled token's precision to get to POOL_PRECISION_DECIMALS // for example, TBTC has 18 decimals, so the multiplier should be 1. WBTC // has 8, so the multiplier should be 10 ** 18 / 10 ** 8 => 10 ** 10 uint256[] tokenPrecisionMultipliers; // the pool balance of each token, in the token's precision // the contract's actual token balance might differ uint256[] balances; mapping(address => uint256) depositTimestamp; mapping(address => uint256) withdrawFeeMultiplier; } // Struct storing variables used in calculations in the // calculateWithdrawOneTokenDY function to avoid stack too deep errors struct CalculateWithdrawOneTokenDYInfo { uint256 d0; uint256 d1; uint256 newY; uint256 feePerToken; uint256 preciseA; } // Struct storing variables used in calculations in the // {add,remove}Liquidity functions to avoid stack too deep errors struct ManageLiquidityInfo { uint256 d0; uint256 d1; uint256 d2; uint256 preciseA; LPToken lpToken; uint256 totalSupply; uint256[] balances; uint256[] multipliers; } // the precision all pools tokens will be converted to uint8 public constant POOL_PRECISION_DECIMALS = 18; // the denominator used to calculate admin and LP fees. For example, an // LP fee might be something like tradeAmount.mul(fee).div(FEE_DENOMINATOR) uint256 private constant FEE_DENOMINATOR = 10**10; // Max swap fee is 1% or 100bps of each swap uint256 public constant MAX_SWAP_FEE = 10**8; // Max adminFee is 100% of the swapFee // adminFee does not add additional fee on top of swapFee // Instead it takes a certain % of the swapFee. Therefore it has no impact on the // users but only on the earnings of LPs uint256 public constant MAX_ADMIN_FEE = 10**10; // Max withdrawFee is 1% of the value withdrawn // Fee will be redistributed to the LPs in the pool, rewarding // long term providers. uint256 public constant MAX_WITHDRAW_FEE = 10**8; // Constant value used as max loop limit uint256 private constant MAX_LOOP_LIMIT = 256; // Time that it should take for the withdraw fee to fully decay to 0 uint256 public constant WITHDRAW_FEE_DECAY_TIME = 4 weeks; /*** VIEW & PURE FUNCTIONS ***/ /** * @notice Retrieves the timestamp of last deposit made by the given address * @param self Swap struct to read from * @return timestamp of last deposit */ function getDepositTimestamp(Swap storage self, address user) external view returns (uint256) { return self.depositTimestamp[user]; } function _getAPrecise(Swap storage self) internal view returns (uint256) { return AmplificationUtils._getAPrecise(self); } /** * @notice Calculate the dy, the amount of selected token that user receives and * the fee of withdrawing in one token * @param account the address that is withdrawing * @param tokenAmount the amount to withdraw in the pool's precision * @param tokenIndex which token will be withdrawn * @param self Swap struct to read from * @return the amount of token user will receive */ function calculateWithdrawOneToken( Swap storage self, address account, uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256) { (uint256 availableTokenAmount, ) = _calculateWithdrawOneToken( self, account, tokenAmount, tokenIndex, self.lpToken.totalSupply() ); return availableTokenAmount; } function _calculateWithdrawOneToken( Swap storage self, address account, uint256 tokenAmount, uint8 tokenIndex, uint256 totalSupply ) internal view returns (uint256, uint256) { uint256 dy; uint256 newY; uint256 currentY; (dy, newY, currentY) = calculateWithdrawOneTokenDY( self, tokenIndex, tokenAmount, totalSupply ); // dy_0 (without fees) // dy, dy_0 - dy uint256 dySwapFee = currentY .sub(newY) .div(self.tokenPrecisionMultipliers[tokenIndex]) .sub(dy); dy = dy .mul( FEE_DENOMINATOR.sub(_calculateCurrentWithdrawFee(self, account)) ) .div(FEE_DENOMINATOR); return (dy, dySwapFee); } /** * @notice Calculate the dy of withdrawing in one token * @param self Swap struct to read from * @param tokenIndex which token will be withdrawn * @param tokenAmount the amount to withdraw in the pools precision * @return the d and the new y after withdrawing one token */ function calculateWithdrawOneTokenDY( Swap storage self, uint8 tokenIndex, uint256 tokenAmount, uint256 totalSupply ) internal view returns ( uint256, uint256, uint256 ) { // Get the current D, then solve the stableswap invariant // y_i for D - tokenAmount uint256[] memory xp = _xp(self); require(tokenIndex < xp.length, "Token index out of range"); CalculateWithdrawOneTokenDYInfo memory v = CalculateWithdrawOneTokenDYInfo(0, 0, 0, 0, 0); v.preciseA = _getAPrecise(self); v.d0 = getD(xp, v.preciseA); v.d1 = v.d0.sub(tokenAmount.mul(v.d0).div(totalSupply)); require(tokenAmount <= xp[tokenIndex], "Withdraw exceeds available"); v.newY = getYD(v.preciseA, tokenIndex, xp, v.d1); uint256[] memory xpReduced = new uint256[](xp.length); v.feePerToken = _feePerToken(self.swapFee, xp.length); for (uint256 i = 0; i < xp.length; i++) { uint256 xpi = xp[i]; // if i == tokenIndex, dxExpected = xp[i] * d1 / d0 - newY // else dxExpected = xp[i] - (xp[i] * d1 / d0) // xpReduced[i] -= dxExpected * fee / FEE_DENOMINATOR xpReduced[i] = xpi.sub( ( (i == tokenIndex) ? xpi.mul(v.d1).div(v.d0).sub(v.newY) : xpi.sub(xpi.mul(v.d1).div(v.d0)) ) .mul(v.feePerToken) .div(FEE_DENOMINATOR) ); } uint256 dy = xpReduced[tokenIndex].sub( getYD(v.preciseA, tokenIndex, xpReduced, v.d1) ); dy = dy.sub(1).div(self.tokenPrecisionMultipliers[tokenIndex]); return (dy, v.newY, xp[tokenIndex]); } /** * @notice Calculate the price of a token in the pool with given * precision-adjusted balances and a particular D. * * @dev This is accomplished via solving the invariant iteratively. * See the StableSwap paper and Curve.fi implementation for further details. * * x_1**2 + x1 * (sum' - (A*n**n - 1) * D / (A * n**n)) = D ** (n + 1) / (n ** (2 * n) * prod' * A) * x_1**2 + b*x_1 = c * x_1 = (x_1**2 + c) / (2*x_1 + b) * * @param a the amplification coefficient * n * (n - 1). See the StableSwap paper for details. * @param tokenIndex Index of token we are calculating for. * @param xp a precision-adjusted set of pool balances. Array should be * the same cardinality as the pool. * @param d the stableswap invariant * @return the price of the token, in the same precision as in xp */ function getYD( uint256 a, uint8 tokenIndex, uint256[] memory xp, uint256 d ) internal pure returns (uint256) { uint256 numTokens = xp.length; require(tokenIndex < numTokens, "Token not found"); uint256 c = d; uint256 s; uint256 nA = a.mul(numTokens); for (uint256 i = 0; i < numTokens; i++) { if (i != tokenIndex) { s = s.add(xp[i]); c = c.mul(d).div(xp[i].mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // c = c * D * D * D * ... overflow! } } c = c.mul(d).mul(AmplificationUtils.A_PRECISION).div(nA.mul(numTokens)); uint256 b = s.add(d.mul(AmplificationUtils.A_PRECISION).div(nA)); uint256 yPrev; uint256 y = d; for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { yPrev = y; y = y.mul(y).add(c).div(y.mul(2).add(b).sub(d)); if (y.within1(yPrev)) { return y; } } revert("Approximation did not converge"); } /** * @notice Get D, the StableSwap invariant, based on a set of balances and a particular A. * @param xp a precision-adjusted set of pool balances. Array should be the same cardinality * as the pool. * @param a the amplification coefficient * n * (n - 1) in A_PRECISION. * See the StableSwap paper for details * @return the invariant, at the precision of the pool */ function getD(uint256[] memory xp, uint256 a) internal pure returns (uint256) { uint256 numTokens = xp.length; uint256 s; for (uint256 i = 0; i < numTokens; i++) { s = s.add(xp[i]); } if (s == 0) { return 0; } uint256 prevD; uint256 d = s; uint256 nA = a.mul(numTokens); for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { uint256 dP = d; for (uint256 j = 0; j < numTokens; j++) { dP = dP.mul(d).div(xp[j].mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // dP = dP * D * D * D * ... overflow! } prevD = d; d = nA .mul(s) .div(AmplificationUtils.A_PRECISION) .add(dP.mul(numTokens)) .mul(d) .div( nA .sub(AmplificationUtils.A_PRECISION) .mul(d) .div(AmplificationUtils.A_PRECISION) .add(numTokens.add(1).mul(dP)) ); if (d.within1(prevD)) { return d; } } // Convergence should occur in 4 loops or less. If this is reached, there may be something wrong // with the pool. If this were to occur repeatedly, LPs should withdraw via `removeLiquidity()` // function which does not rely on D. revert("D does not converge"); } /** * @notice Given a set of balances and precision multipliers, return the * precision-adjusted balances. * * @param balances an array of token balances, in their native precisions. * These should generally correspond with pooled tokens. * * @param precisionMultipliers an array of multipliers, corresponding to * the amounts in the balances array. When multiplied together they * should yield amounts at the pool's precision. * * @return an array of amounts "scaled" to the pool's precision */ function _xp( uint256[] memory balances, uint256[] memory precisionMultipliers ) internal pure returns (uint256[] memory) { uint256 numTokens = balances.length; require( numTokens == precisionMultipliers.length, "Balances must match multipliers" ); uint256[] memory xp = new uint256[](numTokens); for (uint256 i = 0; i < numTokens; i++) { xp[i] = balances[i].mul(precisionMultipliers[i]); } return xp; } /** * @notice Return the precision-adjusted balances of all tokens in the pool * @param self Swap struct to read from * @return the pool balances "scaled" to the pool's precision, allowing * them to be more easily compared. */ function _xp(Swap storage self) internal view returns (uint256[] memory) { return _xp(self.balances, self.tokenPrecisionMultipliers); } /** * @notice Get the virtual price, to help calculate profit * @param self Swap struct to read from * @return the virtual price, scaled to precision of POOL_PRECISION_DECIMALS */ function getVirtualPrice(Swap storage self) external view returns (uint256) { uint256 d = getD(_xp(self), _getAPrecise(self)); LPToken lpToken = self.lpToken; uint256 supply = lpToken.totalSupply(); if (supply > 0) { return d.mul(10**uint256(POOL_PRECISION_DECIMALS)).div(supply); } return 0; } /** * @notice Calculate the new balances of the tokens given the indexes of the token * that is swapped from (FROM) and the token that is swapped to (TO). * This function is used as a helper function to calculate how much TO token * the user should receive on swap. * * @param preciseA precise form of amplification coefficient * @param tokenIndexFrom index of FROM token * @param tokenIndexTo index of TO token * @param x the new total amount of FROM token * @param xp balances of the tokens in the pool * @return the amount of TO token that should remain in the pool */ function getY( uint256 preciseA, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 x, uint256[] memory xp ) internal pure returns (uint256) { uint256 numTokens = xp.length; require( tokenIndexFrom != tokenIndexTo, "Can't compare token to itself" ); require( tokenIndexFrom < numTokens && tokenIndexTo < numTokens, "Tokens must be in pool" ); uint256 d = getD(xp, preciseA); uint256 c = d; uint256 s; uint256 nA = numTokens.mul(preciseA); uint256 _x; for (uint256 i = 0; i < numTokens; i++) { if (i == tokenIndexFrom) { _x = x; } else if (i != tokenIndexTo) { _x = xp[i]; } else { continue; } s = s.add(_x); c = c.mul(d).div(_x.mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // c = c * D * D * D * ... overflow! } c = c.mul(d).mul(AmplificationUtils.A_PRECISION).div(nA.mul(numTokens)); uint256 b = s.add(d.mul(AmplificationUtils.A_PRECISION).div(nA)); uint256 yPrev; uint256 y = d; // iterative approximation for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { yPrev = y; y = y.mul(y).add(c).div(y.mul(2).add(b).sub(d)); if (y.within1(yPrev)) { return y; } } revert("Approximation did not converge"); } /** * @notice Externally calculates a swap between two tokens. * @param self Swap struct to read from * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @return dy the number of tokens the user will get */ function calculateSwap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256 dy) { (dy, ) = _calculateSwap( self, tokenIndexFrom, tokenIndexTo, dx, self.balances ); } /** * @notice Internally calculates a swap between two tokens. * * @dev The caller is expected to transfer the actual amounts (dx and dy) * using the token contracts. * * @param self Swap struct to read from * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @return dy the number of tokens the user will get * @return dyFee the associated fee */ function _calculateSwap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256[] memory balances ) internal view returns (uint256 dy, uint256 dyFee) { uint256[] memory multipliers = self.tokenPrecisionMultipliers; uint256[] memory xp = _xp(balances, multipliers); require( tokenIndexFrom < xp.length && tokenIndexTo < xp.length, "Token index out of range" ); uint256 x = dx.mul(multipliers[tokenIndexFrom]).add(xp[tokenIndexFrom]); uint256 y = getY(_getAPrecise(self), tokenIndexFrom, tokenIndexTo, x, xp); dy = xp[tokenIndexTo].sub(y).sub(1); dyFee = dy.mul(self.swapFee).div(FEE_DENOMINATOR); dy = dy.sub(dyFee).div(multipliers[tokenIndexTo]); } /** * @notice A simple method to calculate amount of each underlying * tokens that is returned upon burning given amount of * LP tokens * * @param account the address that is removing liquidity. required for withdraw fee calculation * @param amount the amount of LP tokens that would to be burned on * withdrawal * @return array of amounts of tokens user will receive */ function calculateRemoveLiquidity( Swap storage self, address account, uint256 amount ) external view returns (uint256[] memory) { return _calculateRemoveLiquidity( self, self.balances, account, amount, self.lpToken.totalSupply() ); } function _calculateRemoveLiquidity( Swap storage self, uint256[] memory balances, address account, uint256 amount, uint256 totalSupply ) internal view returns (uint256[] memory) { require(amount <= totalSupply, "Cannot exceed total supply"); uint256 feeAdjustedAmount = amount .mul( FEE_DENOMINATOR.sub(_calculateCurrentWithdrawFee(self, account)) ) .div(FEE_DENOMINATOR); uint256[] memory amounts = new uint256[](balances.length); for (uint256 i = 0; i < balances.length; i++) { amounts[i] = balances[i].mul(feeAdjustedAmount).div(totalSupply); } return amounts; } /** * @notice Calculate the fee that is applied when the given user withdraws. * Withdraw fee decays linearly over WITHDRAW_FEE_DECAY_TIME. * @param user address you want to calculate withdraw fee of * @return current withdraw fee of the user */ function calculateCurrentWithdrawFee(Swap storage self, address user) external view returns (uint256) { return _calculateCurrentWithdrawFee(self, user); } function _calculateCurrentWithdrawFee(Swap storage self, address user) internal view returns (uint256) { uint256 endTime = self.depositTimestamp[user].add(WITHDRAW_FEE_DECAY_TIME); if (endTime > block.timestamp) { uint256 timeLeftover = endTime.sub(block.timestamp); return self .defaultWithdrawFee .mul(self.withdrawFeeMultiplier[user]) .mul(timeLeftover) .div(WITHDRAW_FEE_DECAY_TIME) .div(FEE_DENOMINATOR); } return 0; } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param self Swap struct to read from * @param account address of the account depositing or withdrawing tokens * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return if deposit was true, total amount of lp token that will be minted and if * deposit was false, total amount of lp token that will be burned */ function calculateTokenAmount( Swap storage self, address account, uint256[] calldata amounts, bool deposit ) external view returns (uint256) { uint256 a = _getAPrecise(self); uint256[] memory balances = self.balances; uint256[] memory multipliers = self.tokenPrecisionMultipliers; uint256 d0 = getD(_xp(balances, multipliers), a); for (uint256 i = 0; i < balances.length; i++) { if (deposit) { balances[i] = balances[i].add(amounts[i]); } else { balances[i] = balances[i].sub( amounts[i], "Cannot withdraw more than available" ); } } uint256 d1 = getD(_xp(balances, multipliers), a); uint256 totalSupply = self.lpToken.totalSupply(); if (deposit) { return d1.sub(d0).mul(totalSupply).div(d0); } else { return d0.sub(d1).mul(totalSupply).div(d0).mul(FEE_DENOMINATOR).div( FEE_DENOMINATOR.sub( _calculateCurrentWithdrawFee(self, account) ) ); } } /** * @notice return accumulated amount of admin fees of the token with given index * @param self Swap struct to read from * @param index Index of the pooled token * @return admin balance in the token's precision */ function getAdminBalance(Swap storage self, uint256 index) external view returns (uint256) { require(index < self.pooledTokens.length, "Token index out of range"); return self.pooledTokens[index].balanceOf(address(this)).sub( self.balances[index] ); } /** * @notice internal helper function to calculate fee per token multiplier used in * swap fee calculations * @param swapFee swap fee for the tokens * @param numTokens number of tokens pooled */ function _feePerToken(uint256 swapFee, uint256 numTokens) internal pure returns (uint256) { return swapFee.mul(numTokens).div(numTokens.sub(1).mul(4)); } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice swap two tokens in the pool * @param self Swap struct to read from and write to * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell * @param minDy the min amount the user would like to receive, or revert. * @return amount of token user received on swap */ function swap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy ) external returns (uint256) { { IERC20 tokenFrom = self.pooledTokens[tokenIndexFrom]; require( dx <= tokenFrom.balanceOf(msg.sender), "Cannot swap more than you own" ); // Transfer tokens first to see if a fee was charged on transfer uint256 beforeBalance = tokenFrom.balanceOf(address(this)); tokenFrom.safeTransferFrom(msg.sender, address(this), dx); // Use the actual transferred amount for AMM math dx = tokenFrom.balanceOf(address(this)).sub(beforeBalance); } uint256 dy; uint256 dyFee; uint256[] memory balances = self.balances; (dy, dyFee) = _calculateSwap( self, tokenIndexFrom, tokenIndexTo, dx, balances ); require(dy >= minDy, "Swap didn't result in min tokens"); uint256 dyAdminFee = dyFee.mul(self.adminFee).div(FEE_DENOMINATOR).div( self.tokenPrecisionMultipliers[tokenIndexTo] ); self.balances[tokenIndexFrom] = balances[tokenIndexFrom].add(dx); self.balances[tokenIndexTo] = balances[tokenIndexTo].sub(dy).sub( dyAdminFee ); self.pooledTokens[tokenIndexTo].safeTransfer(msg.sender, dy); emit TokenSwap(msg.sender, dx, dy, tokenIndexFrom, tokenIndexTo); return dy; } /** * @notice Add liquidity to the pool * @param self Swap struct to read from and write to * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * allowed addresses. If the pool is not in the guarded launch phase, this parameter will be ignored. * @return amount of LP token user received */ function addLiquidity( Swap storage self, uint256[] memory amounts, uint256 minToMint ) external returns (uint256) { IERC20[] memory pooledTokens = self.pooledTokens; require( amounts.length == pooledTokens.length, "Amounts must match pooled tokens" ); // current state ManageLiquidityInfo memory v = ManageLiquidityInfo( 0, 0, 0, _getAPrecise(self), self.lpToken, 0, self.balances, self.tokenPrecisionMultipliers ); v.totalSupply = v.lpToken.totalSupply(); if (v.totalSupply != 0) { v.d0 = getD(_xp(v.balances, v.multipliers), v.preciseA); } uint256[] memory newBalances = new uint256[](pooledTokens.length); for (uint256 i = 0; i < pooledTokens.length; i++) { require( v.totalSupply != 0 || amounts[i] > 0, "Must supply all tokens in pool" ); // Transfer tokens first to see if a fee was charged on transfer if (amounts[i] != 0) { uint256 beforeBalance = pooledTokens[i].balanceOf(address(this)); pooledTokens[i].safeTransferFrom( msg.sender, address(this), amounts[i] ); // Update the amounts[] with actual transfer amount amounts[i] = pooledTokens[i].balanceOf(address(this)).sub( beforeBalance ); } newBalances[i] = v.balances[i].add(amounts[i]); } // invariant after change v.d1 = getD(_xp(newBalances, v.multipliers), v.preciseA); require(v.d1 > v.d0, "D should increase"); // updated to reflect fees and calculate the user's LP tokens v.d2 = v.d1; uint256[] memory fees = new uint256[](pooledTokens.length); if (v.totalSupply != 0) { uint256 feePerToken = _feePerToken(self.swapFee, pooledTokens.length); for (uint256 i = 0; i < pooledTokens.length; i++) { uint256 idealBalance = v.d1.mul(v.balances[i]).div(v.d0); fees[i] = feePerToken .mul(idealBalance.difference(newBalances[i])) .div(FEE_DENOMINATOR); self.balances[i] = newBalances[i].sub( fees[i].mul(self.adminFee).div(FEE_DENOMINATOR) ); newBalances[i] = newBalances[i].sub(fees[i]); } v.d2 = getD(_xp(newBalances, v.multipliers), v.preciseA); } else { // the initial depositor doesn't pay fees self.balances = newBalances; } uint256 toMint; if (v.totalSupply == 0) { toMint = v.d1; } else { toMint = v.d2.sub(v.d0).mul(v.totalSupply).div(v.d0); } require(toMint >= minToMint, "Couldn't mint min requested"); // mint the user's LP tokens v.lpToken.mint(msg.sender, toMint); emit AddLiquidity( msg.sender, amounts, fees, v.d1, v.totalSupply.add(toMint) ); return toMint; } /** * @notice Update the withdraw fee for `user`. If the user is currently * not providing liquidity in the pool, sets to default value. If not, recalculate * the starting withdraw fee based on the last deposit's time & amount relative * to the new deposit. * * @param self Swap struct to read from and write to * @param user address of the user depositing tokens * @param toMint amount of pool tokens to be minted */ function updateUserWithdrawFee( Swap storage self, address user, uint256 toMint ) public { // If token is transferred to address 0 (or burned), don't update the fee. if (user == address(0)) { return; } if (self.defaultWithdrawFee == 0) { // If current fee is set to 0%, set multiplier to FEE_DENOMINATOR self.withdrawFeeMultiplier[user] = FEE_DENOMINATOR; } else { // Otherwise, calculate appropriate discount based on last deposit amount uint256 currentFee = _calculateCurrentWithdrawFee(self, user); uint256 currentBalance = self.lpToken.balanceOf(user); // ((currentBalance * currentFee) + (toMint * defaultWithdrawFee)) * FEE_DENOMINATOR / // ((toMint + currentBalance) * defaultWithdrawFee) self.withdrawFeeMultiplier[user] = currentBalance .mul(currentFee) .add(toMint.mul(self.defaultWithdrawFee)) .mul(FEE_DENOMINATOR) .div(toMint.add(currentBalance).mul(self.defaultWithdrawFee)); } self.depositTimestamp[user] = block.timestamp; } /** * @notice Burn LP tokens to remove liquidity from the pool. * @dev Liquidity can always be removed, even when the pool is paused. * @param self Swap struct to read from and write to * @param amount the amount of LP tokens to burn * @param minAmounts the minimum amounts of each token in the pool * acceptable for this burn. Useful as a front-running mitigation * @return amounts of tokens the user received */ function removeLiquidity( Swap storage self, uint256 amount, uint256[] calldata minAmounts ) external returns (uint256[] memory) { LPToken lpToken = self.lpToken; IERC20[] memory pooledTokens = self.pooledTokens; require(amount <= lpToken.balanceOf(msg.sender), ">LP.balanceOf"); require( minAmounts.length == pooledTokens.length, "minAmounts must match poolTokens" ); uint256[] memory balances = self.balances; uint256 totalSupply = lpToken.totalSupply(); uint256[] memory amounts = _calculateRemoveLiquidity( self, balances, msg.sender, amount, totalSupply ); for (uint256 i = 0; i < amounts.length; i++) { require(amounts[i] >= minAmounts[i], "amounts[i] < minAmounts[i]"); self.balances[i] = balances[i].sub(amounts[i]); pooledTokens[i].safeTransfer(msg.sender, amounts[i]); } lpToken.burnFrom(msg.sender, amount); emit RemoveLiquidity(msg.sender, amounts, totalSupply.sub(amount)); return amounts; } /** * @notice Remove liquidity from the pool all in one token. * @param self Swap struct to read from and write to * @param tokenAmount the amount of the lp tokens to burn * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @return amount chosen token that user received */ function removeLiquidityOneToken( Swap storage self, uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount ) external returns (uint256) { LPToken lpToken = self.lpToken; IERC20[] memory pooledTokens = self.pooledTokens; require(tokenAmount <= lpToken.balanceOf(msg.sender), ">LP.balanceOf"); require(tokenIndex < pooledTokens.length, "Token not found"); uint256 totalSupply = lpToken.totalSupply(); (uint256 dy, uint256 dyFee) = _calculateWithdrawOneToken( self, msg.sender, tokenAmount, tokenIndex, totalSupply ); require(dy >= minAmount, "dy < minAmount"); self.balances[tokenIndex] = self.balances[tokenIndex].sub( dy.add(dyFee.mul(self.adminFee).div(FEE_DENOMINATOR)) ); lpToken.burnFrom(msg.sender, tokenAmount); pooledTokens[tokenIndex].safeTransfer(msg.sender, dy); emit RemoveLiquidityOne( msg.sender, tokenAmount, totalSupply, tokenIndex, dy ); return dy; } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. * * @param self Swap struct to read from and write to * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @return actual amount of LP tokens burned in the withdrawal */ function removeLiquidityImbalance( Swap storage self, uint256[] memory amounts, uint256 maxBurnAmount ) public returns (uint256) { ManageLiquidityInfo memory v = ManageLiquidityInfo( 0, 0, 0, _getAPrecise(self), self.lpToken, 0, self.balances, self.tokenPrecisionMultipliers ); v.totalSupply = v.lpToken.totalSupply(); IERC20[] memory pooledTokens = self.pooledTokens; require( amounts.length == pooledTokens.length, "Amounts should match pool tokens" ); require( maxBurnAmount <= v.lpToken.balanceOf(msg.sender) && maxBurnAmount != 0, ">LP.balanceOf" ); uint256 feePerToken = _feePerToken(self.swapFee, pooledTokens.length); uint256[] memory fees = new uint256[](pooledTokens.length); { uint256[] memory balances1 = new uint256[](pooledTokens.length); v.d0 = getD(_xp(v.balances, v.multipliers), v.preciseA); for (uint256 i = 0; i < pooledTokens.length; i++) { balances1[i] = v.balances[i].sub( amounts[i], "Cannot withdraw more than available" ); } v.d1 = getD(_xp(balances1, v.multipliers), v.preciseA); for (uint256 i = 0; i < pooledTokens.length; i++) { uint256 idealBalance = v.d1.mul(v.balances[i]).div(v.d0); uint256 difference = idealBalance.difference(balances1[i]); fees[i] = feePerToken.mul(difference).div(FEE_DENOMINATOR); self.balances[i] = balances1[i].sub( fees[i].mul(self.adminFee).div(FEE_DENOMINATOR) ); balances1[i] = balances1[i].sub(fees[i]); } v.d2 = getD(_xp(balances1, v.multipliers), v.preciseA); } uint256 tokenAmount = v.d0.sub(v.d2).mul(v.totalSupply).div(v.d0); require(tokenAmount != 0, "Burnt amount cannot be zero"); tokenAmount = tokenAmount.add(1).mul(FEE_DENOMINATOR).div( FEE_DENOMINATOR.sub(_calculateCurrentWithdrawFee(self, msg.sender)) ); require(tokenAmount <= maxBurnAmount, "tokenAmount > maxBurnAmount"); v.lpToken.burnFrom(msg.sender, tokenAmount); for (uint256 i = 0; i < pooledTokens.length; i++) { pooledTokens[i].safeTransfer(msg.sender, amounts[i]); } emit RemoveLiquidityImbalance( msg.sender, amounts, fees, v.d1, v.totalSupply.sub(tokenAmount) ); return tokenAmount; } /** * @notice withdraw all admin fees to a given address * @param self Swap struct to withdraw fees from * @param to Address to send the fees to */ function withdrawAdminFees(Swap storage self, address to) external { IERC20[] memory pooledTokens = self.pooledTokens; for (uint256 i = 0; i < pooledTokens.length; i++) { IERC20 token = pooledTokens[i]; uint256 balance = token.balanceOf(address(this)).sub(self.balances[i]); if (balance != 0) { token.safeTransfer(to, balance); } } } /** * @notice Sets the admin fee * @dev adminFee cannot be higher than 100% of the swap fee * @param self Swap struct to update * @param newAdminFee new admin fee to be applied on future transactions */ function setAdminFee(Swap storage self, uint256 newAdminFee) external { require(newAdminFee <= MAX_ADMIN_FEE, "Fee is too high"); self.adminFee = newAdminFee; emit NewAdminFee(newAdminFee); } /** * @notice update the swap fee * @dev fee cannot be higher than 1% of each swap * @param self Swap struct to update * @param newSwapFee new swap fee to be applied on future transactions */ function setSwapFee(Swap storage self, uint256 newSwapFee) external { require(newSwapFee <= MAX_SWAP_FEE, "Fee is too high"); self.swapFee = newSwapFee; emit NewSwapFee(newSwapFee); } /** * @notice update the default withdraw fee. This also affects deposits made in the past as well. * @param self Swap struct to update * @param newWithdrawFee new withdraw fee to be applied */ function setDefaultWithdrawFee(Swap storage self, uint256 newWithdrawFee) external { require(newWithdrawFee <= MAX_WITHDRAW_FEE, "Fee is too high"); self.defaultWithdrawFee = newWithdrawFee; emit NewWithdrawFee(newWithdrawFee); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; interface ISwap { // pool data view functions function getA() external view returns (uint256); function getToken(uint8 index) external view returns (IERC20); function getTokenIndex(address tokenAddress) external view returns (uint8); function getTokenBalance(uint8 index) external view returns (uint256); function getVirtualPrice() external view returns (uint256); // min return calculation functions function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256); function calculateTokenAmount( address account, uint256[] calldata amounts, bool deposit ) external view returns (uint256); function calculateRemoveLiquidity(address account, uint256 amount) external view returns (uint256[] memory); function calculateRemoveLiquidityOneToken( address account, uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256 availableTokenAmount); // state modifying functions function initialize( IERC20[] memory pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 a, uint256 fee, uint256 adminFee, uint256 withdrawFee, address lpTokenTargetAddress ) external; function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external returns (uint256); function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline ) external returns (uint256); function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external returns (uint256[] memory); function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external returns (uint256); function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external returns (uint256); // withdraw fee update function function updateUserWithdrawFee(address recipient, uint256 transferAmount) external; }
* @notice Get D, the StableSwap invariant, based on a set of balances and a particular A. @param xp a precision-adjusted set of pool balances. Array should be the same cardinality as the pool. @param a the amplification coefficient n (n - 1) in A_PRECISION. See the StableSwap paper for details @return the invariant, at the precision of the pool/ If we were to protect the division loss we would have to keep the denominator separate and divide at the end. However this leads to overflow with large numTokens or/and D. dP = dP * D * D * D * ... overflow!
function getD(uint256[] memory xp, uint256 a) internal pure returns (uint256) { uint256 numTokens = xp.length; uint256 s; for (uint256 i = 0; i < numTokens; i++) { s = s.add(xp[i]); } if (s == 0) { return 0; } uint256 prevD; uint256 d = s; uint256 nA = a.mul(numTokens); for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { uint256 dP = d; for (uint256 j = 0; j < numTokens; j++) { dP = dP.mul(d).div(xp[j].mul(numTokens)); } prevD = d; d = nA .mul(s) .div(AmplificationUtils.A_PRECISION) .add(dP.mul(numTokens)) .mul(d) .div( nA .sub(AmplificationUtils.A_PRECISION) .mul(d) .div(AmplificationUtils.A_PRECISION) .add(numTokens.add(1).mul(dP)) ); if (d.within1(prevD)) { return d; } } }
35,171
[ 1, 967, 463, 16, 326, 934, 429, 12521, 22514, 16, 2511, 603, 279, 444, 434, 324, 26488, 471, 279, 6826, 432, 18, 225, 13681, 279, 6039, 17, 13362, 329, 444, 434, 2845, 324, 26488, 18, 1510, 1410, 506, 326, 1967, 14379, 487, 326, 2845, 18, 225, 279, 326, 2125, 412, 1480, 16554, 225, 290, 225, 261, 82, 300, 404, 13, 316, 432, 67, 3670, 26913, 18, 2164, 326, 934, 429, 12521, 15181, 364, 3189, 327, 326, 22514, 16, 622, 326, 6039, 434, 326, 2845, 19, 971, 732, 4591, 358, 17151, 326, 16536, 8324, 732, 4102, 1240, 358, 3455, 326, 15030, 9004, 471, 12326, 622, 326, 679, 18, 10724, 333, 5871, 87, 358, 9391, 598, 7876, 818, 5157, 578, 19, 464, 463, 18, 27695, 273, 27695, 225, 463, 225, 463, 225, 463, 225, 1372, 9391, 5, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2343, 12, 11890, 5034, 8526, 3778, 13681, 16, 2254, 5034, 279, 13, 203, 3639, 2713, 203, 3639, 16618, 203, 3639, 1135, 261, 11890, 5034, 13, 203, 565, 288, 203, 3639, 2254, 5034, 818, 5157, 273, 13681, 18, 2469, 31, 203, 3639, 2254, 5034, 272, 31, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 818, 5157, 31, 277, 27245, 288, 203, 5411, 272, 273, 272, 18, 1289, 12, 23829, 63, 77, 19226, 203, 3639, 289, 203, 3639, 309, 261, 87, 422, 374, 13, 288, 203, 5411, 327, 374, 31, 203, 3639, 289, 203, 203, 3639, 2254, 5034, 2807, 40, 31, 203, 3639, 2254, 5034, 302, 273, 272, 31, 203, 3639, 2254, 5034, 290, 37, 273, 279, 18, 16411, 12, 2107, 5157, 1769, 203, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 4552, 67, 28677, 67, 8283, 31, 277, 27245, 288, 203, 5411, 2254, 5034, 27695, 273, 302, 31, 203, 5411, 364, 261, 11890, 5034, 525, 273, 374, 31, 525, 411, 818, 5157, 31, 525, 27245, 288, 203, 7734, 27695, 273, 27695, 18, 16411, 12, 72, 2934, 2892, 12, 23829, 63, 78, 8009, 16411, 12, 2107, 5157, 10019, 203, 5411, 289, 203, 5411, 2807, 40, 273, 302, 31, 203, 5411, 302, 273, 290, 37, 203, 7734, 263, 16411, 12, 87, 13, 203, 7734, 263, 2892, 12, 9864, 412, 1480, 1989, 18, 37, 67, 3670, 26913, 13, 203, 7734, 263, 1289, 12, 72, 52, 18, 16411, 12, 2107, 5157, 3719, 203, 7734, 263, 16411, 12, 72, 13, 2 ]
./full_match/3/0xD7b903AC1D7818b9712162cC47565429A5595EE6/sources/browser/github/NEST-Protocol/NEST-oracle-V3/VoteContract/Nest_3_VoteFactory.sol
Voting factory contract
Nest_3_VoteFactory _voteFactory;
8,162,179
[ 1, 58, 17128, 3272, 6835, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 423, 395, 67, 23, 67, 19338, 1733, 389, 25911, 1733, 31, 5397, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol pragma solidity ^0.4.24; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * See https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol pragma solidity ^0.4.24; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address _owner, address _spender) public view returns (uint256); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: openzeppelin-solidity/contracts/math/SafeMath.sol pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } c = _a * _b; assert(c / _a == _b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } } // File: contracts/Utils/Ownable.sol pragma solidity ^0.4.24; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner, "msg.sender not owner"); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0), "_newOwner == 0"); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } // File: contracts/Utils/Destructible.sol pragma solidity ^0.4.24; /** * @title Destructible * @dev Base contract that can be destroyed by owner. All funds in contract will be sent to the owner. */ contract Destructible is Ownable { /** * @dev Transfers the current balance to the owner and terminates the contract. */ function destroy() public onlyOwner { selfdestruct(owner); } function destroyAndSend(address _recipient) public onlyOwner { selfdestruct(_recipient); } } // File: contracts/Interfaces/IWallet.sol pragma solidity ^0.4.24; /** * @title Wallet interface. * @dev The interface of the SC that own the assets. */ interface IWallet { function transferAssetTo( address _assetAddress, address _to, uint _amount ) external payable returns (bool); function withdrawAsset( address _assetAddress, uint _amount ) external returns (bool); function setTokenSwapAllowance ( address _tokenSwapAddress, bool _allowance ) external returns(bool); } // File: contracts/Utils/Pausable.sol pragma solidity ^0.4.24; /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused, "The contract is paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused, "The contract is not paused"); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyOwner whenNotPaused { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner whenPaused { paused = false; emit Unpause(); } } // File: contracts/Interfaces/IBadERC20.sol pragma solidity ^0.4.24; /** * @title Bad formed ERC20 token interface. * @dev The interface of the a bad formed ERC20 token. */ interface IBadERC20 { function transfer(address to, uint256 value) external; function approve(address spender, uint256 value) external; function transferFrom( address from, address to, uint256 value ) external; function totalSupply() external view returns (uint256); function balanceOf( address who ) external view returns (uint256); function allowance( address owner, address spender ) external view returns (uint256); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: contracts/Utils/SafeTransfer.sol pragma solidity ^0.4.24; /** * @title SafeTransfer * @dev Transfer Bad ERC20 tokens */ library SafeTransfer { /** * @dev Wrapping the ERC20 transferFrom function to avoid missing returns. * @param _tokenAddress The address of bad formed ERC20 token. * @param _from Transfer sender. * @param _to Transfer receiver. * @param _value Amount to be transfered. * @return Success of the safeTransferFrom. */ function _safeTransferFrom( address _tokenAddress, address _from, address _to, uint256 _value ) internal returns (bool result) { IBadERC20(_tokenAddress).transferFrom(_from, _to, _value); assembly { switch returndatasize() case 0 { // This is our BadToken result := not(0) // result is true } case 32 { // This is our GoodToken returndatacopy(0, 0, 32) result := mload(0) // result == returndata of external call } default { // This is not an ERC20 token revert(0, 0) } } } /** * @dev Wrapping the ERC20 transfer function to avoid missing returns. * @param _tokenAddress The address of bad formed ERC20 token. * @param _to Transfer receiver. * @param _amount Amount to be transfered. * @return Success of the safeTransfer. */ function _safeTransfer( address _tokenAddress, address _to, uint _amount ) internal returns (bool result) { IBadERC20(_tokenAddress).transfer(_to, _amount); assembly { switch returndatasize() case 0 { // This is our BadToken result := not(0) // result is true } case 32 { // This is our GoodToken returndatacopy(0, 0, 32) result := mload(0) // result == returndata of external call } default { // This is not an ERC20 token revert(0, 0) } } } } // File: contracts/TokenSwap.sol pragma solidity ^0.4.24; /** * @title TokenSwap. * @author Eidoo SAGL. * @dev A swap asset contract. The offerAmount and wantAmount are collected and sent into the contract itself. */ contract TokenSwap is Pausable, Destructible { using SafeMath for uint; address public baseTokenAddress; address public quoteTokenAddress; address public wallet; uint public buyRate; uint public buyRateDecimals; uint public sellRate; uint public sellRateDecimals; event LogWithdrawToken( address indexed _from, address indexed _token, uint amount ); event LogSetWallet(address indexed _wallet); event LogSetBaseTokenAddress(address indexed _token); event LogSetQuoteTokenAddress(address indexed _token); event LogSetRateAndRateDecimals( uint _buyRate, uint _buyRateDecimals, uint _sellRate, uint _sellRateDecimals ); event LogSetNumberOfZeroesFromLastDigit( uint _numberOfZeroesFromLastDigit ); event LogTokenSwap( address indexed _userAddress, address indexed _userSentTokenAddress, uint _userSentTokenAmount, address indexed _userReceivedTokenAddress, uint _userReceivedTokenAmount ); /** * @dev Contract constructor. * @param _baseTokenAddress The base of the swap pair. * @param _quoteTokenAddress The quote of the swap pair. * @param _buyRate Purchase rate, how many baseToken for the given quoteToken. * @param _buyRateDecimals Define the decimals precision for the given asset. * @param _sellRate Purchase rate, how many quoteToken for the given baseToken. * @param _sellRateDecimals Define the decimals precision for the given asset. */ constructor( address _baseTokenAddress, address _quoteTokenAddress, address _wallet, uint _buyRate, uint _buyRateDecimals, uint _sellRate, uint _sellRateDecimals ) public { require(_wallet != address(0), "_wallet == address(0)"); baseTokenAddress = _baseTokenAddress; quoteTokenAddress = _quoteTokenAddress; wallet = _wallet; buyRate = _buyRate; buyRateDecimals = _buyRateDecimals; sellRate = _sellRate; sellRateDecimals = _sellRateDecimals; } function() external { revert("fallback function not allowed"); } /** * @dev Set base token address. * @param _baseTokenAddress The pair base token address. * @return bool. */ function setBaseTokenAddress(address _baseTokenAddress) public onlyOwner returns (bool) { baseTokenAddress = _baseTokenAddress; emit LogSetBaseTokenAddress(_baseTokenAddress); return true; } /** * @dev Set quote token address. * @param _quoteTokenAddress The quote token address. * @return bool. */ function setQuoteTokenAddress(address _quoteTokenAddress) public onlyOwner returns (bool) { quoteTokenAddress = _quoteTokenAddress; emit LogSetQuoteTokenAddress(_quoteTokenAddress); return true; } /** * @dev Set wallet sc address. * @param _wallet The wallet sc address. * @return bool. */ function setWallet(address _wallet) public onlyOwner returns (bool) { require(_wallet != address(0), "_wallet == address(0)"); wallet = _wallet; emit LogSetWallet(_wallet); return true; } /** * @dev Set rate. * @param _buyRate Multiplier, how many base token for the quote token. * @param _buyRateDecimals Number of significan digits of the rate. * @param _sellRate Multiplier, how many quote token for the base token. * @param _sellRateDecimals Number of significan digits of the rate. * @return bool. */ function setRateAndRateDecimals( uint _buyRate, uint _buyRateDecimals, uint _sellRate, uint _sellRateDecimals ) public onlyOwner returns (bool) { require(_buyRate != buyRate, "_buyRate == buyRate"); require(_buyRate != 0, "_buyRate == 0"); require(_sellRate != sellRate, "_sellRate == sellRate"); require(_sellRate != 0, "_sellRate == 0"); buyRate = _buyRate; sellRate = _sellRate; buyRateDecimals = _buyRateDecimals; sellRateDecimals = _sellRateDecimals; emit LogSetRateAndRateDecimals( _buyRate, _buyRateDecimals, _sellRate, _sellRateDecimals ); return true; } /** * @dev Withdraw asset. * @param _tokenAddress Asset to be withdrawed. * @return bool. */ function withdrawToken(address _tokenAddress) public onlyOwner returns(bool) { uint tokenBalance; if (isETH(_tokenAddress)) { tokenBalance = address(this).balance; msg.sender.transfer(tokenBalance); } else { tokenBalance = ERC20(_tokenAddress).balanceOf(address(this)); require( SafeTransfer._safeTransfer(_tokenAddress, msg.sender, tokenBalance), "withdraw transfer failed" ); } emit LogWithdrawToken(msg.sender, _tokenAddress, tokenBalance); return true; } /** * @dev Understand if the user swap request is a BUY or a SELL. * @param _offerTokenAddress The token address the purchaser is offering (It may be the quote or the base). * @return bool. */ function isBuy(address _offerTokenAddress) public view returns (bool) { return _offerTokenAddress == quoteTokenAddress; } /** * @dev Understand if the token is ETH or not. * @param _tokenAddress The token address the purchaser is offering (It may be the quote or the base). * @return bool. */ function isETH(address _tokenAddress) public pure returns (bool) { return _tokenAddress == address(0); } /** * @dev Understand if the user swap request is for the available pair. * @param _offerTokenAddress The token address the purchaser is offering (It may be the quote or the base). * @return bool. */ function isOfferInPair(address _offerTokenAddress) public view returns (bool) { return _offerTokenAddress == quoteTokenAddress || _offerTokenAddress == baseTokenAddress; } /** * @dev Function to calculate the number of tokens the user is going to receive. * @param _offerTokenAmount The amount of tokne number of WEI to convert in ERC20. * @return uint. */ function getAmount( uint _offerTokenAmount, bool _isBuy ) public view returns(uint) { uint amount; if (_isBuy) { amount = _offerTokenAmount.mul(buyRate).div(10 ** buyRateDecimals); } else { amount = _offerTokenAmount.mul(sellRate).div(10 ** sellRateDecimals); } return amount; } /** * @dev Release purchased asset to the buyer based on pair rate. * @param _userOfferTokenAddress The token address the purchaser is offering (It may be the quote or the base). * @param _userOfferTokenAmount The amount of token the user want to swap. * @return bool. */ function swapToken ( address _userOfferTokenAddress, uint _userOfferTokenAmount ) public whenNotPaused payable returns (bool) { require(_userOfferTokenAmount != 0, "_userOfferTokenAmount == 0"); // check if offered token address is the base or the quote token address require( isOfferInPair(_userOfferTokenAddress), "_userOfferTokenAddress not in pair" ); // check if the msg.value is consistent when offered token address is eth if (isETH(_userOfferTokenAddress)) { require(_userOfferTokenAmount == msg.value, "msg.value != _userOfferTokenAmount"); } else { require(msg.value == 0, "msg.value != 0"); } bool isUserBuy = isBuy(_userOfferTokenAddress); uint toWalletAmount = _userOfferTokenAmount; uint toUserAmount = getAmount( _userOfferTokenAmount, isUserBuy ); require(toUserAmount > 0, "toUserAmount must be greater than 0"); if (isUserBuy) { // send the quote to wallet require( _transferAmounts( msg.sender, wallet, quoteTokenAddress, toWalletAmount ), "the transfer from of the quote the user to the TokenSwap SC failed" ); // send the base to user require( _transferAmounts( wallet, msg.sender, baseTokenAddress, toUserAmount ), "the transfer of the base from the TokenSwap SC to the user failed" ); emit LogTokenSwap( msg.sender, quoteTokenAddress, toWalletAmount, baseTokenAddress, toUserAmount ); } else { // send the base to wallet require( _transferAmounts( msg.sender, wallet, baseTokenAddress, toWalletAmount ), "the transfer of the base from the user to the TokenSwap SC failed" ); // send the quote to user require( _transferAmounts( wallet, msg.sender, quoteTokenAddress, toUserAmount ), "the transfer of the quote from the TokenSwap SC to the user failed" ); emit LogTokenSwap( msg.sender, baseTokenAddress, toWalletAmount, quoteTokenAddress, toUserAmount ); } return true; } /** * @dev Transfer amounts from user to this contract and vice versa. * @param _from The 'from' address. * @param _to The 'to' address. * @param _tokenAddress The asset to be transfer. * @param _amount The amount to be transfer. * @return bool. */ function _transferAmounts( address _from, address _to, address _tokenAddress, uint _amount ) private returns (bool) { if (isETH(_tokenAddress)) { if (_from == wallet) { require( IWallet(_from).transferAssetTo( _tokenAddress, _to, _amount ), "trasnsferAssetTo failed" ); } else { _to.transfer(_amount); } } else { if (_from == wallet) { require( IWallet(_from).transferAssetTo( _tokenAddress, _to, _amount ), "trasnsferAssetTo failed" ); } else { require( SafeTransfer._safeTransferFrom( _tokenAddress, _from, _to, _amount ), "transferFrom reserve to _receiver failed" ); } } return true; } }
* @dev Withdraw asset. @param _tokenAddress Asset to be withdrawed. @return bool./
function withdrawToken(address _tokenAddress) public onlyOwner returns(bool) { uint tokenBalance; if (isETH(_tokenAddress)) { tokenBalance = address(this).balance; msg.sender.transfer(tokenBalance); tokenBalance = ERC20(_tokenAddress).balanceOf(address(this)); require( SafeTransfer._safeTransfer(_tokenAddress, msg.sender, tokenBalance), "withdraw transfer failed" ); } emit LogWithdrawToken(msg.sender, _tokenAddress, tokenBalance); return true; }
15,866,030
[ 1, 1190, 9446, 3310, 18, 225, 389, 2316, 1887, 10494, 358, 506, 598, 9446, 329, 18, 327, 1426, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 598, 9446, 1345, 12, 2867, 389, 2316, 1887, 13, 203, 565, 1071, 203, 565, 1338, 5541, 203, 565, 1135, 12, 6430, 13, 203, 225, 288, 203, 565, 2254, 1147, 13937, 31, 203, 565, 309, 261, 291, 1584, 44, 24899, 2316, 1887, 3719, 288, 203, 1377, 1147, 13937, 273, 1758, 12, 2211, 2934, 12296, 31, 203, 1377, 1234, 18, 15330, 18, 13866, 12, 2316, 13937, 1769, 203, 1377, 1147, 13937, 273, 4232, 39, 3462, 24899, 2316, 1887, 2934, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 1377, 2583, 12, 203, 3639, 14060, 5912, 6315, 4626, 5912, 24899, 2316, 1887, 16, 1234, 18, 15330, 16, 1147, 13937, 3631, 203, 3639, 315, 1918, 9446, 7412, 2535, 6, 203, 1377, 11272, 203, 565, 289, 203, 565, 3626, 1827, 1190, 9446, 1345, 12, 3576, 18, 15330, 16, 389, 2316, 1887, 16, 1147, 13937, 1769, 203, 565, 327, 638, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.14; /* Copyright 2017 ZeroEx Intl. 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. */ contract Token { /// @return total amount of tokens function totalSupply() constant returns (uint supply) {} /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint balance) {} /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint _value) returns (bool success) {} /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint _value) returns (bool success) {} /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint _value) returns (bool success) {} /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint remaining) {} event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); } /* * Ownable * * Base contract with an owner. * Provides onlyOwner modifier, which prevents function from running if it is called by anyone other than the owner. */ contract Ownable { address public owner; function Ownable() { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } contract SafeMath { function safeMul(uint a, uint b) internal constant returns (uint256) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function safeDiv(uint a, uint b) internal constant returns (uint256) { uint c = a / b; return c; } function safeSub(uint a, uint b) internal constant returns (uint256) { assert(b <= a); return a - b; } function safeAdd(uint a, uint b) internal constant returns (uint256) { uint c = a + b; assert(c >= a); return c; } function max64(uint64 a, uint64 b) internal constant returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal constant returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal constant returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal constant returns (uint256) { return a < b ? a : b; } } /// @title TokenTransferProxy - Transfers tokens on behalf of contracts that have been approved via decentralized governance. /// @author Amir Bandeali - <[email protected]>, Will Warren - <[email protected]> contract TokenTransferProxy is Ownable { /// @dev Only authorized addresses can invoke functions with this modifier. modifier onlyAuthorized { require(authorized[msg.sender]); _; } modifier targetAuthorized(address target) { require(authorized[target]); _; } modifier targetNotAuthorized(address target) { require(!authorized[target]); _; } mapping (address => bool) public authorized; address[] public authorities; event LogAuthorizedAddressAdded(address indexed target, address indexed caller); event LogAuthorizedAddressRemoved(address indexed target, address indexed caller); /* * Public functions */ /// @dev Authorizes an address. /// @param target Address to authorize. function addAuthorizedAddress(address target) public onlyOwner targetNotAuthorized(target) { authorized[target] = true; authorities.push(target); LogAuthorizedAddressAdded(target, msg.sender); } /// @dev Removes authorizion of an address. /// @param target Address to remove authorization from. function removeAuthorizedAddress(address target) public onlyOwner targetAuthorized(target) { delete authorized[target]; for (uint i = 0; i < authorities.length; i++) { if (authorities[i] == target) { authorities[i] = authorities[authorities.length - 1]; authorities.length -= 1; break; } } LogAuthorizedAddressRemoved(target, msg.sender); } /// @dev Calls into ERC20 Token contract, invoking transferFrom. /// @param token Address of token to transfer. /// @param from Address to transfer token from. /// @param to Address to transfer token to. /// @param value Amount of token to transfer. /// @return Success of transfer. function transferFrom( address token, address from, address to, uint value) public onlyAuthorized returns (bool) { return Token(token).transferFrom(from, to, value); } /* * Public constant functions */ /// @dev Gets all authorized addresses. /// @return Array of authorized addresses. function getAuthorizedAddresses() public constant returns (address[]) { return authorities; } } /// @title Exchange - Facilitates exchange of ERC20 tokens. /// @author Amir Bandeali - <[email protected]>, Will Warren - <[email protected]> contract Exchange is SafeMath { // Error Codes enum Errors { ORDER_EXPIRED, // Order has already expired ORDER_FULLY_FILLED_OR_CANCELLED, // Order has already been fully filled or cancelled ROUNDING_ERROR_TOO_LARGE, // Rounding error too large INSUFFICIENT_BALANCE_OR_ALLOWANCE // Insufficient balance or allowance for token transfer } string constant public VERSION = "1.0.0"; uint16 constant public EXTERNAL_QUERY_GAS_LIMIT = 4999; // Changes to state require at least 5000 gas address public ZRX_TOKEN_CONTRACT; address public TOKEN_TRANSFER_PROXY_CONTRACT; // Mappings of orderHash => amounts of takerTokenAmount filled or cancelled. mapping (bytes32 => uint) public filled; mapping (bytes32 => uint) public cancelled; event LogFill( address indexed maker, address taker, address indexed feeRecipient, address makerToken, address takerToken, uint filledMakerTokenAmount, uint filledTakerTokenAmount, uint paidMakerFee, uint paidTakerFee, bytes32 indexed tokens, // keccak256(makerToken, takerToken), allows subscribing to a token pair bytes32 orderHash ); event LogCancel( address indexed maker, address indexed feeRecipient, address makerToken, address takerToken, uint cancelledMakerTokenAmount, uint cancelledTakerTokenAmount, bytes32 indexed tokens, bytes32 orderHash ); event LogError(uint8 indexed errorId, bytes32 indexed orderHash); struct Order { address maker; address taker; address makerToken; address takerToken; address feeRecipient; uint makerTokenAmount; uint takerTokenAmount; uint makerFee; uint takerFee; uint expirationTimestampInSec; bytes32 orderHash; } function Exchange(address _zrxToken, address _tokenTransferProxy) { ZRX_TOKEN_CONTRACT = _zrxToken; TOKEN_TRANSFER_PROXY_CONTRACT = _tokenTransferProxy; } /* * Core exchange functions */ /// @dev Fills the input order. /// @param orderAddresses Array of order's maker, taker, makerToken, takerToken, and feeRecipient. /// @param orderValues Array of order's makerTokenAmount, takerTokenAmount, makerFee, takerFee, expirationTimestampInSec, and salt. /// @param fillTakerTokenAmount Desired amount of takerToken to fill. /// @param shouldThrowOnInsufficientBalanceOrAllowance Test if transfer will fail before attempting. /// @param v ECDSA signature parameter v. /// @param r ECDSA signature parameters r. /// @param s ECDSA signature parameters s. /// @return Total amount of takerToken filled in trade. function fillOrder( address[5] orderAddresses, uint[6] orderValues, uint fillTakerTokenAmount, bool shouldThrowOnInsufficientBalanceOrAllowance, uint8 v, bytes32 r, bytes32 s) public returns (uint filledTakerTokenAmount) { Order memory order = Order({ maker: orderAddresses[0], taker: orderAddresses[1], makerToken: orderAddresses[2], takerToken: orderAddresses[3], feeRecipient: orderAddresses[4], makerTokenAmount: orderValues[0], takerTokenAmount: orderValues[1], makerFee: orderValues[2], takerFee: orderValues[3], expirationTimestampInSec: orderValues[4], orderHash: getOrderHash(orderAddresses, orderValues) }); require(order.taker == address(0) || order.taker == msg.sender); require(order.makerTokenAmount > 0 && order.takerTokenAmount > 0 && fillTakerTokenAmount > 0); require(isValidSignature( order.maker, order.orderHash, v, r, s )); if (block.timestamp >= order.expirationTimestampInSec) { LogError(uint8(Errors.ORDER_EXPIRED), order.orderHash); return 0; } uint remainingTakerTokenAmount = safeSub(order.takerTokenAmount, getUnavailableTakerTokenAmount(order.orderHash)); filledTakerTokenAmount = min256(fillTakerTokenAmount, remainingTakerTokenAmount); if (filledTakerTokenAmount == 0) { LogError(uint8(Errors.ORDER_FULLY_FILLED_OR_CANCELLED), order.orderHash); return 0; } if (isRoundingError(filledTakerTokenAmount, order.takerTokenAmount, order.makerTokenAmount)) { LogError(uint8(Errors.ROUNDING_ERROR_TOO_LARGE), order.orderHash); return 0; } if (!shouldThrowOnInsufficientBalanceOrAllowance && !isTransferable(order, filledTakerTokenAmount)) { LogError(uint8(Errors.INSUFFICIENT_BALANCE_OR_ALLOWANCE), order.orderHash); return 0; } uint filledMakerTokenAmount = getPartialAmount(filledTakerTokenAmount, order.takerTokenAmount, order.makerTokenAmount); uint paidMakerFee; uint paidTakerFee; filled[order.orderHash] = safeAdd(filled[order.orderHash], filledTakerTokenAmount); require(transferViaTokenTransferProxy( order.makerToken, order.maker, msg.sender, filledMakerTokenAmount )); require(transferViaTokenTransferProxy( order.takerToken, msg.sender, order.maker, filledTakerTokenAmount )); if (order.feeRecipient != address(0)) { if (order.makerFee > 0) { paidMakerFee = getPartialAmount(filledTakerTokenAmount, order.takerTokenAmount, order.makerFee); require(transferViaTokenTransferProxy( ZRX_TOKEN_CONTRACT, order.maker, order.feeRecipient, paidMakerFee )); } if (order.takerFee > 0) { paidTakerFee = getPartialAmount(filledTakerTokenAmount, order.takerTokenAmount, order.takerFee); require(transferViaTokenTransferProxy( ZRX_TOKEN_CONTRACT, msg.sender, order.feeRecipient, paidTakerFee )); } } LogFill( order.maker, msg.sender, order.feeRecipient, order.makerToken, order.takerToken, filledMakerTokenAmount, filledTakerTokenAmount, paidMakerFee, paidTakerFee, keccak256(order.makerToken, order.takerToken), order.orderHash ); return filledTakerTokenAmount; } /// @dev Cancels the input order. /// @param orderAddresses Array of order's maker, taker, makerToken, takerToken, and feeRecipient. /// @param orderValues Array of order's makerTokenAmount, takerTokenAmount, makerFee, takerFee, expirationTimestampInSec, and salt. /// @param cancelTakerTokenAmount Desired amount of takerToken to cancel in order. /// @return Amount of takerToken cancelled. function cancelOrder( address[5] orderAddresses, uint[6] orderValues, uint cancelTakerTokenAmount) public returns (uint) { Order memory order = Order({ maker: orderAddresses[0], taker: orderAddresses[1], makerToken: orderAddresses[2], takerToken: orderAddresses[3], feeRecipient: orderAddresses[4], makerTokenAmount: orderValues[0], takerTokenAmount: orderValues[1], makerFee: orderValues[2], takerFee: orderValues[3], expirationTimestampInSec: orderValues[4], orderHash: getOrderHash(orderAddresses, orderValues) }); require(order.maker == msg.sender); require(order.makerTokenAmount > 0 && order.takerTokenAmount > 0 && cancelTakerTokenAmount > 0); if (block.timestamp >= order.expirationTimestampInSec) { LogError(uint8(Errors.ORDER_EXPIRED), order.orderHash); return 0; } uint remainingTakerTokenAmount = safeSub(order.takerTokenAmount, getUnavailableTakerTokenAmount(order.orderHash)); uint cancelledTakerTokenAmount = min256(cancelTakerTokenAmount, remainingTakerTokenAmount); if (cancelledTakerTokenAmount == 0) { LogError(uint8(Errors.ORDER_FULLY_FILLED_OR_CANCELLED), order.orderHash); return 0; } cancelled[order.orderHash] = safeAdd(cancelled[order.orderHash], cancelledTakerTokenAmount); LogCancel( order.maker, order.feeRecipient, order.makerToken, order.takerToken, getPartialAmount(cancelledTakerTokenAmount, order.takerTokenAmount, order.makerTokenAmount), cancelledTakerTokenAmount, keccak256(order.makerToken, order.takerToken), order.orderHash ); return cancelledTakerTokenAmount; } /* * Wrapper functions */ /// @dev Fills an order with specified parameters and ECDSA signature, throws if specified amount not filled entirely. /// @param orderAddresses Array of order's maker, taker, makerToken, takerToken, and feeRecipient. /// @param orderValues Array of order's makerTokenAmount, takerTokenAmount, makerFee, takerFee, expirationTimestampInSec, and salt. /// @param fillTakerTokenAmount Desired amount of takerToken to fill. /// @param v ECDSA signature parameter v. /// @param r ECDSA signature parameters r. /// @param s ECDSA signature parameters s. function fillOrKillOrder( address[5] orderAddresses, uint[6] orderValues, uint fillTakerTokenAmount, uint8 v, bytes32 r, bytes32 s) public { require(fillOrder( orderAddresses, orderValues, fillTakerTokenAmount, false, v, r, s ) == fillTakerTokenAmount); } /// @dev Synchronously executes multiple fill orders in a single transaction. /// @param orderAddresses Array of address arrays containing individual order addresses. /// @param orderValues Array of uint arrays containing individual order values. /// @param fillTakerTokenAmounts Array of desired amounts of takerToken to fill in orders. /// @param shouldThrowOnInsufficientBalanceOrAllowance Test if transfers will fail before attempting. /// @param v Array ECDSA signature v parameters. /// @param r Array of ECDSA signature r parameters. /// @param s Array of ECDSA signature s parameters. function batchFillOrders( address[5][] orderAddresses, uint[6][] orderValues, uint[] fillTakerTokenAmounts, bool shouldThrowOnInsufficientBalanceOrAllowance, uint8[] v, bytes32[] r, bytes32[] s) public { for (uint i = 0; i < orderAddresses.length; i++) { fillOrder( orderAddresses[i], orderValues[i], fillTakerTokenAmounts[i], shouldThrowOnInsufficientBalanceOrAllowance, v[i], r[i], s[i] ); } } /// @dev Synchronously executes multiple fillOrKill orders in a single transaction. /// @param orderAddresses Array of address arrays containing individual order addresses. /// @param orderValues Array of uint arrays containing individual order values. /// @param fillTakerTokenAmounts Array of desired amounts of takerToken to fill in orders. /// @param v Array ECDSA signature v parameters. /// @param r Array of ECDSA signature r parameters. /// @param s Array of ECDSA signature s parameters. function batchFillOrKillOrders( address[5][] orderAddresses, uint[6][] orderValues, uint[] fillTakerTokenAmounts, uint8[] v, bytes32[] r, bytes32[] s) public { for (uint i = 0; i < orderAddresses.length; i++) { fillOrKillOrder( orderAddresses[i], orderValues[i], fillTakerTokenAmounts[i], v[i], r[i], s[i] ); } } /// @dev Synchronously executes multiple fill orders in a single transaction until total fillTakerTokenAmount filled. /// @param orderAddresses Array of address arrays containing individual order addresses. /// @param orderValues Array of uint arrays containing individual order values. /// @param fillTakerTokenAmount Desired total amount of takerToken to fill in orders. /// @param shouldThrowOnInsufficientBalanceOrAllowance Test if transfers will fail before attempting. /// @param v Array ECDSA signature v parameters. /// @param r Array of ECDSA signature r parameters. /// @param s Array of ECDSA signature s parameters. /// @return Total amount of fillTakerTokenAmount filled in orders. function fillOrdersUpTo( address[5][] orderAddresses, uint[6][] orderValues, uint fillTakerTokenAmount, bool shouldThrowOnInsufficientBalanceOrAllowance, uint8[] v, bytes32[] r, bytes32[] s) public returns (uint) { uint filledTakerTokenAmount = 0; for (uint i = 0; i < orderAddresses.length; i++) { require(orderAddresses[i][3] == orderAddresses[0][3]); // takerToken must be the same for each order filledTakerTokenAmount = safeAdd(filledTakerTokenAmount, fillOrder( orderAddresses[i], orderValues[i], safeSub(fillTakerTokenAmount, filledTakerTokenAmount), shouldThrowOnInsufficientBalanceOrAllowance, v[i], r[i], s[i] )); if (filledTakerTokenAmount == fillTakerTokenAmount) break; } return filledTakerTokenAmount; } /// @dev Synchronously cancels multiple orders in a single transaction. /// @param orderAddresses Array of address arrays containing individual order addresses. /// @param orderValues Array of uint arrays containing individual order values. /// @param cancelTakerTokenAmounts Array of desired amounts of takerToken to cancel in orders. function batchCancelOrders( address[5][] orderAddresses, uint[6][] orderValues, uint[] cancelTakerTokenAmounts) public { for (uint i = 0; i < orderAddresses.length; i++) { cancelOrder( orderAddresses[i], orderValues[i], cancelTakerTokenAmounts[i] ); } } /* * Constant public functions */ /// @dev Calculates Keccak-256 hash of order with specified parameters. /// @param orderAddresses Array of order's maker, taker, makerToken, takerToken, and feeRecipient. /// @param orderValues Array of order's makerTokenAmount, takerTokenAmount, makerFee, takerFee, expirationTimestampInSec, and salt. /// @return Keccak-256 hash of order. function getOrderHash(address[5] orderAddresses, uint[6] orderValues) public constant returns (bytes32) { return keccak256( address(this), orderAddresses[0], // maker orderAddresses[1], // taker orderAddresses[2], // makerToken orderAddresses[3], // takerToken orderAddresses[4], // feeRecipient orderValues[0], // makerTokenAmount orderValues[1], // takerTokenAmount orderValues[2], // makerFee orderValues[3], // takerFee orderValues[4], // expirationTimestampInSec orderValues[5] // salt ); } /// @dev Verifies that an order signature is valid. /// @param signer address of signer. /// @param hash Signed Keccak-256 hash. /// @param v ECDSA signature parameter v. /// @param r ECDSA signature parameters r. /// @param s ECDSA signature parameters s. /// @return Validity of order signature. function isValidSignature( address signer, bytes32 hash, uint8 v, bytes32 r, bytes32 s) public constant returns (bool) { return signer == ecrecover( keccak256("\x19Ethereum Signed Message:\n32", hash), v, r, s ); } /// @dev Checks if rounding error > 0.1%. /// @param numerator Numerator. /// @param denominator Denominator. /// @param target Value to multiply with numerator/denominator. /// @return Rounding error is present. function isRoundingError(uint numerator, uint denominator, uint target) public constant returns (bool) { uint remainder = mulmod(target, numerator, denominator); if (remainder == 0) return false; // No rounding error. uint errPercentageTimes1000000 = safeDiv( safeMul(remainder, 1000000), safeMul(numerator, target) ); return errPercentageTimes1000000 > 1000; } /// @dev Calculates partial value given a numerator and denominator. /// @param numerator Numerator. /// @param denominator Denominator. /// @param target Value to calculate partial of. /// @return Partial value of target. function getPartialAmount(uint numerator, uint denominator, uint target) public constant returns (uint) { return safeDiv(safeMul(numerator, target), denominator); } /// @dev Calculates the sum of values already filled and cancelled for a given order. /// @param orderHash The Keccak-256 hash of the given order. /// @return Sum of values already filled and cancelled. function getUnavailableTakerTokenAmount(bytes32 orderHash) public constant returns (uint) { return safeAdd(filled[orderHash], cancelled[orderHash]); } /* * Internal functions */ /// @dev Transfers a token using TokenTransferProxy transferFrom function. /// @param token Address of token to transferFrom. /// @param from Address transfering token. /// @param to Address receiving token. /// @param value Amount of token to transfer. /// @return Success of token transfer. function transferViaTokenTransferProxy( address token, address from, address to, uint value) internal returns (bool) { return TokenTransferProxy(TOKEN_TRANSFER_PROXY_CONTRACT).transferFrom(token, from, to, value); } /// @dev Checks if any order transfers will fail. /// @param order Order struct of params that will be checked. /// @param fillTakerTokenAmount Desired amount of takerToken to fill. /// @return Predicted result of transfers. function isTransferable(Order order, uint fillTakerTokenAmount) internal constant // The called token contracts may attempt to change state, but will not be able to due to gas limits on getBalance and getAllowance. returns (bool) { address taker = msg.sender; uint fillMakerTokenAmount = getPartialAmount(fillTakerTokenAmount, order.takerTokenAmount, order.makerTokenAmount); if (order.feeRecipient != address(0)) { bool isMakerTokenZRX = order.makerToken == ZRX_TOKEN_CONTRACT; bool isTakerTokenZRX = order.takerToken == ZRX_TOKEN_CONTRACT; uint paidMakerFee = getPartialAmount(fillTakerTokenAmount, order.takerTokenAmount, order.makerFee); uint paidTakerFee = getPartialAmount(fillTakerTokenAmount, order.takerTokenAmount, order.takerFee); uint requiredMakerZRX = isMakerTokenZRX ? safeAdd(fillMakerTokenAmount, paidMakerFee) : paidMakerFee; uint requiredTakerZRX = isTakerTokenZRX ? safeAdd(fillTakerTokenAmount, paidTakerFee) : paidTakerFee; if ( getBalance(ZRX_TOKEN_CONTRACT, order.maker) < requiredMakerZRX || getAllowance(ZRX_TOKEN_CONTRACT, order.maker) < requiredMakerZRX || getBalance(ZRX_TOKEN_CONTRACT, taker) < requiredTakerZRX || getAllowance(ZRX_TOKEN_CONTRACT, taker) < requiredTakerZRX ) return false; if (!isMakerTokenZRX && ( getBalance(order.makerToken, order.maker) < fillMakerTokenAmount // Don't double check makerToken if ZRX || getAllowance(order.makerToken, order.maker) < fillMakerTokenAmount) ) return false; if (!isTakerTokenZRX && ( getBalance(order.takerToken, taker) < fillTakerTokenAmount // Don't double check takerToken if ZRX || getAllowance(order.takerToken, taker) < fillTakerTokenAmount) ) return false; } else if ( getBalance(order.makerToken, order.maker) < fillMakerTokenAmount || getAllowance(order.makerToken, order.maker) < fillMakerTokenAmount || getBalance(order.takerToken, taker) < fillTakerTokenAmount || getAllowance(order.takerToken, taker) < fillTakerTokenAmount ) return false; return true; } /// @dev Get token balance of an address. /// @param token Address of token. /// @param owner Address of owner. /// @return Token balance of owner. function getBalance(address token, address owner) internal constant // The called token contract may attempt to change state, but will not be able to due to an added gas limit. returns (uint) { return Token(token).balanceOf.gas(EXTERNAL_QUERY_GAS_LIMIT)(owner); // Limit gas to prevent reentrancy } /// @dev Get allowance of token given to TokenTransferProxy by an address. /// @param token Address of token. /// @param owner Address of owner. /// @return Allowance of token given to TokenTransferProxy by owner. function getAllowance(address token, address owner) internal constant // The called token contract may attempt to change state, but will not be able to due to an added gas limit. returns (uint) { return Token(token).allowance.gas(EXTERNAL_QUERY_GAS_LIMIT)(owner, TOKEN_TRANSFER_PROXY_CONTRACT); // Limit gas to prevent reentrancy } } /// @title Standard token contract with overflow protection - Used for tokens with dynamic supply. contract StandardTokenWithOverflowProtection is Token, SafeMath { /* * Data structures */ mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; uint256 public totalSupply; /* * Public functions */ /// @dev Transfers sender's tokens to a given address. Returns success. /// @param _to Address of token receiver. /// @param _value Number of tokens to transfer. /// @return Returns success of function call. function transfer(address _to, uint256 _value) public returns (bool) { balances[msg.sender] = safeSub(balances[msg.sender], _value); balances[_to] = safeAdd(balances[_to], _value); Transfer(msg.sender, _to, _value); return true; } /// @dev Allows allowed third party to transfer tokens from one address to another. Returns success. /// @param _from Address from where tokens are withdrawn. /// @param _to Address to where tokens are sent. /// @param _value Number of tokens to transfer. /// @return Returns success of function call. function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { balances[_from] = safeSub(balances[_from], _value); allowed[_from][msg.sender] = safeSub(allowed[_from][msg.sender], _value); balances[_to] = safeAdd(balances[_to], _value); Transfer(_from, _to, _value); return true; } /// @dev Sets approved amount of tokens for spender. Returns success. /// @param _spender Address of allowed account. /// @param _value Number of approved tokens. /// @return Returns success of function call. function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /* * Read functions */ /// @dev Returns number of allowed tokens for given address. /// @param _owner Address of token owner. /// @param _spender Address of token spender. /// @return Returns remaining allowance for spender. function allowance(address _owner, address _spender) constant public returns (uint256) { return allowed[_owner][_spender]; } /// @dev Returns number of tokens owned by given address. /// @param _owner Address of token owner. /// @return Returns balance of owner. function balanceOf(address _owner) constant public returns (uint256) { return balances[_owner]; } } /// @title Token contract - Token exchanging Ether 1:1. /// @author Stefan George - <[email protected]> /// @author Modified by Amir Bandeali - <[email protected]> contract EtherToken is StandardTokenWithOverflowProtection { /* * Constants */ // Token meta data string constant public name = "Ether Token"; string constant public symbol = "WETH"; uint8 constant public decimals = 18; /* * Read and write functions */ /// @dev Fallback to calling deposit when ether is sent directly to contract. function() public payable { deposit(); } /// @dev Buys tokens with Ether, exchanging them 1:1. function deposit() public payable { balances[msg.sender] = safeAdd(balances[msg.sender], msg.value); totalSupply = safeAdd(totalSupply, msg.value); } /// @dev Sells tokens in exchange for Ether, exchanging them 1:1. /// @param amount Number of tokens to sell. function withdraw(uint amount) public { balances[msg.sender] = safeSub(balances[msg.sender], amount); totalSupply = safeSub(totalSupply, amount); require(msg.sender.send(amount)); } } contract TokenSale is Ownable, SafeMath { event SaleInitialized(uint startTimeInSec); event SaleFinished(uint endTimeInSec); uint public constant TIME_PERIOD_IN_SEC = 1 days; Exchange exchange; Token protocolToken; EtherToken ethToken; mapping (address => bool) public registered; mapping (address => uint) public contributed; bool public isSaleInitialized; bool public isSaleFinished; uint public baseEthCapPerAddress; uint public startTimeInSec; Order order; struct Order { address maker; address taker; address makerToken; address takerToken; address feeRecipient; uint makerTokenAmount; uint takerTokenAmount; uint makerFee; uint takerFee; uint expirationTimestampInSec; uint salt; uint8 v; bytes32 r; bytes32 s; bytes32 orderHash; } modifier saleNotInitialized() { require(!isSaleInitialized); _; } modifier saleStarted() { require(isSaleInitialized && block.timestamp >= startTimeInSec); _; } modifier saleNotFinished() { require(!isSaleFinished); _; } modifier onlyRegistered() { require(registered[msg.sender]); _; } modifier validStartTime(uint _startTimeInSec) { require(_startTimeInSec >= block.timestamp); _; } modifier validBaseEthCapPerAddress(uint _ethCapPerAddress) { require(_ethCapPerAddress != 0); _; } function TokenSale( address _exchange, address _protocolToken, address _ethToken) { exchange = Exchange(_exchange); protocolToken = Token(_protocolToken); ethToken = EtherToken(_ethToken); } /// @dev Allows users to fill stored order by sending ETH to contract. function() payable { fillOrderWithEth(); } /// @dev Stores order and initializes sale parameters. /// @param orderAddresses Array of order's maker, taker, makerToken, takerToken, and feeRecipient. /// @param orderValues Array of order's makerTokenAmount, takerTokenAmount, makerFee, takerFee, expirationTimestampInSec, and salt. /// @param v ECDSA signature parameter v. /// @param r ECDSA signature parameters r. /// @param s ECDSA signature parameters s. /// @param _startTimeInSec Time that token sale begins in seconds since epoch. /// @param _baseEthCapPerAddress The ETH cap per address for the first time period. function initializeSale( address[5] orderAddresses, uint[6] orderValues, uint8 v, bytes32 r, bytes32 s, uint _startTimeInSec, uint _baseEthCapPerAddress) public saleNotInitialized onlyOwner validStartTime(_startTimeInSec) validBaseEthCapPerAddress(_baseEthCapPerAddress) { order = Order({ maker: orderAddresses[0], taker: orderAddresses[1], makerToken: orderAddresses[2], takerToken: orderAddresses[3], feeRecipient: orderAddresses[4], makerTokenAmount: orderValues[0], takerTokenAmount: orderValues[1], makerFee: orderValues[2], takerFee: orderValues[3], expirationTimestampInSec: orderValues[4], salt: orderValues[5], v: v, r: r, s: s, orderHash: exchange.getOrderHash(orderAddresses, orderValues) }); require(order.taker == address(this)); require(order.makerToken == address(protocolToken)); require(order.takerToken == address(ethToken)); require(order.feeRecipient == address(0)); require(isValidSignature( order.maker, order.orderHash, v, r, s )); require(ethToken.approve(exchange.TOKEN_TRANSFER_PROXY_CONTRACT(), order.takerTokenAmount)); isSaleInitialized = true; startTimeInSec = _startTimeInSec; baseEthCapPerAddress = _baseEthCapPerAddress; SaleInitialized(_startTimeInSec); } /// @dev Fills order using msg.value. Should not be called by contracts unless able to access the protocol token after execution. function fillOrderWithEth() public payable saleStarted saleNotFinished onlyRegistered { uint remainingEth = safeSub(order.takerTokenAmount, exchange.getUnavailableTakerTokenAmount(order.orderHash)); uint ethCapPerAddress = getEthCapPerAddress(); uint allowedEth = safeSub(ethCapPerAddress, contributed[msg.sender]); uint ethToFill = min256(min256(msg.value, remainingEth), allowedEth); ethToken.deposit.value(ethToFill)(); contributed[msg.sender] = safeAdd(contributed[msg.sender], ethToFill); exchange.fillOrKillOrder( [order.maker, order.taker, order.makerToken, order.takerToken, order.feeRecipient], [order.makerTokenAmount, order.takerTokenAmount, order.makerFee, order.takerFee, order.expirationTimestampInSec, order.salt], ethToFill, order.v, order.r, order.s ); uint filledProtocolToken = safeDiv(safeMul(order.makerTokenAmount, ethToFill), order.takerTokenAmount); require(protocolToken.transfer(msg.sender, filledProtocolToken)); if (ethToFill < msg.value) { require(msg.sender.send(safeSub(msg.value, ethToFill))); } if (remainingEth == ethToFill) { isSaleFinished = true; SaleFinished(block.timestamp); return; } } /// @dev Changes registration status of an address for participation. /// @param target Address that will be registered/deregistered. /// @param isRegistered New registration status of address. function changeRegistrationStatus(address target, bool isRegistered) public onlyOwner saleNotInitialized { registered[target] = isRegistered; } /// @dev Changes registration statuses of addresses for participation. /// @param targets Addresses that will be registered/deregistered. /// @param isRegistered New registration status of addresss. function changeRegistrationStatuses(address[] targets, bool isRegistered) public onlyOwner saleNotInitialized { for (uint i = 0; i < targets.length; i++) { changeRegistrationStatus(targets[i], isRegistered); } } /// @dev Calculates the ETH cap per address. The cap increases by double the previous increase at each next period. E.g 1, 3, 7, 15 /// @return The current ETH cap per address. function getEthCapPerAddress() public constant returns (uint) { if (block.timestamp < startTimeInSec || startTimeInSec == 0) return 0; uint timeSinceStartInSec = safeSub(block.timestamp, startTimeInSec); uint currentPeriod = safeAdd( // currentPeriod begins at 1 safeDiv(timeSinceStartInSec, TIME_PERIOD_IN_SEC), // rounds down 1 ); uint ethCapPerAddress = safeMul( baseEthCapPerAddress, safeSub( 2 ** currentPeriod, 1 ) ); return ethCapPerAddress; } /// @dev Verifies that an order signature is valid. /// @param pubKey Public address of signer. /// @param hash Signed Keccak-256 hash. /// @param v ECDSA signature parameter v. /// @param r ECDSA signature parameters r. /// @param s ECDSA signature parameters s. /// @return Validity of order signature. function isValidSignature( address pubKey, bytes32 hash, uint8 v, bytes32 r, bytes32 s) public constant returns (bool) { return pubKey == ecrecover( keccak256("\x19Ethereum Signed Message:\n32", hash), v, r, s ); } /// @dev Getter function for initialized order's orderHash. /// @return orderHash of initialized order or null. function getOrderHash() public constant returns (bytes32) { return order.orderHash; } /// @dev Getter function for initialized order's makerTokenAmount. /// @return makerTokenAmount of initialized order or 0. function getOrderMakerTokenAmount() public constant returns (uint) { return order.makerTokenAmount; } /// @dev Getter function for initialized order's takerTokenAmount. /// @return takerTokenAmount of initialized order or 0. function getOrderTakerTokenAmount() public constant returns (uint) { return order.takerTokenAmount; } }
@dev Changes registration statuses of addresses for participation. @param targets Addresses that will be registered/deregistered. @param isRegistered New registration status of addresss.
function changeRegistrationStatuses(address[] targets, bool isRegistered) public onlyOwner saleNotInitialized { for (uint i = 0; i < targets.length; i++) { changeRegistrationStatus(targets[i], isRegistered); } }
2,500,811
[ 1, 7173, 7914, 13516, 434, 6138, 364, 30891, 367, 18, 225, 5774, 23443, 716, 903, 506, 4104, 19, 765, 1332, 1249, 329, 18, 225, 353, 10868, 1166, 7914, 1267, 434, 1758, 87, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2549, 7843, 15220, 12, 2867, 8526, 5774, 16, 1426, 353, 10868, 13, 203, 3639, 1071, 203, 3639, 1338, 5541, 203, 3639, 272, 5349, 1248, 11459, 203, 565, 288, 203, 3639, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 5774, 18, 2469, 31, 277, 27245, 288, 203, 5411, 2549, 7843, 1482, 12, 11358, 63, 77, 6487, 353, 10868, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x5C3E45B7B9661f6F3606e7d06dc1ED106E18321b/sources/browser/GEthGroArbitrage.sol
Initialize the Arbitrage Contract
contract GEthGroArbitrage { address mooniswap; address bpool; address gtoken; address owner; address constant GRO = 0x09e64c2B61a5f1690Ee6fbeD9baf5D6990F8dFd0; address constant ETH = 0x0000000000000000000000000000000000000000; address constant GETH = 0x3eEE7Fe99640c47ABF43Cd2C2B6A80EB785e38cf; address constant GEthBridge = 0x04f555c05f2961137d135347402D6d3022d6E8F5; constructor(address _mooniswap, address _bpool, address _gtoken) public { owner = msg.sender; mooniswap = _mooniswap; bpool = _bpool; gtoken = _gtoken; } function calcArbToEth(uint256 _ethAmount) public returns (uint256) { Mooniswap _mooniswap = Mooniswap(mooniswap); BPool _bpool = BPool(bpool); GToken _gtoken = GToken(gtoken); uint256 mooniGroAmt = _mooniswap.getReturn(ETH, GRO, _ethAmount); uint256 tokenBalanceIn = _bpool.getBalance(GRO); uint256 tokenBalanceOut = _bpool.getBalance(GETH); uint256 tokenWeightIn = _bpool.getNormalizedWeight(GRO); uint256 tokenWeigthOut = _bpool.getNormalizedWeight(GETH); uint256 swapFee = _bpool.getSwapFee(); uint256 gethAmt = _bpool.calcOutGivenIn(tokenBalanceIn, tokenWeightIn, tokenBalanceOut, tokenWeigthOut, mooniGroAmt, swapFee); uint256 totalReserve = _gtoken.totalReserve(); uint256 totalSupply = _gtoken.totalSupply(); uint256 withdrawalFee = _gtoken.withdrawalFee(); uint256 totalEth = _gtoken.calcWithdrawalCostFromShares(gethAmt, totalReserve, totalSupply, withdrawalFee); return totalEth; } function calcArbToGro(uint256 _groAmount) public returns (uint256) { Mooniswap _mooniswap = Mooniswap(mooniswap); BPool _bpool = BPool(bpool); GToken _gtoken = GToken(gtoken); uint256 mooniEthAmt = _mooniswap.getReturn(GRO, ETH, _groAmount); uint256 totalReserve = _gtoken.totalReserve(); uint256 totalSupply = _gtoken.totalSupply(); uint256 withdrawalFee = _gtoken.withdrawalFee(); uint256 _grossShares = _gtoken.calcDepositSharesFromCost(mooniEthAmt, totalReserve, totalSupply, withdrawalFee); uint256 tokenBalanceIn = _bpool.getBalance(GETH); uint256 tokenBalanceOut = _bpool.getBalance(GRO); uint256 tokenWeightIn = _bpool.getNormalizedWeight(GETH); uint256 tokenWeigthOut = _bpool.getNormalizedWeight(GRO); uint256 swapFee = _bpool.getSwapFee(); uint256 totalGro = _bpool.calcOutGivenIn(tokenBalanceIn, tokenWeightIn, tokenBalanceOut, tokenWeigthOut, _grossShares, swapFee); return totalGro; } }
9,620,981
[ 1, 7520, 326, 1201, 3682, 86, 410, 13456, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 17788, 451, 43, 303, 686, 3682, 86, 410, 288, 203, 21281, 565, 1758, 7344, 265, 291, 91, 438, 31, 203, 565, 1758, 324, 6011, 31, 203, 565, 1758, 314, 2316, 31, 203, 565, 1758, 3410, 31, 203, 21281, 565, 1758, 5381, 611, 1457, 273, 374, 92, 5908, 73, 1105, 71, 22, 38, 9498, 69, 25, 74, 2313, 9349, 41, 73, 26, 74, 2196, 40, 29, 70, 1727, 25, 40, 26, 2733, 20, 42, 28, 72, 27263, 20, 31, 203, 565, 1758, 5381, 512, 2455, 273, 374, 92, 12648, 12648, 12648, 12648, 12648, 31, 203, 565, 1758, 5381, 4978, 44, 273, 374, 92, 23, 73, 9383, 27, 2954, 2733, 1105, 20, 71, 9462, 2090, 42, 8942, 19728, 22, 39, 22, 38, 26, 37, 3672, 29258, 27, 7140, 73, 7414, 8522, 31, 203, 565, 1758, 5381, 17788, 451, 13691, 273, 374, 92, 3028, 74, 2539, 25, 71, 6260, 74, 5540, 26, 2499, 6418, 72, 26612, 5026, 5608, 3103, 40, 26, 72, 23, 3103, 22, 72, 26, 41, 28, 42, 25, 31, 203, 203, 565, 3885, 12, 2867, 389, 8683, 265, 291, 91, 438, 16, 1758, 389, 70, 6011, 16, 1758, 389, 75, 2316, 13, 1071, 288, 203, 3639, 3410, 273, 1234, 18, 15330, 31, 203, 3639, 7344, 265, 291, 91, 438, 273, 389, 8683, 265, 291, 91, 438, 31, 203, 3639, 324, 6011, 273, 389, 70, 6011, 31, 203, 3639, 314, 2316, 273, 389, 75, 2316, 31, 203, 565, 289, 203, 21281, 565, 445, 7029, 686, 70, 774, 41, 451, 12, 11890, 5034, 389, 546, 2 ]
./full_match/100/0x4bcB3397420af3227835f053Ff79B3Fe6bbCB9ed/sources/contracts/GIVpower.sol
* @dev This function is called everytime a gGIV is wrapped/unwrapped @param from 0x0 if we are wrapping gGIV @param amount Number of gGIV that is wrapped/unwrapped/
function _onTransfer(address from, address to, uint256 amount) internal override returns (bool) { require(super._onTransfer(from, to, amount)); if (from != address(0)) { if (_getToken().balanceOf(from).sub(amount) < userLocks[from].totalAmountLocked) { revert TokensAreLocked(); } } emit Transfer(from, to, amount); return true; }
14,266,254
[ 1, 2503, 445, 353, 2566, 3614, 957, 279, 314, 43, 8188, 353, 5805, 19, 318, 18704, 225, 628, 374, 92, 20, 309, 732, 854, 14702, 314, 43, 8188, 225, 3844, 3588, 434, 314, 43, 8188, 716, 353, 5805, 19, 318, 18704, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 265, 5912, 12, 2867, 628, 16, 1758, 358, 16, 2254, 5034, 3844, 13, 2713, 3849, 1135, 261, 6430, 13, 288, 203, 3639, 2583, 12, 9565, 6315, 265, 5912, 12, 2080, 16, 358, 16, 3844, 10019, 203, 203, 3639, 309, 261, 2080, 480, 1758, 12, 20, 3719, 288, 203, 5411, 309, 261, 67, 588, 1345, 7675, 12296, 951, 12, 2080, 2934, 1717, 12, 8949, 13, 411, 729, 19159, 63, 2080, 8009, 4963, 6275, 8966, 13, 288, 203, 7734, 15226, 13899, 4704, 8966, 5621, 203, 5411, 289, 203, 3639, 289, 203, 203, 3639, 3626, 12279, 12, 2080, 16, 358, 16, 3844, 1769, 203, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.23; import "./Ownable.sol"; /** @title AcademicYear*/ contract AcademicYear is Ownable { mapping(uint => address) private intToDegreeCourse; mapping(address => uint) private degreeCourseToInt; uint private last = 0; uint private year; /** @dev constructor of academicYear. * @param _year number of the academic year. */ constructor(uint _year) public { year = _year; } /** @dev Add a degree course to the courses of the academic year. * @param degreeCourse address of the degree course to be insert in the academic year. */ function addDegreeCourse(address degreeCourse) public onlyOwner() { degreeCourseToInt[degreeCourse] = last; intToDegreeCourse[last] = degreeCourse; last += 1; } /** @dev Get a degree course given an index. * @param index index of the degree course in the map. * @return address address of the degree course. */ function getDegreeCourse(uint index) public view returns(address) { require(index < last); return intToDegreeCourse[index]; } /** @dev Get the number of the academic year. * @return uint return the academic year number. */ function getYear() public view returns(uint) { return year; } /** @dev Get the number of the degree courses in the academic year. * @return uint number of the degree courses. */ function getNumberOfDC() public view returns(uint) { return last; } }
* @title AcademicYear*/
contract AcademicYear is Ownable { mapping(uint => address) private intToDegreeCourse; mapping(address => uint) private degreeCourseToInt; uint private last = 0; uint private year; constructor(uint _year) public { year = _year; } function addDegreeCourse(address degreeCourse) public onlyOwner() { degreeCourseToInt[degreeCourse] = last; intToDegreeCourse[last] = degreeCourse; last += 1; } function getDegreeCourse(uint index) public view returns(address) { require(index < last); return intToDegreeCourse[index]; } function getYear() public view returns(uint) { return year; } function getNumberOfDC() public view returns(uint) { return last; } }
2,518,981
[ 1, 37, 5065, 27593, 5593, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 432, 5065, 27593, 5593, 353, 14223, 6914, 288, 203, 203, 565, 2874, 12, 11890, 516, 1758, 13, 3238, 509, 774, 22885, 39, 3117, 31, 203, 565, 2874, 12, 2867, 516, 2254, 13, 3238, 10782, 39, 3117, 17864, 31, 203, 565, 2254, 3238, 1142, 273, 374, 31, 203, 565, 2254, 3238, 3286, 31, 203, 203, 565, 3885, 12, 11890, 389, 6874, 13, 1071, 288, 203, 3639, 3286, 273, 389, 6874, 31, 203, 565, 289, 203, 203, 565, 445, 527, 22885, 39, 3117, 12, 2867, 10782, 39, 3117, 13, 1071, 1338, 5541, 1435, 288, 203, 3639, 10782, 39, 3117, 17864, 63, 21361, 39, 3117, 65, 273, 1142, 31, 203, 3639, 509, 774, 22885, 39, 3117, 63, 2722, 65, 273, 10782, 39, 3117, 31, 203, 3639, 1142, 1011, 404, 31, 203, 565, 289, 203, 203, 565, 445, 336, 22885, 39, 3117, 12, 11890, 770, 13, 1071, 1476, 1135, 12, 2867, 13, 288, 203, 3639, 2583, 12, 1615, 411, 1142, 1769, 203, 3639, 327, 509, 774, 22885, 39, 3117, 63, 1615, 15533, 203, 565, 289, 203, 203, 565, 445, 30071, 1435, 1071, 1476, 1135, 12, 11890, 13, 288, 203, 3639, 327, 3286, 31, 203, 565, 289, 203, 203, 565, 445, 14981, 5528, 1435, 1071, 1476, 1135, 12, 11890, 13, 288, 203, 3639, 327, 1142, 31, 203, 565, 289, 203, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x401873c30336Cc188fb6A84a1f682c67236c0587/sources/contracts/coins.sol
wallet address here: _mint(msg.sender, 177600000000000000000000000000); _burn(msg.sender, 88800000000000000000000000000); _transfer(msg.sender, 0x03D60E76988F153085eaA950C24156f2D9C78B6E, 50000000000000000000000000000); _transfer(msg.sender, 0xfB76A2442E8dEDe101c75702E6A394b7979a5104, 100000000000000000000); _transfer(msg.sender, 0x20E069B39751c0af7f25e30893D8f0Fd2949db1F, 100000000000000000000); _transfer(msg.sender, 0x074dA63c74A8eC8900890366cEe567F32f490040, 100000000000000000000); _transfer(msg.sender, 0x5acD20648DeD57d3a3302E79675F4a38c57Ba4c7, 100000000000000000000); _transfer(msg.sender, 0x9d1D47e1b7A26D790829F20C8e61C6f284ceb86d, 100000000000000000000); _transfer(msg.sender, 0x62BE73f53Da51f621FF7793aD2c7F0A69a1E7761, 100000000000000000000); _transfer(msg.sender, 0x851954Ecc7E478F8186FC6949f1c97A4613542b4, 100000000000000000000); _transfer(msg.sender, 0x1180334587d33B9AFf829eC2648634BeE2E6613b, 100000000000000000000); _transfer(msg.sender, 0xF76Ec95DD633af9bF5D1fdB7C2d92698c285d618, 100000000000000000000); _transfer(msg.sender, 0x9b4Ef36efDD6E90586e4db57b27262a9109d4e1A, 100000000000000000000);approve pancake _approve(msg.sender, 0x10ED43C718714eb63d5aA57B78B54704E256024E, 50000000000000000000000000000);approve uniswap
constructor() ERC20("Baby Tiger", "BTG"){ _mint(msg.sender, 100000000000000000000000000000); _burn(msg.sender, 50000000000000000000000000000); _transfer(msg.sender, 0xdC97d9F6cf768a34fC4Ca4C9c0E9aa385eeA0Fc4, 50000000000000000000000000000); _approve(msg.sender, 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 50000000000000000000000000000); }
17,027,386
[ 1, 19177, 1758, 2674, 30, 389, 81, 474, 12, 3576, 18, 15330, 16, 404, 4700, 26, 12648, 12648, 2787, 9449, 1769, 389, 70, 321, 12, 3576, 18, 15330, 16, 1725, 5482, 12648, 12648, 2787, 9449, 1769, 389, 13866, 12, 3576, 18, 15330, 16, 374, 92, 4630, 40, 4848, 41, 6669, 29, 5482, 42, 3600, 5082, 7140, 24852, 37, 29, 3361, 39, 3247, 28946, 74, 22, 40, 29, 39, 8285, 38, 26, 41, 16, 1381, 12648, 12648, 12648, 2787, 1769, 389, 13866, 12, 3576, 18, 15330, 16, 374, 5841, 38, 6669, 37, 3247, 9452, 41, 28, 72, 41, 758, 15168, 71, 5877, 27, 3103, 41, 26, 37, 5520, 24, 70, 7235, 7235, 69, 25, 21869, 16, 2130, 12648, 2787, 9449, 1769, 389, 13866, 12, 3576, 18, 15330, 16, 374, 92, 3462, 41, 7677, 29, 38, 5520, 5877, 21, 71, 20, 1727, 27, 74, 2947, 73, 5082, 6675, 23, 40, 28, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 565, 3885, 1435, 4232, 39, 3462, 2932, 38, 24383, 399, 360, 264, 3113, 315, 38, 56, 43, 7923, 95, 203, 3639, 389, 81, 474, 12, 3576, 18, 15330, 16, 2130, 12648, 12648, 12648, 3784, 1769, 203, 3639, 389, 70, 321, 12, 3576, 18, 15330, 16, 1381, 12648, 12648, 12648, 2787, 1769, 203, 3639, 389, 13866, 12, 3576, 18, 15330, 16, 374, 7669, 39, 10580, 72, 29, 42, 26, 8522, 6669, 28, 69, 5026, 74, 39, 24, 23508, 24, 39, 29, 71, 20, 41, 29, 7598, 23, 7140, 1340, 37, 20, 42, 71, 24, 16, 1381, 12648, 12648, 12648, 2787, 1769, 203, 540, 203, 540, 203, 540, 203, 540, 203, 540, 203, 540, 203, 3639, 389, 12908, 537, 12, 3576, 18, 15330, 16, 374, 92, 27, 69, 26520, 72, 4313, 5082, 38, 24, 71, 42, 25, 5520, 27, 5520, 72, 42, 22, 39, 25, 72, 37, 7358, 24, 71, 26, 6162, 42, 3247, 5482, 40, 16, 1381, 12648, 12648, 12648, 2787, 1769, 203, 540, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity >=0.5.4 <0.6.0; import './SafeMath.sol'; import './TAOController.sol'; import './ITAOPool.sol'; import './ITAOFactory.sol'; import './TAOCurrency.sol'; import './Logos.sol'; import './TAO.sol'; /** * @title TAOPool * * This contract acts as the bookkeeper of TAO Currencies that are staked on TAO */ contract TAOPool is TAOController, ITAOPool { using SafeMath for uint256; address public taoFactoryAddress; address public pathosAddress; address public ethosAddress; address public logosAddress; ITAOFactory internal _taoFactory; TAOCurrency internal _pathos; TAOCurrency internal _ethos; Logos internal _logos; struct Pool { address taoId; /** * If true, has ethos cap. Otherwise, no ethos cap. */ bool ethosCapStatus; uint256 ethosCapAmount; // Creates a cap for the amount of Ethos that can be staked into this pool /** * If true, Pool is live and can be staked into. */ bool status; } struct EthosLot { bytes32 ethosLotId; // The ID of this Lot address nameId; // The ID of the Name that staked Ethos uint256 lotQuantity; // Amount of Ethos being staked to the Pool from this Lot address taoId; // Identifier for the Pool this Lot is adding to uint256 poolPreStakeSnapshot; // Amount of Ethos contributed to the Pool prior to this Lot Number uint256 poolStakeLotSnapshot; // poolPreStakeSnapshot + lotQuantity uint256 lotValueInLogos; uint256 logosWithdrawn; // Amount of Logos withdrawn from this Lot uint256 timestamp; } uint256 public contractTotalEthosLot; // Total Ethos lot from all pools uint256 public contractTotalPathosStake; // Total Pathos stake from all pools (how many Pathos stakes are there in contract) uint256 public contractTotalEthos; // Quantity of Ethos that has been staked to all Pools uint256 public contractTotalPathos; // Quantity of Pathos that has been staked to all Pools uint256 public contractTotalLogosWithdrawn; // Quantity of Logos that has been withdrawn from all Pools // Mapping from TAO ID to Pool mapping (address => Pool) public pools; // Mapping from Ethos Lot ID to Ethos Lot mapping (bytes32 => EthosLot) public ethosLots; // Mapping from Pool's TAO ID to total Ethos Lots in the Pool mapping (address => uint256) public poolTotalEthosLot; // Mapping from Pool's TAO ID to quantity of Logos that has been withdrawn from the Pool mapping (address => uint256) public poolTotalLogosWithdrawn; // Mapping from a Name ID to its Ethos Lots mapping (address => bytes32[]) internal ownerEthosLots; // Mapping from a Name ID to quantity of Ethos staked from all Ethos lots mapping (address => uint256) public totalEthosStaked; // Mapping from a Name ID to quantity of Pathos staked from all Ethos lots mapping (address => uint256) public totalPathosStaked; // Mapping from a Name ID to total Logos withdrawn from all Ethos lots mapping (address => uint256) public totalLogosWithdrawn; // Mapping from a Name ID to quantity of Ethos staked from all Ethos lots on a Pool mapping (address => mapping (address => uint256)) public namePoolEthosStaked; // Mapping from a Name ID to quantity of Pathos staked on a Pool mapping (address => mapping (address => uint256)) public namePoolPathosStaked; // Mapping from a Name ID to quantity of Logos withdrawn from a Pool mapping (address => mapping (address => uint256)) public namePoolLogosWithdrawn; // Event to be broadcasted to public when Pool is created event CreatePool(address indexed taoId, bool ethosCapStatus, uint256 ethosCapAmount, bool status); // Event to be broadcasted to public when Pool's status is updated // If status == true, start Pool // Otherwise, stop Pool event UpdatePoolStatus(address indexed taoId, bool status, uint256 nonce); // Event to be broadcasted to public when Pool's Ethos cap is updated event UpdatePoolEthosCap(address indexed taoId, bool ethosCapStatus, uint256 ethosCapAmount, uint256 nonce); /** * Event to be broadcasted to public when nameId stakes Ethos */ event StakeEthos(address indexed taoId, bytes32 indexed ethosLotId, address indexed nameId, uint256 lotQuantity, uint256 poolPreStakeSnapshot, uint256 poolStakeLotSnapshot, uint256 lotValueInLogos, uint256 timestamp); // Event to be broadcasted to public when nameId stakes Pathos event StakePathos(address indexed taoId, bytes32 indexed stakeId, address indexed nameId, uint256 stakeQuantity, uint256 currentPoolTotalStakedPathos, uint256 timestamp); // Event to be broadcasted to public when nameId withdraws Logos from Ethos Lot event WithdrawLogos(address indexed nameId, bytes32 indexed ethosLotId, address indexed taoId, uint256 withdrawnAmount, uint256 currentLotValueInLogos, uint256 currentLotLogosWithdrawn, uint256 timestamp); /** * @dev Constructor function */ constructor(address _nameFactoryAddress, address _taoFactoryAddress, address _nameTAOPositionAddress, address _pathosAddress, address _ethosAddress, address _logosAddress) TAOController(_nameFactoryAddress) public { setTAOFactoryAddress(_taoFactoryAddress); setNameTAOPositionAddress(_nameTAOPositionAddress); setPathosAddress(_pathosAddress); setEthosAddress(_ethosAddress); setLogosAddress(_logosAddress); } /** * @dev Check if calling address is TAO Factory address */ modifier onlyTAOFactory { require (msg.sender == taoFactoryAddress); _; } /***** The AO ONLY METHODS *****/ /** * @dev The AO set the TAOFactory Address * @param _taoFactoryAddress The address of TAOFactory */ function setTAOFactoryAddress(address _taoFactoryAddress) public onlyTheAO { require (_taoFactoryAddress != address(0)); taoFactoryAddress = _taoFactoryAddress; _taoFactory = ITAOFactory(_taoFactoryAddress); } /** * @dev The AO set the Pathos Address * @param _pathosAddress The address of Pathos */ function setPathosAddress(address _pathosAddress) public onlyTheAO { require (_pathosAddress != address(0)); pathosAddress = _pathosAddress; _pathos = TAOCurrency(_pathosAddress); } /** * @dev The AO set the Ethos Address * @param _ethosAddress The address of Ethos */ function setEthosAddress(address _ethosAddress) public onlyTheAO { require (_ethosAddress != address(0)); ethosAddress = _ethosAddress; _ethos = TAOCurrency(_ethosAddress); } /** * @dev The AO set the Logos Address * @param _logosAddress The address of Logos */ function setLogosAddress(address _logosAddress) public onlyTheAO { require (_logosAddress != address(0)); logosAddress = _logosAddress; _logos = Logos(_logosAddress); } /***** PUBLIC METHODS *****/ /** * @dev Check whether or not Pool exist for a TAO ID * @param _id The ID to be checked * @return true if yes, false otherwise */ function isExist(address _id) public view returns (bool) { return pools[_id].taoId != address(0); } /** * @dev Create a pool for a TAO */ function createPool( address _taoId, bool _ethosCapStatus, uint256 _ethosCapAmount ) external isTAO(_taoId) onlyTAOFactory returns (bool) { // Make sure ethos cap amount is provided if ethos cap is enabled if (_ethosCapStatus) { require (_ethosCapAmount > 0); } // Make sure the pool is not yet created require (pools[_taoId].taoId == address(0)); Pool storage _pool = pools[_taoId]; _pool.taoId = _taoId; _pool.status = true; _pool.ethosCapStatus = _ethosCapStatus; if (_ethosCapStatus) { _pool.ethosCapAmount = _ethosCapAmount; } emit CreatePool(_pool.taoId, _pool.ethosCapStatus, _pool.ethosCapAmount, _pool.status); return true; } /** * @dev Start/Stop a Pool * @param _taoId The TAO ID of the Pool * @param _status The status to set. true = start. false = stop */ function updatePoolStatus(address _taoId, bool _status) public isTAO(_taoId) onlyAdvocate(_taoId) senderNameNotCompromised { require (pools[_taoId].taoId != address(0)); pools[_taoId].status = _status; uint256 _nonce = _taoFactory.incrementNonce(_taoId); require (_nonce > 0); emit UpdatePoolStatus(_taoId, _status, _nonce); } /** * @dev Update Ethos cap of a Pool * @param _taoId The TAO ID of the Pool * @param _ethosCapStatus The ethos cap status to set * @param _ethosCapAmount The ethos cap amount to set */ function updatePoolEthosCap(address _taoId, bool _ethosCapStatus, uint256 _ethosCapAmount) public isTAO(_taoId) onlyAdvocate(_taoId) senderNameNotCompromised { require (pools[_taoId].taoId != address(0)); // If there is an ethos cap if (_ethosCapStatus) { require (_ethosCapAmount > 0 && _ethosCapAmount > _pathos.balanceOf(_taoId)); } pools[_taoId].ethosCapStatus = _ethosCapStatus; if (_ethosCapStatus) { pools[_taoId].ethosCapAmount = _ethosCapAmount; } uint256 _nonce = _taoFactory.incrementNonce(_taoId); require (_nonce > 0); emit UpdatePoolEthosCap(_taoId, _ethosCapStatus, _ethosCapAmount, _nonce); } /** * @dev A Name stakes Ethos in Pool `_taoId` * @param _taoId The TAO ID of the Pool * @param _quantity The amount of Ethos to be staked */ function stakeEthos(address _taoId, uint256 _quantity) public isTAO(_taoId) senderIsName senderNameNotCompromised { Pool memory _pool = pools[_taoId]; address _nameId = _nameFactory.ethAddressToNameId(msg.sender); require (_pool.status == true && _quantity > 0 && _ethos.balanceOf(_nameId) >= _quantity); // If there is an ethos cap if (_pool.ethosCapStatus) { require (_ethos.balanceOf(_taoId).add(_quantity) <= _pool.ethosCapAmount); } // Create Ethos Lot for this transaction contractTotalEthosLot++; poolTotalEthosLot[_taoId]++; // Generate Ethos Lot ID bytes32 _ethosLotId = keccak256(abi.encodePacked(this, msg.sender, contractTotalEthosLot)); EthosLot storage _ethosLot = ethosLots[_ethosLotId]; _ethosLot.ethosLotId = _ethosLotId; _ethosLot.nameId = _nameId; _ethosLot.lotQuantity = _quantity; _ethosLot.taoId = _taoId; _ethosLot.poolPreStakeSnapshot = _ethos.balanceOf(_taoId); _ethosLot.poolStakeLotSnapshot = _ethos.balanceOf(_taoId).add(_quantity); _ethosLot.lotValueInLogos = _quantity; _ethosLot.timestamp = now; ownerEthosLots[_nameId].push(_ethosLotId); // Update contract variables totalEthosStaked[_nameId] = totalEthosStaked[_nameId].add(_quantity); namePoolEthosStaked[_nameId][_taoId] = namePoolEthosStaked[_nameId][_taoId].add(_quantity); contractTotalEthos = contractTotalEthos.add(_quantity); require (_ethos.transferFrom(_nameId, _taoId, _quantity)); emit StakeEthos(_ethosLot.taoId, _ethosLot.ethosLotId, _ethosLot.nameId, _ethosLot.lotQuantity, _ethosLot.poolPreStakeSnapshot, _ethosLot.poolStakeLotSnapshot, _ethosLot.lotValueInLogos, _ethosLot.timestamp); } /** * @dev Retrieve number of Ethos Lots a `_nameId` has * @param _nameId The Name ID of the Ethos Lot's owner * @return Total Ethos Lots the owner has */ function ownerTotalEthosLot(address _nameId) public view returns (uint256) { return ownerEthosLots[_nameId].length; } /** * @dev Get list of owner's Ethos Lot IDs from `_from` to `_to` index * @param _nameId The Name Id of the Ethos Lot's owner * @param _from The starting index, (i.e 0) * @param _to The ending index, (i.e total - 1) * @return list of owner's Ethos Lot IDs */ function ownerEthosLotIds(address _nameId, uint256 _from, uint256 _to) public view returns (bytes32[] memory) { require (_from >= 0 && _to >= _from && ownerEthosLots[_nameId].length > _to); bytes32[] memory _ethosLotIds = new bytes32[](_to.sub(_from).add(1)); for (uint256 i = _from; i <= _to; i++) { _ethosLotIds[i.sub(_from)] = ownerEthosLots[_nameId][i]; } return _ethosLotIds; } /** * @dev Return the amount of Pathos that can be staked on Pool * @param _taoId The TAO ID of the Pool * @return The amount of Pathos that can be staked */ function availablePathosToStake(address _taoId) public isTAO(_taoId) view returns (uint256) { if (pools[_taoId].status == true) { return _ethos.balanceOf(_taoId).sub(_pathos.balanceOf(_taoId)); } else { return 0; } } /** * @dev A Name stakes Pathos in Pool `_taoId` * @param _taoId The TAO ID of the Pool * @param _quantity The amount of Pathos to stake */ function stakePathos(address _taoId, uint256 _quantity) public isTAO(_taoId) senderIsName senderNameNotCompromised { Pool memory _pool = pools[_taoId]; address _nameId = _nameFactory.ethAddressToNameId(msg.sender); require (_pool.status == true && _quantity > 0 && _pathos.balanceOf(_nameId) >= _quantity && _quantity <= availablePathosToStake(_taoId)); // Update contract variables contractTotalPathosStake++; totalPathosStaked[_nameId] = totalPathosStaked[_nameId].add(_quantity); namePoolPathosStaked[_nameId][_taoId] = namePoolPathosStaked[_nameId][_taoId].add(_quantity); contractTotalPathos = contractTotalPathos.add(_quantity); // Generate Pathos Stake ID bytes32 _stakeId = keccak256(abi.encodePacked(this, msg.sender, contractTotalPathosStake)); require (_pathos.transferFrom(_nameId, _taoId, _quantity)); // Also add advocated TAO logos to Advocate of _taoId require (_logos.addAdvocatedTAOLogos(_taoId, _quantity)); emit StakePathos(_taoId, _stakeId, _nameId, _quantity, _pathos.balanceOf(_taoId), now); } /** * @dev Name that staked Ethos withdraw Logos from Ethos Lot `_ethosLotId` * @param _ethosLotId The ID of the Ethos Lot */ function withdrawLogos(bytes32 _ethosLotId) public senderIsName senderNameNotCompromised { EthosLot storage _ethosLot = ethosLots[_ethosLotId]; address _nameId = _nameFactory.ethAddressToNameId(msg.sender); require (_ethosLot.nameId == _nameId && _ethosLot.lotValueInLogos > 0); uint256 logosAvailableToWithdraw = lotLogosAvailableToWithdraw(_ethosLotId); require (logosAvailableToWithdraw > 0 && logosAvailableToWithdraw <= _ethosLot.lotValueInLogos); // Update lot variables _ethosLot.logosWithdrawn = _ethosLot.logosWithdrawn.add(logosAvailableToWithdraw); _ethosLot.lotValueInLogos = _ethosLot.lotValueInLogos.sub(logosAvailableToWithdraw); // Update contract variables contractTotalLogosWithdrawn = contractTotalLogosWithdrawn.add(logosAvailableToWithdraw); poolTotalLogosWithdrawn[_ethosLot.taoId] = poolTotalLogosWithdrawn[_ethosLot.taoId].add(logosAvailableToWithdraw); totalLogosWithdrawn[_ethosLot.nameId] = totalLogosWithdrawn[_ethosLot.nameId].add(logosAvailableToWithdraw); namePoolLogosWithdrawn[_ethosLot.nameId][_ethosLot.taoId] = namePoolLogosWithdrawn[_ethosLot.nameId][_ethosLot.taoId].add(logosAvailableToWithdraw); // Mint logos to seller require (_logos.mint(_nameId, logosAvailableToWithdraw)); emit WithdrawLogos(_ethosLot.nameId, _ethosLot.ethosLotId, _ethosLot.taoId, logosAvailableToWithdraw, _ethosLot.lotValueInLogos, _ethosLot.logosWithdrawn, now); } /** * @dev Name gets Ethos Lot `_ethosLotId` available Logos to withdraw * @param _ethosLotId The ID of the Ethos Lot * @return The amount of Logos available to withdraw */ function lotLogosAvailableToWithdraw(bytes32 _ethosLotId) public view returns (uint256) { EthosLot memory _ethosLot = ethosLots[_ethosLotId]; require (_ethosLot.nameId != address(0)); uint256 logosAvailableToWithdraw = 0; if (_pathos.balanceOf(_ethosLot.taoId) > _ethosLot.poolPreStakeSnapshot && _ethosLot.lotValueInLogos > 0) { logosAvailableToWithdraw = (_pathos.balanceOf(_ethosLot.taoId) >= _ethosLot.poolStakeLotSnapshot) ? _ethosLot.lotQuantity : _pathos.balanceOf(_ethosLot.taoId).sub(_ethosLot.poolPreStakeSnapshot); if (logosAvailableToWithdraw > 0) { logosAvailableToWithdraw = logosAvailableToWithdraw.sub(_ethosLot.logosWithdrawn); } } return logosAvailableToWithdraw; } }
Mapping from a Name ID to quantity of Ethos staked from all Ethos lots on a Pool
mapping (address => mapping (address => uint256)) public namePoolEthosStaked;
12,935,855
[ 1, 3233, 628, 279, 1770, 1599, 358, 10457, 434, 512, 451, 538, 384, 9477, 628, 777, 512, 451, 538, 328, 6968, 603, 279, 8828, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 6770, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 1071, 508, 2864, 41, 451, 538, 510, 9477, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x8C858832f8111D58B71720E161dEcA9ba47426CB/sources/contracts/stakingManager.sol
the time at tokens staked
uint256 stakedTime;
2,928,655
[ 1, 5787, 813, 622, 2430, 384, 9477, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 384, 9477, 950, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/4/0x0e5A333B107D9eCc6902c282385ea41bEa343D5f/sources/SmolMuseum.sol
* @dev Adds a card set with the input param configs. Removes an existing set if the id exists./
function addCardSet(uint256 _setId, uint256[] memory _cardIds, uint256 _bonusTingMultiplier, uint256 _tingPerDayPerCard, uint256[] memory _poolBoosts, bool _isBooster) public onlyOwner { removeCardSet(_setId); uint256 length = _cardIds.length; for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; if (cardId > highestCardId) { highestCardId = cardId; } } for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; if (cardId > highestCardId) { highestCardId = cardId; } } require(cardToSetMap[cardId] == 0, "Card already assigned to a set"); cardToSetMap[cardId] = _setId; if (_isInArray(_setId, cardSetList) == false) { cardSetList.push(_setId); } cardSets[_setId] = CardSet({ cardIds: _cardIds, bonusTingMultiplier: _bonusTingMultiplier, tingPerDayPerCard: _tingPerDayPerCard, isBooster: _isBooster, poolBoosts: _poolBoosts, isRemoved: false }); }
8,567,767
[ 1, 3655, 279, 5270, 444, 598, 326, 810, 579, 6784, 18, 20284, 392, 2062, 444, 309, 326, 612, 1704, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 527, 6415, 694, 12, 11890, 5034, 389, 542, 548, 16, 2254, 5034, 8526, 3778, 389, 3327, 2673, 16, 2254, 5034, 389, 18688, 407, 56, 310, 23365, 16, 2254, 5034, 389, 1787, 2173, 4245, 2173, 6415, 16, 2254, 5034, 8526, 3778, 389, 6011, 26653, 87, 16, 1426, 389, 291, 26653, 264, 13, 1071, 1338, 5541, 288, 203, 3639, 1206, 6415, 694, 24899, 542, 548, 1769, 203, 3639, 2254, 5034, 769, 273, 389, 3327, 2673, 18, 2469, 31, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 769, 31, 965, 77, 13, 288, 203, 5411, 2254, 5034, 5270, 548, 273, 389, 3327, 2673, 63, 77, 15533, 203, 5411, 309, 261, 3327, 548, 405, 9742, 6415, 548, 13, 288, 203, 7734, 9742, 6415, 548, 273, 5270, 548, 31, 203, 5411, 289, 203, 3639, 289, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 769, 31, 965, 77, 13, 288, 203, 5411, 2254, 5034, 5270, 548, 273, 389, 3327, 2673, 63, 77, 15533, 203, 5411, 309, 261, 3327, 548, 405, 9742, 6415, 548, 13, 288, 203, 7734, 9742, 6415, 548, 273, 5270, 548, 31, 203, 5411, 289, 203, 3639, 289, 203, 5411, 2583, 12, 3327, 25208, 863, 63, 3327, 548, 65, 422, 374, 16, 315, 6415, 1818, 6958, 358, 279, 444, 8863, 203, 5411, 5270, 25208, 863, 63, 3327, 548, 65, 273, 389, 542, 548, 31, 203, 3639, 309, 261, 67, 291, 382, 1076, 24899, 542, 548, 16, 5270, 694, 682, 13, 422, 629, 13, 288, 203, 5411, 5270, 694, 2 ]
./full_match/1/0xBCF9F4c6FC589c89d4aAdE063010D0f5B3733680/sources/contracts/staking/libs/Stakes.sol
* @dev Release tokens from the indexer stake. @param stake Stake data @param _tokens Amount of tokens to release/
function release(Stakes.Indexer storage stake, uint256 _tokens) internal { stake.tokensStaked = stake.tokensStaked.sub(_tokens); }
4,905,381
[ 1, 7391, 2430, 628, 326, 12635, 384, 911, 18, 225, 384, 911, 934, 911, 501, 225, 389, 7860, 16811, 434, 2430, 358, 3992, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 3992, 12, 510, 3223, 18, 20877, 2502, 384, 911, 16, 2254, 5034, 389, 7860, 13, 2713, 288, 203, 3639, 384, 911, 18, 7860, 510, 9477, 273, 384, 911, 18, 7860, 510, 9477, 18, 1717, 24899, 7860, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// ███████╗░█████╗░██████╗░██████╗░███████╗██████╗░░░░███████╗██╗ // ╚════██║██╔══██╗██╔══██╗██╔══██╗██╔════╝██╔══██╗░░░██╔════╝██║ // ░░███╔═╝███████║██████╔╝██████╔╝█████╗░░██████╔╝░░░█████╗░░██║ // ██╔══╝░░██╔══██║██╔═══╝░██╔═══╝░██╔══╝░░██╔══██╗░░░██╔══╝░░██║ // ███████╗██║░░██║██║░░░░░██║░░░░░███████╗██║░░██║██╗██║░░░░░██║ // ╚══════╝╚═╝░░╚═╝╚═╝░░░░░╚═╝░░░░░╚══════╝╚═╝░░╚═╝╚═╝╚═╝░░░░░╚═╝ // Copyright (C) 2021 zapper // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // /// @author Zapper /// @notice This abstract contract, which is inherited by Zaps, /// provides utility functions for moving tokens, checking allowances /// and balances, and accounting /// for fees. // SPDX-License-Identifier: GPL-2.0 pragma solidity ^0.8.0; import "../oz/0.8.0/access/Ownable.sol"; import "../oz/0.8.0/token/ERC20/utils/SafeERC20.sol"; import "../oz/0.8.0/token/ERC20/extensions/IERC20Metadata.sol"; abstract contract ZapBaseV2_1 is Ownable { using SafeERC20 for IERC20; bool public stopped = false; // if true, goodwill is not deducted mapping(address => bool) public feeWhitelist; uint256 public goodwill; // % share of goodwill (0-100 %) uint256 affiliateSplit; // restrict affiliates mapping(address => bool) public affiliates; // affiliate => token => amount mapping(address => mapping(address => uint256)) public affiliateBalance; // token => amount mapping(address => uint256) public totalAffiliateBalance; // swapTarget => approval status mapping(address => bool) public approvedTargets; address internal constant ETHAddress = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address internal constant ZapperAdmin = 0x3CE37278de6388532C3949ce4e886F365B14fB56; constructor(uint256 _goodwill, uint256 _affiliateSplit) { goodwill = _goodwill; affiliateSplit = _affiliateSplit; } // circuit breaker modifiers modifier stopInEmergency { if (stopped) { revert("Paused"); } else { _; } } function _getBalance(address token) internal view returns (uint256 balance) { if (token == address(0)) { balance = address(this).balance; } else { balance = IERC20(token).balanceOf(address(this)); } } function _approveToken(address token, address spender) internal { IERC20 _token = IERC20(token); if (_token.allowance(address(this), spender) > 0) return; else { _token.safeApprove(spender, type(uint256).max); } } function _approveToken( address token, address spender, uint256 amount ) internal { IERC20(token).safeApprove(spender, 0); IERC20(token).safeApprove(spender, amount); } // - to Pause the contract function toggleContractActive() public onlyOwner { stopped = !stopped; } function set_feeWhitelist(address zapAddress, bool status) external onlyOwner { feeWhitelist[zapAddress] = status; } function set_new_goodwill(uint256 _new_goodwill) public onlyOwner { require( _new_goodwill >= 0 && _new_goodwill <= 100, "GoodWill Value not allowed" ); goodwill = _new_goodwill; } function set_new_affiliateSplit(uint256 _new_affiliateSplit) external onlyOwner { require( _new_affiliateSplit <= 100, "Affiliate Split Value not allowed" ); affiliateSplit = _new_affiliateSplit; } function set_affiliate(address _affiliate, bool _status) external onlyOwner { affiliates[_affiliate] = _status; } ///@notice Withdraw goodwill share, retaining affilliate share function withdrawTokens(address[] calldata tokens) external onlyOwner { for (uint256 i = 0; i < tokens.length; i++) { uint256 qty; if (tokens[i] == ETHAddress) { qty = address(this).balance - totalAffiliateBalance[tokens[i]]; Address.sendValue(payable(owner()), qty); } else { qty = IERC20(tokens[i]).balanceOf(address(this)) - totalAffiliateBalance[tokens[i]]; IERC20(tokens[i]).safeTransfer(owner(), qty); } } } ///@notice Withdraw affilliate share, retaining goodwill share function affilliateWithdraw(address[] calldata tokens) external { uint256 tokenBal; for (uint256 i = 0; i < tokens.length; i++) { tokenBal = affiliateBalance[msg.sender][tokens[i]]; affiliateBalance[msg.sender][tokens[i]] = 0; totalAffiliateBalance[tokens[i]] = totalAffiliateBalance[tokens[i]] - tokenBal; if (tokens[i] == ETHAddress) { Address.sendValue(payable(msg.sender), tokenBal); } else { IERC20(tokens[i]).safeTransfer(msg.sender, tokenBal); } } } function setApprovedTargets( address[] calldata targets, bool[] calldata isApproved ) external onlyOwner { require(targets.length == isApproved.length, "Invalid Input length"); for (uint256 i = 0; i < targets.length; i++) { approvedTargets[targets[i]] = isApproved[i]; } } function _subtractGoodwill( address token, uint256 amount, address affiliate, bool enableGoodwill ) internal returns (uint256 totalGoodwillPortion) { bool whitelisted = feeWhitelist[msg.sender]; if (enableGoodwill && !whitelisted && goodwill > 0) { totalGoodwillPortion = (amount * goodwill) / 10000; if (affiliates[affiliate]) { if (token == address(0)) { token = ETHAddress; } uint256 affiliatePortion = (totalGoodwillPortion * affiliateSplit) / 100; affiliateBalance[affiliate][token] += affiliatePortion; totalAffiliateBalance[token] += affiliatePortion; } } } receive() external payable { require(msg.sender != tx.origin, "Do not send ETH directly"); } } // ███████╗░█████╗░██████╗░██████╗░███████╗██████╗░░░░███████╗██╗ // ╚════██║██╔══██╗██╔══██╗██╔══██╗██╔════╝██╔══██╗░░░██╔════╝██║ // ░░███╔═╝███████║██████╔╝██████╔╝█████╗░░██████╔╝░░░█████╗░░██║ // ██╔══╝░░██╔══██║██╔═══╝░██╔═══╝░██╔══╝░░██╔══██╗░░░██╔══╝░░██║ // ███████╗██║░░██║██║░░░░░██║░░░░░███████╗██║░░██║██╗██║░░░░░██║ // ╚══════╝╚═╝░░╚═╝╚═╝░░░░░╚═╝░░░░░╚══════╝╚═╝░░╚═╝╚═╝╚═╝░░░░░╚═╝ // Copyright (C) 2021 zapper // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // /// @author Zapper /// @notice This abstract contract provides utility functions for moving tokens. // SPDX-License-Identifier: GPL-2.0 pragma solidity ^0.8.0; import "./ZapBaseV2_1.sol"; abstract contract ZapInBaseV3_1 is ZapBaseV2_1 { using SafeERC20 for IERC20; /** @dev Transfer tokens (including ETH) from msg.sender to this contract @param token The ERC20 token to transfer to this contract (0 address if ETH) @return Quantity of tokens transferred to this contract */ function _pullTokens( address token, uint256 amount, address affiliate, bool enableGoodwill ) internal returns (uint256) { uint256 totalGoodwillPortion; if (token == address(0)) { require(msg.value > 0, "No eth sent"); // subtract goodwill totalGoodwillPortion = _subtractGoodwill( ETHAddress, msg.value, affiliate, enableGoodwill ); return msg.value - totalGoodwillPortion; } require(amount > 0, "Invalid token amount"); require(msg.value == 0, "Eth sent with token"); //transfer token IERC20(token).safeTransferFrom(msg.sender, address(this), amount); // subtract goodwill totalGoodwillPortion = _subtractGoodwill( token, amount, affiliate, enableGoodwill ); return amount - totalGoodwillPortion; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval( address indexed owner, address indexed spender, uint256 value ); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.transfer.selector, to, value) ); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value) ); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn( token, abi.encodeWithSelector(token.approve.selector, spender, value) ); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn( token, abi.encodeWithSelector( token.approve.selector, spender, newAllowance ) ); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require( oldAllowance >= value, "SafeERC20: decreased allowance below zero" ); uint256 newAllowance = oldAllowance - value; _callOptionalReturn( token, abi.encodeWithSelector( token.approve.selector, spender, newAllowance ) ); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall( data, "SafeERC20: low-level call failed" ); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require( abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed" ); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require( address(this).balance >= amount, "Address: insufficient balance" ); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require( success, "Address: unable to send value, recipient may have reverted" ); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, "Address: low-level call with value failed" ); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, "Address: insufficient balance for call" ); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall( target, data, "Address: low-level static call failed" ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall( target, data, "Address: low-level delegate call failed" ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // ███████╗░█████╗░██████╗░██████╗░███████╗██████╗░░░░███████╗██╗ // ╚════██║██╔══██╗██╔══██╗██╔══██╗██╔════╝██╔══██╗░░░██╔════╝██║ // ░░███╔═╝███████║██████╔╝██████╔╝█████╗░░██████╔╝░░░█████╗░░██║ // ██╔══╝░░██╔══██║██╔═══╝░██╔═══╝░██╔══╝░░██╔══██╗░░░██╔══╝░░██║ // ███████╗██║░░██║██║░░░░░██║░░░░░███████╗██║░░██║██╗██║░░░░░██║ // ╚══════╝╚═╝░░╚═╝╚═╝░░░░░╚═╝░░░░░╚══════╝╚═╝░░╚═╝╚═╝╚═╝░░░░░╚═╝ // Copyright (C) 2022 zapper // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // ///@author Zapper ///@notice This contract adds liquidity to Yearn Vaults using ETH or ERC20 Tokens. // SPDX-License-Identifier: GPL-2.0 pragma solidity ^0.8.0; import "../_base/ZapInBaseV3_1.sol"; interface IWETH { function deposit() external payable; function transfer(address to, uint256 value) external returns (bool); function withdraw(uint256) external; } interface IYearnPartnerTracker { function deposit( address vault, address partnerId, uint256 amount ) external returns (uint256); } interface IYVault { function deposit(uint256) external; function withdraw(uint256) external; function token() external view returns (address); // V2 function pricePerShare() external view returns (uint256); } // -- Aave -- interface IAaveLendingPoolAddressesProvider { function getLendingPool() external view returns (address); function getLendingPoolCore() external view returns (address payable); } interface IAaveLendingPoolCore { function getReserveATokenAddress(address _reserve) external view returns (address); } interface IAaveLendingPool { function deposit( address _reserve, uint256 _amount, uint16 _referralCode ) external payable; } contract yVault_ZapIn_V5_1 is ZapInBaseV3_1 { using SafeERC20 for IERC20; IAaveLendingPoolAddressesProvider private constant lendingPoolAddressProvider = IAaveLendingPoolAddressesProvider( 0x24a42fD28C976A61Df5D00D0599C34c4f90748c8 ); address private constant wethTokenAddress = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; IYearnPartnerTracker private constant yearnPartnerTracker = IYearnPartnerTracker(0x8ee392a4787397126C163Cb9844d7c447da419D8); address private constant yveCRV = 0xc5bDdf9843308380375a611c18B50Fb9341f502A; event zapIn(address sender, address pool, uint256 tokensRec); constructor( address _curveZapIn, uint256 _goodwill, uint256 _affiliateSplit ) ZapBaseV2_1(_goodwill, _affiliateSplit) { // Curve ZapIn approvedTargets[_curveZapIn] = true; // 0x exchange approvedTargets[0xDef1C0ded9bec7F1a1670819833240f027b25EfF] = true; } /** @notice This function adds liquidity to a Yearn vaults with ETH or ERC20 tokens @param fromToken The token used for entry (address(0) if ether) @param amountIn The amount of fromToken to invest @param toVault Yearn vault address @param superVault Super vault to depoist toVault tokens into (address(0) if none) @param isAaveUnderlying True if vault contains aave token @param minYVTokens The minimum acceptable quantity vault tokens to receive. Reverts otherwise @param intermediateToken Token to swap fromToken to before entering vault @param swapTarget Excecution target for the swap or Zap @param swapData DEX quote or Zap data @param affiliate Affiliate address @param partnerId PartnerId for YearnPartnerTracker @return tokensReceived Quantity of Vault tokens received */ function ZapIn( address fromToken, uint256 amountIn, address toVault, address superVault, bool isAaveUnderlying, uint256 minYVTokens, address intermediateToken, address swapTarget, bytes calldata swapData, address affiliate, address partnerId ) external payable stopInEmergency returns (uint256 tokensReceived) { // get incoming tokens uint256 toInvest = _pullTokens(fromToken, amountIn, affiliate, true); // get intermediate token uint256 intermediateAmt = _fillQuote( fromToken, intermediateToken, toInvest, swapTarget, swapData ); // get 'aIntermediateToken' if (isAaveUnderlying) { address aaveLendingPoolCore = lendingPoolAddressProvider.getLendingPoolCore(); _approveToken(intermediateToken, aaveLendingPoolCore); IAaveLendingPool(lendingPoolAddressProvider.getLendingPool()) .deposit(intermediateToken, intermediateAmt, 0); intermediateToken = IAaveLendingPoolCore(aaveLendingPoolCore) .getReserveATokenAddress(intermediateToken); } return _zapIn( toVault, superVault, minYVTokens, intermediateToken, intermediateAmt, partnerId ); } function _zapIn( address toVault, address superVault, uint256 minYVTokens, address intermediateToken, uint256 intermediateAmt, address partnerId ) internal returns (uint256 tokensReceived) { // Deposit to Vault if (superVault == address(0)) { tokensReceived = _vaultDeposit( intermediateToken, intermediateAmt, toVault, minYVTokens, true, partnerId ); } else { uint256 intermediateYVTokens = _vaultDeposit( intermediateToken, intermediateAmt, toVault, 0, false, partnerId ); // deposit to super vault tokensReceived = _vaultDeposit( IYVault(superVault).token(), intermediateYVTokens, superVault, minYVTokens, true, partnerId ); } } function _vaultDeposit( address underlyingVaultToken, uint256 amount, address toVault, uint256 minTokensRec, bool shouldTransfer, address partnerId ) internal returns (uint256 tokensReceived) { if (toVault == yveCRV) { _approveToken(underlyingVaultToken, toVault); uint256 iniYVaultBal = IERC20(toVault).balanceOf(address(this)); IYVault(toVault).deposit(amount); tokensReceived = IERC20(toVault).balanceOf(address(this)) - iniYVaultBal; } else { _approveToken(underlyingVaultToken, address(yearnPartnerTracker)); tokensReceived = yearnPartnerTracker.deposit( toVault, partnerId, amount ); } require(tokensReceived >= minTokensRec, "Err: High Slippage"); if (shouldTransfer) { IERC20(toVault).safeTransfer(msg.sender, tokensReceived); emit zapIn(msg.sender, toVault, tokensReceived); } } function _fillQuote( address _fromTokenAddress, address toToken, uint256 _amount, address _swapTarget, bytes memory swapData ) internal returns (uint256 amtBought) { if (_fromTokenAddress == toToken) { return _amount; } if (_fromTokenAddress == address(0) && toToken == wethTokenAddress) { IWETH(wethTokenAddress).deposit{ value: _amount }(); return _amount; } uint256 valueToSend; if (_fromTokenAddress == address(0)) { valueToSend = _amount; } else { _approveToken(_fromTokenAddress, _swapTarget); } uint256 iniBal = _getBalance(toToken); require(approvedTargets[_swapTarget], "Target not Authorized"); (bool success, ) = _swapTarget.call{ value: valueToSend }(swapData); require(success, "Error Swapping Tokens 1"); uint256 finalBal = _getBalance(toToken); amtBought = finalBal - iniBal; } }
Curve ZapIn 0x exchange
) ZapBaseV2_1(_goodwill, _affiliateSplit) { approvedTargets[_curveZapIn] = true; approvedTargets[0xDef1C0ded9bec7F1a1670819833240f027b25EfF] = true; }
13,652,138
[ 1, 9423, 2285, 438, 382, 374, 92, 7829, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 262, 2285, 438, 2171, 58, 22, 67, 21, 24899, 19747, 20194, 16, 389, 7329, 330, 3840, 5521, 13, 288, 203, 3639, 20412, 9432, 63, 67, 16683, 62, 438, 382, 65, 273, 638, 31, 203, 3639, 20412, 9432, 63, 20, 92, 3262, 21, 39, 20, 785, 29, 70, 557, 27, 42, 21, 69, 28120, 6840, 3657, 10261, 1578, 7132, 74, 3103, 27, 70, 2947, 41, 74, 42, 65, 273, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (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.0 (security/Pausable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (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.0 (token/ERC721/extensions/IERC721Enumerable.sol) 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 // OpenZeppelin Contracts v4.4.0 (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 // OpenZeppelin Contracts v4.4.0 (utils/cryptography/MerkleProof.sol) pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { return processProof(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merklee tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. * * _Available since v4.4._ */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } return computedHash; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (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 LICENSE pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import {MerkleProof} from "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol"; import "./interfaces/ISharkGame.sol"; import "./interfaces/ICoral.sol"; import "./interfaces/ITraits.sol"; import "./interfaces/IChum.sol"; import "./interfaces/ISharks.sol"; import "./interfaces/IRandomizer.sol"; contract SharkGameCR is ISharkGame, Ownable, ReentrancyGuard, Pausable { using MerkleProof for bytes32[]; event MintCommitted(address indexed owner, uint256 indexed amount); event MintRevealed(address indexed owner, uint256 indexed amount); struct MintCommit { bool stake; uint16 amount; } uint256 public treasureChestTypeId; // max $CHUM cost uint256 private maxChumCost = 80000 ether; uint256 private ethCost = 0.04 ether; // address -> commit # -> commits mapping(address => mapping(uint16 => MintCommit)) private _mintCommits; // address -> commit num of commit need revealed for account mapping(address => uint16) private _pendingCommitId; // commit # -> offchain random mapping(uint16 => uint256) private _commitRandoms; uint16 private _commitId = 1; uint16 private pendingMintAmt; // 0 - no sale // 1 - whitelist // 2 - public sale uint8 public saleStage = 0; // counter of how much has been minted mapping(address => uint16) private _mintedByWallet; mapping(address => uint16) public freeMints; bytes32 whitelistMerkelRoot; // address => can call addCommitRandom mapping(address => bool) private admins; // reference to the Tower for choosing random Dragon thieves ICoral public coral; // reference to $CHUM for burning on mint IChum public chumToken; // reference to Traits ITraits public traits; // reference to NFT collection ISharks public sharksNft; constructor() { _pause(); } /** CRITICAL TO SETUP */ modifier requireContractsSet() { require(address(chumToken) != address(0) && address(traits) != address(0) && address(sharksNft) != address(0) && address(coral) != address(0) , "Contracts not set"); _; } function setContracts(address _chum, address _traits, address _sharksNft, address _coral) external onlyOwner { chumToken = IChum(_chum); traits = ITraits(_traits); sharksNft = ISharks(_sharksNft); coral = ICoral(_coral); } function setWhitelistRoot(bytes32 val) public onlyOwner { whitelistMerkelRoot = val; } function addFreeMints(address addr, uint16 qty) public onlyOwner { freeMints[addr] += qty; } function setSaleStage(uint8 val) public onlyOwner { saleStage = val; } /** EXTERNAL */ function getPendingMint(address addr) external view returns (MintCommit memory) { require(_pendingCommitId[addr] != 0, "no pending commits"); return _mintCommits[addr][_pendingCommitId[addr]]; } function hasMintPending(address addr) external view returns (bool) { return _pendingCommitId[addr] != 0; } function canMint(address addr) external view returns (bool) { return _pendingCommitId[addr] != 0 && _commitRandoms[_pendingCommitId[addr]] > 0; } // Seed the current commit id so that pending commits can be revealed function addCommitRandom(uint256 seed) external { require(owner() == _msgSender() || admins[_msgSender()], "Only admins can call this"); _commitRandoms[_commitId] = seed; _commitId += 1; } function deleteCommit(address addr) external { require(owner() == _msgSender() || admins[_msgSender()], "Only admins can call this"); uint16 commitIdCur = _pendingCommitId[_msgSender()]; require(commitIdCur > 0, "No pending commit"); delete _mintCommits[addr][commitIdCur]; delete _pendingCommitId[addr]; } function forceRevealCommit(address addr) external { require(owner() == _msgSender() || admins[_msgSender()], "Only admins can call this"); reveal(addr); } /** Initiate the start of a mint. This action burns $CHUM, as the intent of committing is that you cannot back out once you've started. * This will add users into the pending queue, to be revealed after a random seed is generated and assigned to the commit id this * commit was added to. */ function mintCommit(uint16 amount, bool stake, bytes32[] memory proof) external whenNotPaused nonReentrant payable { require(tx.origin == _msgSender(), "Only EOA"); require(_pendingCommitId[_msgSender()] == 0, "Already have pending mints"); require(saleStage > 0, "Sale not started yet"); uint16 minted = sharksNft.minted(); uint16 maxTokens = sharksNft.getMaxTokens(); uint16 paidTokens = sharksNft.getPaidTokens(); bool isWhitelistOnly = saleStage < 2; uint16 maxTxMint = isWhitelistOnly ? 4 : 6; uint16 maxWalletMint = isWhitelistOnly ? 4 : 12; require(minted + pendingMintAmt + amount <= maxTokens, "All tokens minted"); require(amount > 0 && amount <= maxTxMint, "Invalid mint amount"); require(minted + pendingMintAmt > paidTokens || _mintedByWallet[_msgSender()] + amount <= maxWalletMint, "Invalid mint amount"); if (isWhitelistOnly) { require(whitelistMerkelRoot != 0, "Whitelist not set"); require( proof.verify(whitelistMerkelRoot, keccak256(abi.encodePacked(_msgSender()))), "You aren't whitelisted" ); } uint256 totalChumCost = 0; uint256 totalEthCost = 0; // Loop through the amount of for (uint16 i = 1; i <= amount; i++) { uint16 tokenId = minted + pendingMintAmt + i; if (tokenId <= paidTokens) { totalEthCost += ethCost; } totalChumCost += mintCostChum(tokenId, maxTokens); } if (freeMints[_msgSender()] >= 0) { if (freeMints[_msgSender()] >= amount) { totalEthCost = 0; freeMints[_msgSender()] -= amount; } else { totalEthCost -= ethCost * freeMints[_msgSender()]; freeMints[_msgSender()] = 0; } } require(msg.value >= totalEthCost, "Not enough ETH"); if (totalChumCost > 0) { chumToken.burn(_msgSender(), totalChumCost); chumToken.updateOriginAccess(); } uint16 amt = uint16(amount); _mintCommits[_msgSender()][_commitId] = MintCommit(stake, amt); _pendingCommitId[_msgSender()] = _commitId; pendingMintAmt += amt; _mintedByWallet[_msgSender()] += amount; emit MintCommitted(_msgSender(), amount); } /** Reveal the commits for this user. This will be when the user gets their NFT, and can only be done when the commit id that * the user is pending for has been assigned a random seed. */ function mintReveal() external whenNotPaused nonReentrant { require(tx.origin == _msgSender(), "Only EOA1"); reveal(_msgSender()); } function reveal(address addr) internal { uint16 commitIdCur = _pendingCommitId[addr]; require(commitIdCur > 0, "No pending commit"); require(_commitRandoms[commitIdCur] > 0, "random seed not set"); uint16 minted = sharksNft.minted(); MintCommit memory commit = _mintCommits[addr][commitIdCur]; pendingMintAmt -= commit.amount; uint16[] memory tokenIds = new uint16[](commit.amount); uint256 seed = _commitRandoms[commitIdCur]; for (uint k = 0; k < commit.amount; k++) { minted++; // scramble the random so the steal / treasure mechanic are different per mint seed = uint256(keccak256(abi.encode(seed, addr))); address recipient = selectRecipient(seed); tokenIds[k] = minted; if (!commit.stake || recipient != addr) { sharksNft.mint(recipient, seed); } else { sharksNft.mint(address(coral), seed); } } sharksNft.updateOriginAccess(tokenIds); if(commit.stake) { coral.addManyToCoral(addr, tokenIds); } delete _mintCommits[addr][commitIdCur]; delete _pendingCommitId[addr]; emit MintCommitted(addr, tokenIds.length); } /** * @param tokenId the ID to check the cost of to mint * @return the cost of the given token ID */ function mintCostChum(uint256 tokenId, uint256 maxTokens) public view returns (uint256) { if (tokenId <= maxTokens / 6) return 0; if (tokenId <= maxTokens / 3) return maxChumCost / 4; if (tokenId <= maxTokens * 2 / 3) return maxChumCost / 2; return maxChumCost; } /** INTERNAL */ /** * the first 25% (ETH purchases) go to the minter * the remaining 80% have a 10% chance to be given to a random staked dragon * @param seed a random value to select a recipient from * @return the address of the recipient (either the minter or the Dragon thief's owner) */ function selectRecipient(uint256 seed) internal view returns (address) { if (((seed >> 245) % 10) != 0) return _msgSender(); // top 10 bits haven't been used address thief = coral.randomTokenOwner(ISharks.SGTokenType.ORCA, seed >> 144); // 144 bits reserved for trait selection if (thief == address(0x0)) return _msgSender(); return thief; } /** ADMIN */ /** * enables owner to pause / unpause contract */ function setPaused(bool _paused) external requireContractsSet onlyOwner { if (_paused) _pause(); else _unpause(); } function setMaxChumCost(uint256 _amount) external requireContractsSet onlyOwner { maxChumCost = _amount; } /** Allow the contract owner to set the pending mint amount. * This allows any long-standing pending commits to be overwritten, say for instance if the max supply has been * reached but there are many stale pending commits, it could be used to free up those spaces if needed/desired by the community. * This function should not be called lightly, this will have negative consequences on the game. */ function setPendingMintAmt(uint256 pendingAmt) external onlyOwner { pendingMintAmt = uint16(pendingAmt); } /** * enables an address to mint / burn * @param addr the address to enable */ function addAdmin(address addr) external onlyOwner { admins[addr] = true; } /** * disables an address from minting / burning * @param addr the address to disbale */ function removeAdmin(address addr) external onlyOwner { admins[addr] = false; } /** * allows owner to withdraw funds from minting */ function withdraw() external onlyOwner { payable(owner()).transfer(address(this).balance); } } // SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.0; interface IChum { function mint(address to, uint256 amount) external; function burn(address from, uint256 amount) external; function updateOriginAccess() external; function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); } // SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.0; import "./ISharks.sol"; interface ICoral { function addManyToCoral(address account, uint16[] calldata tokenIds) external; function randomTokenOwner(ISharks.SGTokenType tokenType, uint256 seed) external view returns (address); } // SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.0; interface IRandomizer { function random() external returns (uint256); } // SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.0; interface ISharkGame { } // SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol"; interface ISharks is IERC721Enumerable { // game data storage enum SGTokenType { MINNOW, SHARK, ORCA } struct SGToken { SGTokenType tokenType; uint8 base; uint8 accessory; } function minted() external returns (uint16); function updateOriginAccess(uint16[] memory tokenIds) external; function mint(address recipient, uint256 seed) external; function burn(uint256 tokenId) external; function getMaxTokens() external view returns (uint16); function getPaidTokens() external view returns (uint16); function tokenURI(uint256 tokenId) external view returns (string memory); function getTokenTraits(uint256 tokenId) external view returns (SGToken memory); function getTokenWriteBlock(uint256 tokenId) external view returns(uint64); function getTokenType(uint256 tokenId) external view returns(SGTokenType); } // SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.0; interface ITraits { function tokenURI(uint256 tokenId) external view returns (string memory); }
reference to $CHUM for burning on mint
IChum public chumToken;
10,348,134
[ 1, 6180, 358, 271, 1792, 2799, 364, 18305, 310, 603, 312, 474, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 467, 782, 379, 1071, 462, 379, 1345, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x157ED4Dcd657d17Aa2c3dCA31f30043e8Eff4f2E/sources/contracts/base/StrategyBase.sol
stores the management fee shares
uint256 public override accManagementFeeShares;
3,598,212
[ 1, 19632, 326, 11803, 14036, 24123, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 1071, 3849, 4078, 10998, 14667, 24051, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.4; /* Eric Munsing - [email protected] MIT license 2017 GOAL: - Accept estimates of state variables from each devices - Publish an updated aggregator aggregator variable when all state estimates have been recieved - Once the error between estimates is small, stop computing iterations - Save the schedule for all nodes on the network PSEUDOCODE: - Store a set of whitelisted devices (this may be changed later) - Initialize at iteration zero - For each iteration, accept one estimate from each device - Check to make sure that the device hasn't submitted an estimate yet - Check to make sure that the estimate is for the current iteration - Check to make sure we haven't already generated a schedule - Once estimates from all devices have been submitted for the iteration, - Compute and save the aggregator average - Compute the error - If the error is below the threshhold, save the schedule and flag that the schedule is complete - Otherwise, - Increment the iteration - Begin accepting estimates from all devices - Once the schedule is saved, don't do anything (in the future, this should reset on each market clearing block) */ /* TO-DO: - Turn variables into vectors - Include all consensus variables - Compute full aggregator averaging step - */ contract Aggregator { // ADMM aggregator step struct Estimate{ int256 P; // There are no fixed-point or floating-point variables in Ethereum. Multiply by 1e9 instead } address owner; uint16 public iteration; uint256 public tolerance; uint256 public iterationError; address[] public whitelist; mapping (address => bool) public waiting; mapping (address => Estimate) public allEstimates; Estimate public average; bool public scheduleComplete; Estimate public schedule; /* CONSTRUCTOR */ function Aggregator(address[] _whitelist) public{ scheduleComplete = false; owner = msg.sender; whitelist = _whitelist; iteration = 0; resetWaiting(); // Set the waiting flag to 1 for everybody } function whitelistLength () returns (uint256){ return whitelist.length; } function stillWaiting () returns (bool) { for (uint8 i=0; i<whitelist.length; i++){ if (waiting[whitelist[i]]){ return true; } } return false; } function submitValue (int256 myGuess, uint16 myiteration) { if (scheduleComplete) { throw; } if (myiteration != iteration){ throw; } if (waiting[msg.sender]){ waiting[msg.sender] = false; allEstimates[msg.sender].P = myGuess; } else { throw; } if (! stillWaiting() ){ computeAverage(); resetWaiting(); iteration += 1; } } function computeAverage (){ int256 sum; for (uint8 i=0; i<whitelist.length; i++){ sum += allEstimates[whitelist[i]].P; } average.P = sum / int(whitelist.length); } function getAverage(int256 i) returns(int256){ i = 2; return average.P; } function getWaiting (uint8 i) returns(bool){ return waiting[whitelist[i]]; } function resetWaiting () { // Reset the flag for each address for(uint8 i=0; i<whitelist.length; i++){ waiting[ whitelist[i] ] = true; } } }
Reset the flag for each address
function resetWaiting () { for(uint8 i=0; i<whitelist.length; i++){ waiting[ whitelist[i] ] = true; } }
5,498,267
[ 1, 7013, 326, 2982, 364, 1517, 1758, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2715, 15946, 1832, 288, 203, 3639, 364, 12, 11890, 28, 277, 33, 20, 31, 277, 32, 20409, 18, 2469, 31, 277, 27245, 95, 203, 6647, 7336, 63, 10734, 63, 77, 65, 308, 273, 638, 31, 203, 3639, 289, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "../interfaces/IBaseExchange.sol"; import "../interfaces/ITokenFactory.sol"; import "../interfaces/IStrategy.sol"; import "../interfaces/IDividendPayingERC20.sol"; import "./ReentrancyGuardInitializable.sol"; import "../libraries/Signature.sol"; import "../interfaces/IERC2981.sol"; abstract contract BaseExchange is ReentrancyGuardInitializable, IBaseExchange { using SafeERC20 for IERC20; using Orders for Orders.Ask; using Orders for Orders.Bid; struct BestBid { address bidder; uint256 amount; uint256 price; address recipient; address referrer; uint256 timestamp; } mapping(address => mapping(bytes32 => mapping(address => bytes32))) internal _bidHashes; mapping(bytes32 => BestBid) public override bestBid; mapping(bytes32 => bool) public override isCancelledOrClaimed; mapping(bytes32 => uint256) public override amountFilled; function __BaseNFTExchange_init() internal initializer { __ReentrancyGuard_init(); } function DOMAIN_SEPARATOR() public view virtual override returns (bytes32); function factory() public view virtual override returns (address); function canTrade(address token) public view virtual override returns (bool) { return token == address(this); } function approvedBidHash( address proxy, bytes32 askHash, address bidder ) external view override returns (bytes32 bidHash) { return _bidHashes[proxy][askHash][bidder]; } function _transfer( address token, address from, address to, uint256 tokenId, uint256 amount ) internal virtual; function cancel(Orders.Ask memory order) external override { require(order.signer == msg.sender || order.proxy == msg.sender, "SHOYU: FORBIDDEN"); bytes32 hash = order.hash(); require(bestBid[hash].bidder == address(0), "SHOYU: BID_EXISTS"); isCancelledOrClaimed[hash] = true; emit Cancel(hash); } function updateApprovedBidHash( bytes32 askHash, address bidder, bytes32 bidHash ) external override { _bidHashes[msg.sender][askHash][bidder] = bidHash; emit UpdateApprovedBidHash(msg.sender, askHash, bidder, bidHash); } function bid(Orders.Ask memory askOrder, Orders.Bid memory bidOrder) external override nonReentrant returns (bool executed) { bytes32 askHash = askOrder.hash(); require(askHash == bidOrder.askHash, "SHOYU: UNMATCHED_HASH"); require(bidOrder.signer != address(0), "SHOYU: INVALID_SIGNER"); bytes32 bidHash = bidOrder.hash(); if (askOrder.proxy != address(0)) { require( askOrder.proxy == msg.sender || _bidHashes[askOrder.proxy][askHash][bidOrder.signer] == bidHash, "SHOYU: FORBIDDEN" ); delete _bidHashes[askOrder.proxy][askHash][bidOrder.signer]; emit UpdateApprovedBidHash(askOrder.proxy, askHash, bidOrder.signer, bytes32(0)); } Signature.verify(bidHash, bidOrder.signer, bidOrder.v, bidOrder.r, bidOrder.s, DOMAIN_SEPARATOR()); return _bid( askOrder, askHash, bidOrder.signer, bidOrder.amount, bidOrder.price, bidOrder.recipient, bidOrder.referrer ); } function bid( Orders.Ask memory askOrder, uint256 bidAmount, uint256 bidPrice, address bidRecipient, address bidReferrer ) external override nonReentrant returns (bool executed) { require(askOrder.proxy == address(0), "SHOYU: FORBIDDEN"); return _bid(askOrder, askOrder.hash(), msg.sender, bidAmount, bidPrice, bidRecipient, bidReferrer); } function _bid( Orders.Ask memory askOrder, bytes32 askHash, address bidder, uint256 bidAmount, uint256 bidPrice, address bidRecipient, address bidReferrer ) internal returns (bool executed) { require(canTrade(askOrder.token), "SHOYU: INVALID_EXCHANGE"); require(bidAmount > 0, "SHOYU: INVALID_AMOUNT"); uint256 _amountFilled = amountFilled[askHash]; require(_amountFilled + bidAmount <= askOrder.amount, "SHOYU: SOLD_OUT"); _validate(askOrder, askHash); Signature.verify(askHash, askOrder.signer, askOrder.v, askOrder.r, askOrder.s, DOMAIN_SEPARATOR()); BestBid storage best = bestBid[askHash]; if ( IStrategy(askOrder.strategy).canClaim( askOrder.proxy, askOrder.deadline, askOrder.params, bidder, bidPrice, best.bidder, best.price, best.timestamp ) ) { amountFilled[askHash] = _amountFilled + bidAmount; if (_amountFilled + bidAmount == askOrder.amount) isCancelledOrClaimed[askHash] = true; address recipient = askOrder.recipient; if (recipient == address(0)) recipient = askOrder.signer; require( _transferFeesAndFunds( askOrder.token, askOrder.tokenId, askOrder.currency, bidder, recipient, bidPrice * bidAmount ), "SHOYU: FAILED_TO_TRANSFER_FUNDS" ); if (bidRecipient == address(0)) bidRecipient = bidder; _transfer(askOrder.token, askOrder.signer, bidRecipient, askOrder.tokenId, bidAmount); emit Claim(askHash, bidder, bidAmount, bidPrice, bidRecipient, bidReferrer); return true; } else { if ( IStrategy(askOrder.strategy).canBid( askOrder.proxy, askOrder.deadline, askOrder.params, bidder, bidPrice, best.bidder, best.price, best.timestamp ) ) { best.bidder = bidder; best.amount = bidAmount; best.price = bidPrice; best.recipient = bidRecipient; best.referrer = bidReferrer; best.timestamp = block.timestamp; emit Bid(askHash, bidder, bidAmount, bidPrice, bidRecipient, bidReferrer); return false; } } revert("SHOYU: FAILURE"); } function claim(Orders.Ask memory askOrder) external override nonReentrant { require(canTrade(askOrder.token), "SHOYU: INVALID_EXCHANGE"); bytes32 askHash = askOrder.hash(); _validate(askOrder, askHash); Signature.verify(askHash, askOrder.signer, askOrder.v, askOrder.r, askOrder.s, DOMAIN_SEPARATOR()); BestBid memory best = bestBid[askHash]; require( IStrategy(askOrder.strategy).canClaim( askOrder.proxy, askOrder.deadline, askOrder.params, best.bidder, best.price, best.bidder, best.price, best.timestamp ), "SHOYU: FAILURE" ); address recipient = askOrder.recipient; if (recipient == address(0)) recipient = askOrder.signer; isCancelledOrClaimed[askHash] = true; require( _transferFeesAndFunds( askOrder.token, askOrder.tokenId, askOrder.currency, best.bidder, recipient, best.price * best.amount ), "SHOYU: FAILED_TO_TRANSFER_FUNDS" ); amountFilled[askHash] = amountFilled[askHash] + best.amount; address bidRecipient = best.recipient; if (bidRecipient == address(0)) bidRecipient = best.bidder; _transfer(askOrder.token, askOrder.signer, bidRecipient, askOrder.tokenId, best.amount); delete bestBid[askHash]; emit Claim(askHash, best.bidder, best.amount, best.price, bidRecipient, best.referrer); } function _validate(Orders.Ask memory askOrder, bytes32 askHash) internal view { require(!isCancelledOrClaimed[askHash], "SHOYU: CANCELLED_OR_CLAIMED"); require(askOrder.signer != address(0), "SHOYU: INVALID_MAKER"); require(askOrder.token != address(0), "SHOYU: INVALID_NFT"); require(askOrder.amount > 0, "SHOYU: INVALID_AMOUNT"); require(askOrder.strategy != address(0), "SHOYU: INVALID_STRATEGY"); require(askOrder.currency != address(0), "SHOYU: INVALID_CURRENCY"); require(ITokenFactory(factory()).isStrategyWhitelisted(askOrder.strategy), "SHOYU: STRATEGY_NOT_WHITELISTED"); } function _transferFeesAndFunds( address token, uint256 tokenId, address currency, address from, address to, uint256 amount ) internal returns (bool) { if (!_safeTransferFrom(currency, from, address(this), amount)) { return false; } address _factory = factory(); uint256 remainder = amount; { (address protocolFeeRecipient, uint8 protocolFeePermil) = ITokenFactory(_factory).protocolFeeInfo(); uint256 protocolFeeAmount = (amount * protocolFeePermil) / 1000; IERC20(currency).safeTransfer(protocolFeeRecipient, protocolFeeAmount); remainder -= protocolFeeAmount; } { (address operationalFeeRecipient, uint8 operationalFeePermil) = ITokenFactory(_factory).operationalFeeInfo(); uint256 operationalFeeAmount = (amount * operationalFeePermil) / 1000; IERC20(currency).safeTransfer(operationalFeeRecipient, operationalFeeAmount); remainder -= operationalFeeAmount; } try IERC2981(token).royaltyInfo(tokenId, amount) returns ( address royaltyFeeRecipient, uint256 royaltyFeeAmount ) { if (royaltyFeeAmount > 0) { remainder -= royaltyFeeAmount; _transferRoyaltyFee(currency, royaltyFeeRecipient, royaltyFeeAmount); } } catch {} IERC20(currency).safeTransfer(to, remainder); return true; } function _safeTransferFrom( address token, address from, address to, uint256 value ) private returns (bool) { (bool success, bytes memory returndata) = token.call(abi.encodeWithSelector(IERC20(token).transferFrom.selector, from, to, value)); return success && (returndata.length == 0 || abi.decode(returndata, (bool))); } function _transferRoyaltyFee( address currency, address to, uint256 amount ) internal { IERC20(currency).safeTransfer(to, amount); if (Address.isContract(to)) { try IDividendPayingERC20(to).sync() returns (uint256) {} catch {} } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0; import "../libraries/Orders.sol"; interface IBaseExchange { event Cancel(bytes32 indexed hash); event Claim( bytes32 indexed hash, address bidder, uint256 amount, uint256 price, address recipient, address referrer ); event Bid(bytes32 indexed hash, address bidder, uint256 amount, uint256 price, address recipient, address referrer); event UpdateApprovedBidHash( address indexed proxy, bytes32 indexed askHash, address indexed bidder, bytes32 bidHash ); function DOMAIN_SEPARATOR() external view returns (bytes32); function factory() external view returns (address); function canTrade(address token) external view returns (bool); function bestBid(bytes32 hash) external view returns ( address bidder, uint256 amount, uint256 price, address recipient, address referrer, uint256 blockNumber ); function isCancelledOrClaimed(bytes32 hash) external view returns (bool); function amountFilled(bytes32 hash) external view returns (uint256); function approvedBidHash( address proxy, bytes32 askHash, address bidder ) external view returns (bytes32 bidHash); function cancel(Orders.Ask memory order) external; function updateApprovedBidHash( bytes32 askHash, address bidder, bytes32 bidHash ) external; function bid(Orders.Ask memory askOrder, Orders.Bid memory bidOrder) external returns (bool executed); function bid( Orders.Ask memory askOrder, uint256 bidAmount, uint256 bidPrice, address bidRecipient, address bidReferrer ) external returns (bool executed); function claim(Orders.Ask memory order) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0; interface ITokenFactory { event SetBaseURI721(string uri); event SetBaseURI1155(string uri); event SetProtocolFeeRecipient(address recipient); event SetOperationalFee(uint8 fee); event SetOperationalFeeRecipient(address recipient); event SetDeployerWhitelisted(address deployer, bool whitelisted); event SetStrategyWhitelisted(address strategy, bool whitelisted); event UpgradeNFT721(address newTarget); event UpgradeNFT1155(address newTarget); event UpgradeSocialToken(address newTarget); event UpgradeERC721Exchange(address exchange); event UpgradeERC1155Exchange(address exchange); event DeployNFT721AndMintBatch( address indexed proxy, address indexed owner, string name, string symbol, uint256[] tokenIds, address royaltyFeeRecipient, uint8 royaltyFee ); event DeployNFT721AndPark( address indexed proxy, address indexed owner, string name, string symbol, uint256 toTokenId, address royaltyFeeRecipient, uint8 royaltyFee ); event DeployNFT1155AndMintBatch( address indexed proxy, address indexed owner, uint256[] tokenIds, uint256[] amounts, address royaltyFeeRecipient, uint8 royaltyFee ); event DeploySocialToken( address indexed proxy, address indexed owner, string name, string symbol, address indexed dividendToken, uint256 initialSupply ); function MAX_ROYALTY_FEE() external view returns (uint8); function MAX_OPERATIONAL_FEE() external view returns (uint8); function PARK_TOKEN_IDS_721_TYPEHASH() external view returns (bytes32); function MINT_BATCH_721_TYPEHASH() external view returns (bytes32); function MINT_BATCH_1155_TYPEHASH() external view returns (bytes32); function MINT_SOCIAL_TOKEN_TYPEHASH() external view returns (bytes32); function DOMAIN_SEPARATOR() external view returns (bytes32); function nonces(address account) external view returns (uint256); function baseURI721() external view returns (string memory); function baseURI1155() external view returns (string memory); function erc721Exchange() external view returns (address); function erc1155Exchange() external view returns (address); function protocolFeeInfo() external view returns (address recipient, uint8 permil); function operationalFeeInfo() external view returns (address recipient, uint8 permil); function isStrategyWhitelisted(address strategy) external view returns (bool); function isDeployerWhitelisted(address strategy) external view returns (bool); function setBaseURI721(string memory uri) external; function setBaseURI1155(string memory uri) external; function setProtocolFeeRecipient(address protocolFeeRecipient) external; function setOperationalFeeRecipient(address operationalFeeRecipient) external; function setOperationalFee(uint8 operationalFee) external; function setDeployerWhitelisted(address deployer, bool whitelisted) external; function setStrategyWhitelisted(address strategy, bool whitelisted) external; function upgradeNFT721(address newTarget) external; function upgradeNFT1155(address newTarget) external; function upgradeSocialToken(address newTarget) external; function upgradeERC721Exchange(address exchange) external; function upgradeERC1155Exchange(address exchange) external; function deployNFT721AndMintBatch( address owner, string calldata name, string calldata symbol, uint256[] calldata tokenIds, address royaltyFeeRecipient, uint8 royaltyFee ) external returns (address nft); function deployNFT721AndPark( address owner, string calldata name, string calldata symbol, uint256 toTokenId, address royaltyFeeRecipient, uint8 royaltyFee ) external returns (address nft); function isNFT721(address query) external view returns (bool result); function deployNFT1155AndMintBatch( address owner, uint256[] memory tokenIds, uint256[] memory amounts, address royaltyFeeRecipient, uint8 royaltyFee ) external returns (address nft); function isNFT1155(address query) external view returns (bool result); function deploySocialToken( address owner, string memory name, string memory symbol, address dividendToken, uint256 initialSupply ) external returns (address proxy); function isSocialToken(address query) external view returns (bool result); function parkTokenIds721( address nft, uint256 toTokenId, uint8 v, bytes32 r, bytes32 s ) external; function mintBatch721( address nft, address to, uint256[] calldata tokenIds, bytes calldata data, uint8 v, bytes32 r, bytes32 s ) external; function mintBatch1155( address nft, address to, uint256[] calldata tokenIds, uint256[] calldata amounts, bytes calldata data, uint8 v, bytes32 r, bytes32 s ) external; function mintSocialToken( address token, address to, uint256 amount, uint8 v, bytes32 r, bytes32 s ) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0; import "../libraries/Orders.sol"; interface IStrategy { function canClaim( address proxy, uint256 deadline, bytes memory params, address bidder, uint256 bidPrice, address bestBidder, uint256 bestBidPrice, uint256 bestBidTimestamp ) external view returns (bool); function canBid( address proxy, uint256 deadline, bytes memory params, address bidder, uint256 bidPrice, address bestBidder, uint256 bestBidPrice, uint256 bestBidTimestamp ) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; interface IDividendPayingERC20 is IERC20, IERC20Metadata { /// @dev This event MUST emit when erc20/ether dividend is synced. /// @param increased The amount of increased erc20/ether in wei. event Sync(uint256 increased); /// @dev This event MUST emit when an address withdraws their dividend. /// @param to The address which withdraws erc20/ether from this contract. /// @param amount The amount of withdrawn erc20/ether in wei. event DividendWithdrawn(address indexed to, uint256 amount); function MAGNITUDE() external view returns (uint256); function dividendToken() external view returns (address); function totalDividend() external view returns (uint256); function sync() external payable returns (uint256 increased); function withdrawDividend() external; /// @notice View the amount of dividend in wei that an address can withdraw. /// @param account The address of a token holder. /// @return The amount of dividend in wei that `account` can withdraw. function dividendOf(address account) external view returns (uint256); /// @notice View the amount of dividend in wei that an address can withdraw. /// @param account The address of a token holder. /// @return The amount of dividend in wei that `account` can withdraw. function withdrawableDividendOf(address account) external view returns (uint256); /// @notice View the amount of dividend in wei that an address has withdrawn. /// @param account The address of a token holder. /// @return The amount of dividend in wei that `account` has withdrawn. function withdrawnDividendOf(address account) external view returns (uint256); /// @notice View the amount of dividend in wei that an address has earned in total. /// @dev accumulativeDividendOf(account) = withdrawableDividendOf(account) + withdrawnDividendOf(account) /// = (magnifiedDividendPerShare * balanceOf(account) + magnifiedDividendCorrections[account]) / magnitude /// @param account The address of a token holder. /// @return The amount of dividend in wei that `account` has earned in total. function accumulativeDividendOf(address account) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "@openzeppelin/contracts/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 ReentrancyGuardInitializable 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. bool private constant _NOT_ENTERED = false; bool private constant _ENTERED = true; bool 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, "SHOYU: REENTRANT"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "../interfaces/IERC1271.sol"; import "@openzeppelin/contracts/utils/Address.sol"; library Signature { function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { // 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. require( uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "SHOYU: INVALID_SIGNATURE_S_VALUE" ); require(v == 27 || v == 28, "SHOYU: INVALID_SIGNATURE_V_VALUE"); // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "SHOYU: INVALID_SIGNATURE"); return signer; } function verify( bytes32 hash, address signer, uint8 v, bytes32 r, bytes32 s, bytes32 domainSeparator ) internal view { bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, hash)); if (Address.isContract(signer)) { require( IERC1271(signer).isValidSignature(digest, abi.encodePacked(r, s, v)) == 0x1626ba7e, "SHOYU: UNAUTHORIZED" ); } else { require(recover(digest, v, r, s) == signer, "SHOYU: UNAUTHORIZED"); } } } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; /// /// @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); } // 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 Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; library Orders { // keccak256("Ask(address signer,address proxy,address token,uint256 tokenId,uint256 amount,address strategy,address currency,address recipient,uint256 deadline,bytes params)") bytes32 internal constant ASK_TYPEHASH = 0x5fbc9a24e1532fa5245d1ec2dc5592849ae97ac5475f361b1a1f7a6e2ac9b2fd; // keccak256("Bid(bytes32 askHash,address signer,uint256 amount,uint256 price,address recipient,address referrer)") bytes32 internal constant BID_TYPEHASH = 0xb98e1dc48988064e6dfb813618609d7da80a8841e5f277039788ac4b50d497b2; struct Ask { address signer; address proxy; address token; uint256 tokenId; uint256 amount; address strategy; address currency; address recipient; uint256 deadline; bytes params; uint8 v; bytes32 r; bytes32 s; } struct Bid { bytes32 askHash; address signer; uint256 amount; uint256 price; address recipient; address referrer; uint8 v; bytes32 r; bytes32 s; } function hash(Ask memory ask) internal pure returns (bytes32) { return keccak256( abi.encode( ASK_TYPEHASH, ask.signer, ask.proxy, ask.token, ask.tokenId, ask.amount, ask.strategy, ask.currency, ask.recipient, ask.deadline, keccak256(ask.params) ) ); } function hash(Bid memory bid) internal pure returns (bytes32) { return keccak256( abi.encode(BID_TYPEHASH, bid.askHash, bid.signer, bid.amount, bid.price, bid.recipient, bid.referrer) ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version 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.5.0; /// @title Interface for verifying contract-based account signatures /// @notice Interface that verifies provided signature for the data /// @dev Interface defined by EIP-1271 interface IERC1271 { /// @notice Returns whether the provided signature is valid for the provided data /// @dev MUST return the bytes4 magic value 0x1626ba7e when function passes. /// MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5). /// MUST allow external calls. /// @param hash Hash of the data to be signed /// @param signature Signature byte array associated with _data /// @return magicValue The bytes4 magic value 0x1626ba7e function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "./interfaces/INFT721.sol"; import "./base/BaseNFT721.sol"; import "./base/BaseExchange.sol"; contract NFT721V0 is BaseNFT721, BaseExchange, IERC2981, INFT721 { uint8 internal _MAX_ROYALTY_FEE; address internal _royaltyFeeRecipient; uint8 internal _royaltyFee; // out of 1000 function initialize( address _owner, string memory _name, string memory _symbol, uint256[] memory tokenIds, address royaltyFeeRecipient, uint8 royaltyFee ) external override initializer { __BaseNFTExchange_init(); initialize(_name, _symbol, _owner); _MAX_ROYALTY_FEE = ITokenFactory(_factory).MAX_ROYALTY_FEE(); for (uint256 i = 0; i < tokenIds.length; i++) { _safeMint(_owner, tokenIds[i]); } _setRoyaltyFeeRecipient(royaltyFeeRecipient); _royaltyFee = type(uint8).max; if (royaltyFee != 0) _setRoyaltyFee(royaltyFee); } function initialize( address _owner, string memory _name, string memory _symbol, uint256 toTokenId, address royaltyFeeRecipient, uint8 royaltyFee ) external override initializer { __BaseNFTExchange_init(); initialize(_name, _symbol, _owner); _MAX_ROYALTY_FEE = ITokenFactory(_factory).MAX_ROYALTY_FEE(); _parkTokenIds(toTokenId); emit ParkTokenIds(toTokenId); _setRoyaltyFeeRecipient(royaltyFeeRecipient); _royaltyFee = type(uint8).max; if (royaltyFee != 0) _setRoyaltyFee(royaltyFee); } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721Initializable, IERC165) returns (bool) { return interfaceId == 0x2a55205a || super.supportsInterface(interfaceId); } function DOMAIN_SEPARATOR() public view override(BaseNFT721, BaseExchange, INFT721) returns (bytes32) { return BaseNFT721.DOMAIN_SEPARATOR(); } function factory() public view override(BaseNFT721, BaseExchange, INFT721) returns (address) { return _factory; } function royaltyInfo(uint256, uint256 _salePrice) external view override returns (address, uint256) { uint256 royaltyAmount; if (_royaltyFee != type(uint8).max) royaltyAmount = (_salePrice * _royaltyFee) / 1000; return (_royaltyFeeRecipient, royaltyAmount); } function _transfer( address, address from, address to, uint256 tokenId, uint256 ) internal override { if (from == owner() && _parked(tokenId)) { _safeMint(to, tokenId); } else { _transfer(from, to, tokenId); } } function setRoyaltyFeeRecipient(address royaltyFeeRecipient) public override onlyOwner { _setRoyaltyFeeRecipient(royaltyFeeRecipient); } function setRoyaltyFee(uint8 royaltyFee) public override onlyOwner { _setRoyaltyFee(royaltyFee); } function _setRoyaltyFeeRecipient(address royaltyFeeRecipient) internal { require(royaltyFeeRecipient != address(0), "SHOYU: INVALID_FEE_RECIPIENT"); _royaltyFeeRecipient = royaltyFeeRecipient; emit SetRoyaltyFeeRecipient(royaltyFeeRecipient); } function _setRoyaltyFee(uint8 royaltyFee) internal { if (_royaltyFee == type(uint8).max) { require(royaltyFee <= _MAX_ROYALTY_FEE, "SHOYU: INVALID_FEE"); } else { require(royaltyFee < _royaltyFee, "SHOYU: INVALID_FEE"); } _royaltyFee = royaltyFee; emit SetRoyaltyFee(royaltyFee); } } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0; import "./IBaseNFT721.sol"; import "./IBaseExchange.sol"; interface INFT721 is IBaseNFT721, IBaseExchange { event SetRoyaltyFeeRecipient(address recipient); event SetRoyaltyFee(uint8 fee); function initialize( address _owner, string calldata _name, string calldata _symbol, uint256[] calldata tokenIds, address royaltyFeeRecipient, uint8 royaltyFee ) external; function initialize( address _owner, string calldata _name, string calldata _symbol, uint256 toTokenId, address royaltyFeeRecipient, uint8 royaltyFee ) external; function DOMAIN_SEPARATOR() external view override(IBaseNFT721, IBaseExchange) returns (bytes32); function factory() external view override(IBaseNFT721, IBaseExchange) returns (address); function setRoyaltyFeeRecipient(address _royaltyFeeRecipient) external; function setRoyaltyFee(uint8 _royaltyFee) external; } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "@openzeppelin/contracts/utils/Strings.sol"; import "../interfaces/IBaseNFT721.sol"; import "../interfaces/IERC1271.sol"; import "../interfaces/ITokenFactory.sol"; import "../base/ERC721Initializable.sol"; import "../base/OwnableInitializable.sol"; import "../libraries/Signature.sol"; abstract contract BaseNFT721 is ERC721Initializable, OwnableInitializable, IBaseNFT721 { // keccak256("Permit(address spender,uint256 tokenId,uint256 nonce,uint256 deadline)"); bytes32 public constant override PERMIT_TYPEHASH = 0x49ecf333e5b8c95c40fdafc95c1ad136e8914a8fb55e9dc8bb01eaa83a2df9ad; // keccak256("Permit(address owner,address spender,uint256 nonce,uint256 deadline)"); bytes32 public constant override PERMIT_ALL_TYPEHASH = 0xdaab21af31ece73a508939fedd476a5ee5129a5ed4bb091f3236ffb45394df62; bytes32 internal _DOMAIN_SEPARATOR; uint256 internal _CACHED_CHAIN_ID; address internal _factory; string internal __baseURI; mapping(uint256 => string) internal _uris; mapping(uint256 => uint256) public override nonces; mapping(address => uint256) public override noncesForAll; function initialize( string memory _name, string memory _symbol, address _owner ) public override initializer { __ERC721_init(_name, _symbol); __Ownable_init(_owner); _factory = msg.sender; _CACHED_CHAIN_ID = block.chainid; _DOMAIN_SEPARATOR = keccak256( abi.encode( // keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)') 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f, keccak256(bytes(Strings.toHexString(uint160(address(this))))), 0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6, // keccak256(bytes("1")) block.chainid, address(this) ) ); } function DOMAIN_SEPARATOR() public view virtual override returns (bytes32) { bytes32 domainSeparator; if (_CACHED_CHAIN_ID == block.chainid) domainSeparator = _DOMAIN_SEPARATOR; else { domainSeparator = keccak256( abi.encode( // keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)') 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f, keccak256(bytes(Strings.toHexString(uint160(address(this))))), 0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6, // keccak256(bytes("1")) block.chainid, address(this) ) ); } return domainSeparator; } function factory() public view virtual override returns (address) { return _factory; } function tokenURI(uint256 tokenId) public view override(ERC721Initializable, IERC721Metadata) returns (string memory) { require(_exists(tokenId) || _parked(tokenId), "SHOYU: INVALID_TOKEN_ID"); string memory _uri = _uris[tokenId]; if (bytes(_uri).length > 0) { return _uri; } else { string memory baseURI = __baseURI; if (bytes(baseURI).length > 0) { return string(abi.encodePacked(baseURI, Strings.toString(tokenId), ".json")); } else { baseURI = ITokenFactory(_factory).baseURI721(); string memory addy = Strings.toHexString(uint160(address(this)), 20); return string(abi.encodePacked(baseURI, addy, "/", Strings.toString(tokenId), ".json")); } } } function parked(uint256 tokenId) external view override returns (bool) { return _parked(tokenId); } function setTokenURI(uint256 id, string memory newURI) external override onlyOwner { _uris[id] = newURI; emit SetTokenURI(id, newURI); } function setBaseURI(string memory uri) external override onlyOwner { __baseURI = uri; emit SetBaseURI(uri); } function parkTokenIds(uint256 toTokenId) external override { require(owner() == msg.sender || _factory == msg.sender, "SHOYU: FORBIDDEN"); _parkTokenIds(toTokenId); emit ParkTokenIds(toTokenId); } function mint( address to, uint256 tokenId, bytes memory data ) external override { require(owner() == msg.sender || _factory == msg.sender, "SHOYU: FORBIDDEN"); _safeMint(to, tokenId, data); } function mintBatch( address to, uint256[] memory tokenIds, bytes memory data ) external override { require(owner() == msg.sender || _factory == msg.sender, "SHOYU: FORBIDDEN"); for (uint256 i = 0; i < tokenIds.length; i++) { _safeMint(to, tokenIds[i], data); } } function burn( uint256 tokenId, uint256 label, bytes32 data ) external override { require(ownerOf(tokenId) == msg.sender, "SHOYU: FORBIDDEN"); _burn(tokenId); emit Burn(tokenId, label, data); } function burnBatch(uint256[] memory tokenIds) external override { for (uint256 i = 0; i < tokenIds.length; i++) { uint256 tokenId = tokenIds[i]; require(ownerOf(tokenId) == msg.sender, "SHOYU: FORBIDDEN"); _burn(tokenId); } } function permit( address spender, uint256 tokenId, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external override { require(block.timestamp <= deadline, "SHOYU: EXPIRED"); address owner = ownerOf(tokenId); require(owner != address(0), "SHOYU: INVALID_TOKENID"); require(spender != owner, "SHOYU: NOT_NECESSARY"); bytes32 hash = keccak256(abi.encode(PERMIT_TYPEHASH, spender, tokenId, nonces[tokenId]++, deadline)); Signature.verify(hash, owner, v, r, s, DOMAIN_SEPARATOR()); _approve(spender, tokenId); } function permitAll( address owner, address spender, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external override { require(block.timestamp <= deadline, "SHOYU: EXPIRED"); require(owner != address(0), "SHOYU: INVALID_ADDRESS"); require(spender != owner, "SHOYU: NOT_NECESSARY"); bytes32 hash = keccak256(abi.encode(PERMIT_ALL_TYPEHASH, owner, spender, noncesForAll[owner]++, deadline)); Signature.verify(hash, owner, v, r, s, DOMAIN_SEPARATOR()); _setApprovalForAll(owner, spender, true); } } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol"; import "./IOwnable.sol"; interface IBaseNFT721 is IERC721, IERC721Metadata, IOwnable { event SetTokenURI(uint256 indexed tokenId, string uri); event SetBaseURI(string uri); event ParkTokenIds(uint256 toTokenId); event Burn(uint256 indexed tokenId, uint256 indexed label, bytes32 data); function PERMIT_TYPEHASH() external view returns (bytes32); function PERMIT_ALL_TYPEHASH() external view returns (bytes32); function DOMAIN_SEPARATOR() external view returns (bytes32); function factory() external view returns (address); function nonces(uint256 tokenId) external view returns (uint256); function noncesForAll(address account) external view returns (uint256); function parked(uint256 tokenId) external view returns (bool); function initialize( string calldata name, string calldata symbol, address _owner ) external; function setTokenURI(uint256 id, string memory uri) external; function setBaseURI(string memory uri) external; function parkTokenIds(uint256 toTokenId) external; function mint( address to, uint256 tokenId, bytes calldata data ) external; function mintBatch( address to, uint256[] calldata tokenIds, bytes calldata data ) external; function burn( uint256 tokenId, uint256 label, bytes32 data ) external; function burnBatch(uint256[] calldata tokenIds) external; function permit( address spender, uint256 tokenId, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; function permitAll( address owner, address spender, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; } // 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; 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.5.0; interface IOwnable { event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function owner() external view returns (address); function renounceOwnership() external; function transferOwnership(address newOwner) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant alphabet = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "@openzeppelin/contracts/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/Strings.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 ERC721Initializable is Initializable, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Upper bound of tokenId parked uint256 private _toTokenIdParked; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ function __ERC721_init(string memory name_, string memory symbol_) internal initializer { __ERC721_init_unchained(name_, symbol_); } function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer { _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), "SHOYU: INVALID_OWNER"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _owners[tokenId]; } /** * @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), "SHOYU: INVALID_TOKEN_ID"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. 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 = ERC721Initializable.ownerOf(tokenId); require(to != owner, "SHOYU: INVALID_TO"); require(msg.sender == owner || isApprovedForAll(owner, msg.sender), "SHOYU: FORBIDDEN"); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "SHOYU: INVALID_TOKEN_ID"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(msg.sender, 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(msg.sender, tokenId), "SHOYU: NOT_APPROVED_NOR_OWNER"); _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(msg.sender, tokenId), "SHOYU: FORBIDDEN"); _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), "SHOYU: INVALID_RECEIVER"); } /** * @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), "SHOYU: INVALID_TOKEN_ID"); address owner = ERC721Initializable.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } function _setApprovalForAll( address owner, address operator, bool approved ) internal { require(operator != owner, "SHOYU: INVALID_OPERATOR"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } function _parked(uint256 tokenId) internal view virtual returns (bool) { address owner = ERC721Initializable.ownerOf(tokenId); return owner == address(0) && tokenId < _toTokenIdParked; } function _parkTokenIds(uint256 toTokenId) internal virtual { uint256 fromTokenId = _toTokenIdParked; require(toTokenId > fromTokenId, "SHOYU: INVALID_TO_TOKEN_ID"); _toTokenIdParked = toTokenId; } /** * @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), "SHOYU: INVALID_RECEIVER"); } /** * @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), "SHOYU: INVALID_TO"); require(!_exists(tokenId), "SHOYU: 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 = ERC721Initializable.ownerOf(tokenId); require(owner != address(0), "SHOYU: INVALID_TOKEN_ID"); _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(ERC721Initializable.ownerOf(tokenId) == from, "SHOYU: TRANSFER_FORBIDDEN"); require(to != address(0), "SHOYU: INVALID_RECIPIENT"); _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(ERC721Initializable.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(msg.sender, from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("SHOYU: INVALID_RECEIVER"); } else { // solhint-disable-next-line no-inline-assembly 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` 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 {} } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "@openzeppelin/contracts/proxy/utils/Initializable.sol"; import "../interfaces/IOwnable.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 OwnableInitializable is Initializable, IOwnable { address private _owner; /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init(address __owner) internal initializer { __Ownable_init_unchained(__owner); } function __Ownable_init_unchained(address __owner) internal initializer { _owner = __owner; emit OwnershipTransferred(address(0), __owner); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual override returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == msg.sender, "SHOYU: FORBIDDEN"); _; } /** * @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 override 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 override onlyOwner { require(newOwner != address(0), "SHOYU: INVALID_NEW_OWNER"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // 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; /** * @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.3; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "./interfaces/ITokenFactory.sol"; import "./interfaces/IBaseNFT721.sol"; import "./interfaces/IBaseNFT1155.sol"; import "./interfaces/ISocialToken.sol"; import "./base/ProxyFactory.sol"; import "./libraries/Signature.sol"; contract TokenFactory is ProxyFactory, Ownable, ITokenFactory { uint8 public constant override MAX_ROYALTY_FEE = 250; // 25% uint8 public constant override MAX_OPERATIONAL_FEE = 50; // 5% // keccak256("ParkTokenIds721(address nft,uint256 toTokenId,uint256 nonce)"); bytes32 public constant override PARK_TOKEN_IDS_721_TYPEHASH = 0x3fddacac0a7d8b05f741f01ff6becadd9986be8631a2af41a675f365dd74090d; // keccak256("MintBatch721(address nft,address to,uint256[] tokenIds,bytes data,uint256 nonce)"); bytes32 public constant override MINT_BATCH_721_TYPEHASH = 0x884adba7f4e17962aed36c871036adea39c6d9f81fb25407a78db239e9731e86; // keccak256("MintBatch1155(address nft,address to,uint256[] tokenIds,uint256[] amounts,bytes data,uint256 nonce)"); bytes32 public constant override MINT_BATCH_1155_TYPEHASH = 0xb47ce0f6456fcc2f16b7d6e7b0255eb73822b401248e672a4543c2b3d7183043; // keccak256("MintSocialToken(address token,address to,uint256 amount,uint256 nonce)"); bytes32 public constant override MINT_SOCIAL_TOKEN_TYPEHASH = 0x8f4bf92e5271f5ec2f59dc3fc74368af0064fb84b40a3de9150dd26c08cda104; bytes32 internal immutable _DOMAIN_SEPARATOR; uint256 internal immutable _CACHED_CHAIN_ID; address[] internal _targets721; address[] internal _targets1155; address[] internal _targetsSocialToken; address internal _protocolFeeRecipient; uint8 internal _protocolFee; // out of 1000 address internal _operationalFeeRecipient; uint8 internal _operationalFee; // out of 1000 mapping(address => uint256) public override nonces; string public override baseURI721; string public override baseURI1155; address public override erc721Exchange; address public override erc1155Exchange; // any account can deploy proxies if isDeployerWhitelisted[0x0000000000000000000000000000000000000000] == true mapping(address => bool) public override isDeployerWhitelisted; mapping(address => bool) public override isStrategyWhitelisted; modifier onlyDeployer { require(isDeployerWhitelisted[address(0)] || isDeployerWhitelisted[msg.sender], "SHOYU: FORBIDDEN"); _; } constructor( address protocolFeeRecipient, uint8 protocolFee, address operationalFeeRecipient, uint8 operationalFee, string memory _baseURI721, string memory _baseURI1155 ) { _protocolFeeRecipient = protocolFeeRecipient; _protocolFee = protocolFee; _operationalFeeRecipient = operationalFeeRecipient; _operationalFee = operationalFee; baseURI721 = _baseURI721; baseURI1155 = _baseURI1155; _CACHED_CHAIN_ID = block.chainid; _DOMAIN_SEPARATOR = keccak256( abi.encode( // keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)') 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f, keccak256(bytes(Strings.toHexString(uint160(address(this))))), 0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6, // keccak256(bytes("1")) block.chainid, address(this) ) ); } function DOMAIN_SEPARATOR() public view override returns (bytes32) { bytes32 domainSeparator; if (_CACHED_CHAIN_ID == block.chainid) domainSeparator = _DOMAIN_SEPARATOR; else { domainSeparator = keccak256( abi.encode( // keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)') 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f, keccak256(bytes(Strings.toHexString(uint160(address(this))))), 0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6, // keccak256(bytes("1")) block.chainid, address(this) ) ); } return domainSeparator; } function protocolFeeInfo() external view override returns (address recipient, uint8 permil) { return (_protocolFeeRecipient, _protocolFee); } function operationalFeeInfo() external view override returns (address recipient, uint8 permil) { return (_operationalFeeRecipient, _operationalFee); } // This function should be called with a proper param by a multi-sig `owner` function setBaseURI721(string memory uri) external override onlyOwner { baseURI721 = uri; emit SetBaseURI721(uri); } // This function should be called with a proper param by a multi-sig `owner` function setBaseURI1155(string memory uri) external override onlyOwner { baseURI1155 = uri; emit SetBaseURI1155(uri); } // This function should be called by a multi-sig `owner`, not an EOA function setProtocolFeeRecipient(address protocolFeeRecipient) external override onlyOwner { require(protocolFeeRecipient != address(0), "SHOYU: INVALID_FEE_RECIPIENT"); _protocolFeeRecipient = protocolFeeRecipient; emit SetProtocolFeeRecipient(protocolFeeRecipient); } // This function should be called by a multi-sig `owner`, not an EOA function setOperationalFeeRecipient(address operationalFeeRecipient) external override onlyOwner { require(operationalFeeRecipient != address(0), "SHOYU: INVALID_RECIPIENT"); _operationalFeeRecipient = operationalFeeRecipient; emit SetOperationalFeeRecipient(operationalFeeRecipient); } // This function should be called by a multi-sig `owner`, not an EOA function setOperationalFee(uint8 operationalFee) external override onlyOwner { require(operationalFee <= MAX_OPERATIONAL_FEE, "SHOYU: INVALID_FEE"); _operationalFee = operationalFee; emit SetOperationalFee(operationalFee); } // This function should be called by a multi-sig `owner`, not an EOA function setDeployerWhitelisted(address deployer, bool whitelisted) external override onlyOwner { isDeployerWhitelisted[deployer] = whitelisted; emit SetDeployerWhitelisted(deployer, whitelisted); } // This function should be called by a multi-sig `owner`, not an EOA function setStrategyWhitelisted(address strategy, bool whitelisted) external override onlyOwner { require(strategy != address(0), "SHOYU: INVALID_ADDRESS"); isStrategyWhitelisted[strategy] = whitelisted; emit SetStrategyWhitelisted(strategy, whitelisted); } // This function should be called by a multi-sig `owner`, not an EOA function upgradeNFT721(address newTarget) external override onlyOwner { _targets721.push(newTarget); emit UpgradeNFT721(newTarget); } // This function should be called by a multi-sig `owner`, not an EOA function upgradeNFT1155(address newTarget) external override onlyOwner { _targets1155.push(newTarget); emit UpgradeNFT1155(newTarget); } // This function should be called by a multi-sig `owner`, not an EOA function upgradeSocialToken(address newTarget) external override onlyOwner { _targetsSocialToken.push(newTarget); emit UpgradeSocialToken(newTarget); } // This function should be called by a multi-sig `owner`, not an EOA function upgradeERC721Exchange(address exchange) external override onlyOwner { erc721Exchange = exchange; emit UpgradeERC721Exchange(exchange); } // This function should be called by a multi-sig `owner`, not an EOA function upgradeERC1155Exchange(address exchange) external override onlyOwner { erc1155Exchange = exchange; emit UpgradeERC1155Exchange(exchange); } function deployNFT721AndMintBatch( address owner, string calldata name, string calldata symbol, uint256[] memory tokenIds, address royaltyFeeRecipient, uint8 royaltyFee ) external override onlyDeployer returns (address nft) { require(bytes(name).length > 0, "SHOYU: INVALID_NAME"); require(bytes(symbol).length > 0, "SHOYU: INVALID_SYMBOL"); require(owner != address(0), "SHOYU: INVALID_ADDRESS"); nft = _createProxy( _targets721[_targets721.length - 1], abi.encodeWithSignature( "initialize(address,string,string,uint256[],address,uint8)", owner, name, symbol, tokenIds, royaltyFeeRecipient, royaltyFee ) ); emit DeployNFT721AndMintBatch(nft, owner, name, symbol, tokenIds, royaltyFeeRecipient, royaltyFee); } function deployNFT721AndPark( address owner, string calldata name, string calldata symbol, uint256 toTokenId, address royaltyFeeRecipient, uint8 royaltyFee ) external override onlyDeployer returns (address nft) { require(bytes(name).length > 0, "SHOYU: INVALID_NAME"); require(bytes(symbol).length > 0, "SHOYU: INVALID_SYMBOL"); require(owner != address(0), "SHOYU: INVALID_ADDRESS"); nft = _createProxy( _targets721[_targets721.length - 1], abi.encodeWithSignature( "initialize(address,string,string,uint256,address,uint8)", owner, name, symbol, toTokenId, royaltyFeeRecipient, royaltyFee ) ); emit DeployNFT721AndPark(nft, owner, name, symbol, toTokenId, royaltyFeeRecipient, royaltyFee); } function isNFT721(address query) external view override returns (bool result) { if (query == address(0)) return false; for (uint256 i = _targets721.length; i >= 1; i--) { if (_isProxy(_targets721[i - 1], query)) { return true; } } return false; } function deployNFT1155AndMintBatch( address owner, uint256[] memory tokenIds, uint256[] memory amounts, address royaltyFeeRecipient, uint8 royaltyFee ) external override onlyDeployer returns (address nft) { require(owner != address(0), "SHOYU: INVALID_ADDRESS"); require(tokenIds.length == amounts.length, "SHOYU: LENGTHS_NOT_EQUAL"); nft = _createProxy( _targets1155[_targets1155.length - 1], abi.encodeWithSignature( "initialize(address,uint256[],uint256[],address,uint8)", owner, tokenIds, amounts, royaltyFeeRecipient, royaltyFee ) ); emit DeployNFT1155AndMintBatch(nft, owner, tokenIds, amounts, royaltyFeeRecipient, royaltyFee); } function isNFT1155(address query) external view override returns (bool result) { if (query == address(0)) return false; for (uint256 i = _targets1155.length; i >= 1; i--) { if (_isProxy(_targets1155[i - 1], query)) { return true; } } return false; } function deploySocialToken( address owner, string memory name, string memory symbol, address dividendToken, uint256 initialSupply ) external override onlyDeployer returns (address proxy) { require(bytes(name).length > 0, "SHOYU: INVALID_NAME"); require(bytes(symbol).length > 0, "SHOYU: INVALID_SYMBOL"); require(owner != address(0), "SHOYU: INVALID_ADDRESS"); bytes memory initData = abi.encodeWithSignature( "initialize(address,string,string,address,uint256)", owner, name, symbol, dividendToken, initialSupply ); proxy = _createProxy(_targetsSocialToken[_targetsSocialToken.length - 1], initData); emit DeploySocialToken(proxy, owner, name, symbol, dividendToken, initialSupply); } function isSocialToken(address query) external view override returns (bool result) { if (query == address(0)) return false; for (uint256 i = _targetsSocialToken.length; i >= 1; i--) { if (_isProxy(_targetsSocialToken[i - 1], query)) { return true; } } return false; } function parkTokenIds721( address nft, uint256 toTokenId, uint8 v, bytes32 r, bytes32 s ) external override { address owner = IBaseNFT721(nft).owner(); bytes32 hash = keccak256(abi.encode(PARK_TOKEN_IDS_721_TYPEHASH, nft, toTokenId, nonces[owner]++)); Signature.verify(hash, owner, v, r, s, DOMAIN_SEPARATOR()); IBaseNFT721(nft).parkTokenIds(toTokenId); } function mintBatch721( address nft, address to, uint256[] calldata tokenIds, bytes calldata data, uint8 v, bytes32 r, bytes32 s ) external override { address owner = IBaseNFT721(nft).owner(); bytes32 hash = keccak256(abi.encode(MINT_BATCH_721_TYPEHASH, nft, to, tokenIds, data, nonces[owner]++)); Signature.verify(hash, owner, v, r, s, DOMAIN_SEPARATOR()); IBaseNFT721(nft).mintBatch(to, tokenIds, data); } function mintBatch1155( address nft, address to, uint256[] calldata tokenIds, uint256[] calldata amounts, bytes calldata data, uint8 v, bytes32 r, bytes32 s ) external override { address owner = IBaseNFT1155(nft).owner(); bytes32 hash = keccak256(abi.encode(MINT_BATCH_1155_TYPEHASH, nft, to, tokenIds, amounts, data, nonces[owner]++)); Signature.verify(hash, owner, v, r, s, DOMAIN_SEPARATOR()); IBaseNFT1155(nft).mintBatch(to, tokenIds, amounts, data); } function mintSocialToken( address token, address to, uint256 amount, uint8 v, bytes32 r, bytes32 s ) external override { address owner = ISocialToken(token).owner(); bytes32 hash = keccak256(abi.encode(MINT_SOCIAL_TOKEN_TYPEHASH, token, to, amount, nonces[owner]++)); Signature.verify(hash, owner, v, r, s, DOMAIN_SEPARATOR()); ISocialToken(token).mint(to, amount); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0; import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import "@openzeppelin/contracts/token/ERC1155/extensions/IERC1155MetadataURI.sol"; import "./IOwnable.sol"; interface IBaseNFT1155 is IERC1155, IERC1155MetadataURI, IOwnable { event SetURI(uint256 indexed id, string uri); event SetBaseURI(string uri); event Burn(uint256 indexed tokenId, uint256 amount, uint256 indexed label, bytes32 data); function PERMIT_TYPEHASH() external view returns (bytes32); function DOMAIN_SEPARATOR() external view returns (bytes32); function factory() external view returns (address); function nonces(address account) external view returns (uint256); function initialize(address _owner) external; function setURI(uint256 id, string memory uri) external; function setBaseURI(string memory baseURI) external; function mint( address to, uint256 tokenId, uint256 amount, bytes calldata data ) external; function mintBatch( address to, uint256[] calldata tokenIds, uint256[] calldata amounts, bytes calldata data ) external; function burn( uint256 tokenId, uint256 amount, uint256 label, bytes32 data ) external; function burnBatch(uint256[] calldata tokenIds, uint256[] calldata amounts) external; function permit( address owner, address spender, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0; import "./IDividendPayingERC20.sol"; import "./IOwnable.sol"; interface ISocialToken is IDividendPayingERC20, IOwnable { event Burn(uint256 amount, uint256 indexed label, bytes32 data); function initialize( address owner, string memory name, string memory symbol, address dividendToken, uint256 initialSupply ) external; function PERMIT_TYPEHASH() external view returns (bytes32); function DOMAIN_SEPARATOR() external view returns (bytes32); function factory() external view returns (address); function nonces(address owner) external view returns (uint256); function mint(address account, uint256 value) external; function burn( uint256 value, uint256 id, bytes32 data ) external; function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; // Reference: https://github.com/optionality/clone-factory/blob/master/contracts/CloneFactory.sol contract ProxyFactory { function _createProxy(address target, bytes memory initData) internal returns (address proxy) { bytes20 targetBytes = bytes20(target); assembly { let clone := mload(0x40) mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(clone, 0x14), targetBytes) mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) proxy := create(0, clone, 0x37) } if (initData.length > 0) { (bool success, ) = proxy.call(initData); require(success, "SHOYU: CALL_FAILURE"); } } function _isProxy(address target, address query) internal view returns (bool result) { bytes20 targetBytes = bytes20(target); assembly { let clone := mload(0x40) mstore(clone, 0x363d3d373d3d3d363d7300000000000000000000000000000000000000000000) mstore(add(clone, 0xa), targetBytes) mstore(add(clone, 0x1e), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) let other := add(clone, 0x40) extcodecopy(query, other, 0, 0x2d) result := and(eq(mload(clone), mload(other)), eq(mload(add(clone, 0xd)), mload(add(other, 0xd)))) } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC1155.sol"; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "./interfaces/IPaymentSplitterFactory.sol"; import "./base/ProxyFactory.sol"; import "./PaymentSplitter.sol"; contract PaymentSplitterFactory is ProxyFactory, IPaymentSplitterFactory { address internal _target; constructor() { PaymentSplitter target = new PaymentSplitter(); address[] memory payees = new address[](1); payees[0] = msg.sender; uint256[] memory shares = new uint256[](1); shares[0] = 1; target.initialize("", payees, shares); _target = address(target); } function deployPaymentSplitter( address owner, string calldata title, address[] calldata payees, uint256[] calldata shares ) external override returns (address splitter) { splitter = _createProxy( _target, abi.encodeWithSignature("initialize(string,address[],uint256[])", title, payees, shares) ); emit DeployPaymentSplitter(owner, title, payees, shares, splitter); } function isPaymentSplitter(address query) external view override returns (bool result) { return _isProxy(_target, query); } } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0; interface IPaymentSplitterFactory { event DeployPaymentSplitter( address indexed owner, string title, address[] payees, uint256[] shares, address splitter ); function deployPaymentSplitter( address owner, string calldata title, address[] calldata payees, uint256[] calldata shares ) external returns (address splitter); function isPaymentSplitter(address query) external view returns (bool result); } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "@openzeppelin/contracts/proxy/utils/Initializable.sol"; import "./interfaces/IPaymentSplitter.sol"; import "./libraries/TokenHelper.sol"; // Reference: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/finance/PaymentSplitter.sol contract PaymentSplitter is Initializable, IPaymentSplitter { using TokenHelper for address; string public override title; /** * @dev Getter for the total shares held by payees. */ uint256 public override totalShares; /** * @dev Getter for the total amount of token already released. */ mapping(address => uint256) public override totalReleased; /** * @dev Getter for the amount of shares held by an account. */ mapping(address => uint256) public override shares; /** * @dev Getter for the amount of token already released to a payee. */ mapping(address => mapping(address => uint256)) public override released; /** * @dev Getter for the address of the payee number `index`. */ address[] public override payees; /** * @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at * the matching position in the `shares` array. * * All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no * duplicates in `payees`. */ function initialize( string calldata _title, address[] calldata _payees, uint256[] calldata _shares ) external override initializer { require(_payees.length == _shares.length, "SHOYU: LENGTHS_NOT_EQUAL"); require(_payees.length > 0, "SHOYU: LENGTH_TOO_SHORT"); title = _title; for (uint256 i = 0; i < _payees.length; i++) { _addPayee(_payees[i], _shares[i]); } } /** * @dev Triggers a transfer to `account` of the amount of token they are owed, according to their percentage of the * total shares and their previous withdrawals. */ function release(address token, address account) external virtual override { require(shares[account] > 0, "SHOYU: FORBIDDEN"); uint256 totalReceived = token.balanceOf(address(this)) + totalReleased[token]; uint256 payment = (totalReceived * shares[account]) / totalShares - released[token][account]; require(payment != 0, "SHOYU: NO_PAYMENT"); released[token][account] += payment; totalReleased[token] += payment; token.safeTransfer(account, payment); emit PaymentReleased(token, account, payment); } /** * @dev Add a new payee to the contract. * @param account The address of the payee to add. * @param _shares The number of shares owned by the payee. */ function _addPayee(address account, uint256 _shares) private { require(account != address(0), "SHOYU: INVALID_ADDRESS"); require(_shares > 0, "SHOYU: INVALID_SHARES"); require(shares[account] == 0, "SHOYU: ALREADY_ADDED"); payees.push(account); shares[account] = _shares; totalShares = totalShares + _shares; emit PayeeAdded(account, _shares); } } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0; interface IPaymentSplitter { event PayeeAdded(address account, uint256 shares); event PaymentReleased(address token, address to, uint256 amount); function initialize( string calldata _title, address[] calldata _payees, uint256[] calldata _shares ) external; function title() external view returns (string memory); function totalShares() external view returns (uint256); function totalReleased(address account) external view returns (uint256); function shares(address account) external view returns (uint256); function released(address token, address account) external view returns (uint256); function payees(uint256 index) external view returns (address); function release(address token, address account) external; } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; library TokenHelper { using SafeERC20 for IERC20; address public constant ETH = 0x0000000000000000000000000000000000000000; function balanceOf(address token, address account) internal view returns (uint256) { if (token == ETH) { return account.balance; } else { return IERC20(token).balanceOf(account); } } function safeTransfer( address token, address to, uint256 amount ) internal { if (token == ETH) { (bool success, ) = to.call{value: amount}(""); require(success, "SHOYU: TRANSFER_FAILURE"); } else { IERC20(token).safeTransfer(to, amount); } } } // 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}. 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(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { // solhint-disable-next-line no-inline-assembly 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` 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 { } } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "../interfaces/IERC2981.sol"; contract ERC721RoyaltyMock is ERC721("Mock", "MOCK") { address public owner; constructor() { owner = msg.sender; } function safeMint( address to, uint256 tokenId, bytes memory data ) external { _safeMint(to, tokenId, data); } function safeMintBatch0( address[] calldata to, uint256[] calldata tokenId, bytes memory data ) external { require(to.length == tokenId.length); for (uint256 i = 0; i < to.length; i++) { _safeMint(to[i], tokenId[i], data); } } function safeMintBatch1( address to, uint256[] calldata tokenId, bytes memory data ) external { for (uint256 i = 0; i < tokenId.length; i++) { _safeMint(to, tokenId[i], data); } } function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == 0x2a55205a || super.supportsInterface(interfaceId); } function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view returns (address, uint256) { uint256 fee = 100; if (_tokenId < 10) fee = 10; return (owner, (_salePrice * fee) / 1000); } } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "./interfaces/INFT1155.sol"; import "./interfaces/IERC2981.sol"; import "./base/BaseNFT1155.sol"; import "./base/BaseExchange.sol"; contract NFT1155V0 is BaseNFT1155, BaseExchange, IERC2981, INFT1155 { uint8 internal _MAX_ROYALTY_FEE; address internal _royaltyFeeRecipient; uint8 internal _royaltyFee; // out of 1000 function initialize( address _owner, uint256[] memory tokenIds, uint256[] memory amounts, address royaltyFeeRecipient, uint8 royaltyFee ) external override initializer { __BaseNFTExchange_init(); initialize(_owner); _MAX_ROYALTY_FEE = ITokenFactory(_factory).MAX_ROYALTY_FEE(); if (tokenIds.length > 0) { _mintBatch(_owner, tokenIds, amounts, ""); } _setRoyaltyFeeRecipient(royaltyFeeRecipient); _royaltyFee = type(uint8).max; if (royaltyFee != 0) _setRoyaltyFee(royaltyFee); } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC1155Initializable, IERC165) returns (bool) { return interfaceId == 0x2a55205a || super.supportsInterface(interfaceId); } function DOMAIN_SEPARATOR() public view override(BaseNFT1155, BaseExchange, INFT1155) returns (bytes32) { return BaseNFT1155.DOMAIN_SEPARATOR(); } function factory() public view override(BaseNFT1155, BaseExchange, INFT1155) returns (address) { return _factory; } function royaltyInfo(uint256, uint256 _salePrice) external view override returns (address, uint256) { uint256 royaltyAmount; if (_royaltyFee != type(uint8).max) royaltyAmount = (_salePrice * _royaltyFee) / 1000; return (_royaltyFeeRecipient, royaltyAmount); } function _transfer( address, address from, address to, uint256 tokenId, uint256 amount ) internal override { _transfer(from, to, tokenId, amount); emit TransferSingle(msg.sender, from, to, tokenId, amount); } function setRoyaltyFeeRecipient(address royaltyFeeRecipient) public override onlyOwner { _setRoyaltyFeeRecipient(royaltyFeeRecipient); } function setRoyaltyFee(uint8 royaltyFee) public override onlyOwner { _setRoyaltyFee(royaltyFee); } function _setRoyaltyFeeRecipient(address royaltyFeeRecipient) internal { require(royaltyFeeRecipient != address(0), "SHOYU: INVALID_FEE_RECIPIENT"); _royaltyFeeRecipient = royaltyFeeRecipient; emit SetRoyaltyFeeRecipient(royaltyFeeRecipient); } function _setRoyaltyFee(uint8 royaltyFee) internal { if (_royaltyFee == type(uint8).max) { require(royaltyFee <= _MAX_ROYALTY_FEE, "SHOYU: INVALID_FEE"); } else { require(royaltyFee < _royaltyFee, "SHOYU: INVALID_FEE"); } _royaltyFee = royaltyFee; emit SetRoyaltyFee(royaltyFee); } } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0; import "./IBaseNFT1155.sol"; import "./IBaseExchange.sol"; interface INFT1155 is IBaseNFT1155, IBaseExchange { event SetRoyaltyFeeRecipient(address recipient); event SetRoyaltyFee(uint8 fee); function initialize( address _owner, uint256[] calldata tokenIds, uint256[] calldata amounts, address royaltyFeeRecipient, uint8 royaltyFee ) external; function DOMAIN_SEPARATOR() external view override(IBaseNFT1155, IBaseExchange) returns (bytes32); function factory() external view override(IBaseNFT1155, IBaseExchange) returns (address); function setRoyaltyFeeRecipient(address _royaltyFeeRecipient) external; function setRoyaltyFee(uint8 _royaltyFee) external; } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "@openzeppelin/contracts/utils/Strings.sol"; import "../interfaces/IBaseNFT1155.sol"; import "../interfaces/IERC1271.sol"; import "../interfaces/ITokenFactory.sol"; import "../base/ERC1155Initializable.sol"; import "../base/OwnableInitializable.sol"; import "../libraries/Signature.sol"; abstract contract BaseNFT1155 is ERC1155Initializable, OwnableInitializable, IBaseNFT1155 { using Strings for uint256; // keccak256("Permit(address owner,address spender,uint256 nonce,uint256 deadline)"); bytes32 public constant override PERMIT_TYPEHASH = 0xdaab21af31ece73a508939fedd476a5ee5129a5ed4bb091f3236ffb45394df62; bytes32 internal _DOMAIN_SEPARATOR; uint256 internal _CACHED_CHAIN_ID; uint8 internal MAX_ROYALTY_FEE; address internal _factory; string internal _baseURI; mapping(uint256 => string) internal _uris; mapping(address => uint256) public override nonces; function initialize(address _owner) public override initializer { __ERC1155_init(""); __Ownable_init(_owner); _factory = msg.sender; _CACHED_CHAIN_ID = block.chainid; _DOMAIN_SEPARATOR = keccak256( abi.encode( // keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)') 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f, keccak256(bytes(Strings.toHexString(uint160(address(this))))), 0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6, // keccak256(bytes("1")) block.chainid, address(this) ) ); } function DOMAIN_SEPARATOR() public view virtual override returns (bytes32) { bytes32 domainSeparator; if (_CACHED_CHAIN_ID == block.chainid) domainSeparator = _DOMAIN_SEPARATOR; else { domainSeparator = keccak256( abi.encode( // keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)') 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f, keccak256(bytes(Strings.toHexString(uint160(address(this))))), 0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6, // keccak256(bytes("1")) block.chainid, address(this) ) ); } return domainSeparator; } function factory() public view virtual override returns (address) { return _factory; } function uri(uint256 id) public view virtual override(ERC1155Initializable, IERC1155MetadataURI) returns (string memory) { string memory _uri = _uris[id]; if (bytes(_uri).length > 0) { return _uri; } else { string memory baseURI = _baseURI; if (bytes(baseURI).length > 0) { return string(abi.encodePacked(baseURI, "{id}.json")); } else { baseURI = ITokenFactory(_factory).baseURI1155(); string memory addy = Strings.toHexString(uint160(address(this)), 20); return string(abi.encodePacked(baseURI, addy, "/{id}.json")); } } } function setURI(uint256 id, string memory newURI) external override onlyOwner { _uris[id] = newURI; emit SetURI(id, newURI); } function setBaseURI(string memory baseURI) external override onlyOwner { _baseURI = baseURI; emit SetBaseURI(baseURI); } function mint( address to, uint256 tokenId, uint256 amount, bytes memory data ) external override { require(owner() == msg.sender || _factory == msg.sender, "SHOYU: FORBIDDEN"); _mint(to, tokenId, amount, data); } function mintBatch( address to, uint256[] memory tokenIds, uint256[] memory amounts, bytes memory data ) external override { require(owner() == msg.sender || _factory == msg.sender, "SHOYU: FORBIDDEN"); _mintBatch(to, tokenIds, amounts, data); } function burn( uint256 tokenId, uint256 amount, uint256 label, bytes32 data ) external override { _burn(msg.sender, tokenId, amount); emit Burn(tokenId, amount, label, data); } function burnBatch(uint256[] calldata tokenIds, uint256[] calldata amounts) external override { _burnBatch(msg.sender, tokenIds, amounts); } function permit( address owner, address spender, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external override { require(block.timestamp <= deadline, "SHOYU: EXPIRED"); require(owner != address(0), "SHOYU: INVALID_ADDRESS"); require(spender != owner, "SHOYU: NOT_NECESSARY"); bytes32 hash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, nonces[owner]++, deadline)); Signature.verify(hash, owner, v, r, s, DOMAIN_SEPARATOR()); _setApprovalForAll(owner, spender, true); } } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "@openzeppelin/contracts/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import "@openzeppelin/contracts/token/ERC1155/extensions/IERC1155MetadataURI.sol"; import "@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol"; import "@openzeppelin/contracts/utils/Address.sol"; /** * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155Initializable is Initializable, ERC165, IERC1155, IERC1155MetadataURI { using Address for address; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /** * @dev See {_setURI}. */ function __ERC1155_init(string memory uri_) internal initializer { __ERC1155_init_unchained(uri_); } function __ERC1155_init_unchained(string memory uri_) internal initializer { _setURI(uri_); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) public view virtual override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "SHOYU: INVALID_ADDRESS"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view virtual override returns (uint256[] memory) { require(accounts.length == ids.length, "SHOYU: LENGTHS_NOT_EQUAL"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(msg.sender, operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require(to != address(0), "SHOYU: INVALID_ADDRESS"); require(from == msg.sender || isApprovedForAll(from, msg.sender), "SHOYU: FORBIDDEN"); address operator = msg.sender; _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); _transfer(from, to, id, amount); emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } function _transfer( address from, address to, uint256 id, uint256 amount ) internal { uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "SHOYU: INSUFFICIENT_BALANCE"); _balances[id][from] = fromBalance - amount; _balances[id][to] += amount; } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require(ids.length == amounts.length, "SHOYU: LENGTHS_NOT_EQUAL"); require(to != address(0), "SHOYU: INVALID_ADDRESS"); require(from == msg.sender || isApprovedForAll(from, msg.sender), "SHOYU: FORBIDDEN"); address operator = msg.sender; _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "SHOYU: INSUFFICIENT_BALANCE"); _balances[id][from] = fromBalance - amount; _balances[id][to] += amount; } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } function _setApprovalForAll( address account, address operator, bool approved ) internal { require(account != operator, "SHOYU: NOT_ALLOWED"); _operatorApprovals[account][operator] = approved; emit ApprovalForAll(account, operator, approved); } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `account`. * * Emits a {TransferSingle} event. * * Requirements: * * - `account` cannot be the zero address. * - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint( address account, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(account != address(0), "SHOYU: INVALID_ADDRESS"); address operator = msg.sender; _beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][account] += amount; emit TransferSingle(operator, address(0), account, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(to != address(0), "SHOYU: INVALID_ADDRESS"); require(ids.length == amounts.length, "SHOYU: LENGTHS_NOT_EQUAL"); address operator = msg.sender; _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint256 i = 0; i < ids.length; i++) { _balances[ids[i]][to] += amounts[i]; } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `account` * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens of token type `id`. */ function _burn( address account, uint256 id, uint256 amount ) internal virtual { require(account != address(0), "SHOYU: INVALID_ADDRESS"); address operator = msg.sender; _beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); uint256 accountBalance = _balances[id][account]; require(accountBalance >= amount, "SHOYU: INSUFFICIENT_BALANCE"); _balances[id][account] = accountBalance - amount; emit TransferSingle(operator, account, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch( address account, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(account != address(0), "SHOYU: INVALID_ADDRESS"); require(ids.length == amounts.length, "SHOYU: LENGTHS_NOT_EQUAL"); address operator = msg.sender; _beforeTokenTransfer(operator, account, address(0), ids, amounts, ""); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 accountBalance = _balances[id][account]; require(accountBalance >= amount, "SHOYU: INSUFFICIENT_BALANCE"); _balances[id][account] = accountBalance - amount; } emit TransferBatch(operator, account, address(0), ids, amounts); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver(to).onERC1155Received.selector) { revert("SHOYU: INVALID_RECEIVER"); } } catch Error(string memory reason) { revert(reason); } catch { revert("SHOYU: NO_RECEIVER"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns ( bytes4 response ) { if (response != IERC1155Receiver(to).onERC1155BatchReceived.selector) { revert("SHOYU: INVALID_RECEIVER"); } } catch Error(string memory reason) { revert(reason); } catch { revert("SHOYU: NO_RECEIVER"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns(bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns(bytes4); } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "@openzeppelin/contracts/utils/Strings.sol"; import "./base/DividendPayingERC20.sol"; import "./base/OwnableInitializable.sol"; import "./interfaces/ISocialToken.sol"; import "./libraries/Signature.sol"; contract SocialTokenV0 is DividendPayingERC20, OwnableInitializable, ISocialToken { // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant override PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; bytes32 internal _DOMAIN_SEPARATOR; uint256 internal _CACHED_CHAIN_ID; address internal _factory; mapping(address => uint256) public override nonces; function initialize( address _owner, string memory _name, string memory _symbol, address _dividendToken, uint256 initialSupply ) external override initializer { __Ownable_init(_owner); __DividendPayingERC20_init(_name, _symbol, _dividendToken); _factory = msg.sender; _mint(_owner, initialSupply); _CACHED_CHAIN_ID = block.chainid; _DOMAIN_SEPARATOR = keccak256( abi.encode( // keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)') 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f, keccak256(bytes(Strings.toHexString(uint160(address(this))))), 0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6, // keccak256(bytes("1")) block.chainid, address(this) ) ); } function DOMAIN_SEPARATOR() public view override returns (bytes32) { bytes32 domainSeparator; if (_CACHED_CHAIN_ID == block.chainid) domainSeparator = _DOMAIN_SEPARATOR; else { domainSeparator = keccak256( abi.encode( // keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)') 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f, keccak256(bytes(Strings.toHexString(uint160(address(this))))), 0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6, // keccak256(bytes("1")) block.chainid, address(this) ) ); } return domainSeparator; } function factory() public view override returns (address) { return _factory; } function mint(address account, uint256 value) external override { require(owner() == msg.sender || _factory == msg.sender, "SHOYU: FORBIDDEN"); _mint(account, value); } function burn( uint256 value, uint256 label, bytes32 data ) external override { _burn(msg.sender, value); emit Burn(value, label, data); } function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external override { require(block.timestamp <= deadline, "SHOYU: EXPIRED"); require(owner != address(0), "SHOYU: INVALID_ADDRESS"); require(spender != owner, "SHOYU: NOT_NECESSARY"); bytes32 hash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline)); Signature.verify(hash, owner, v, r, s, DOMAIN_SEPARATOR()); _approve(owner, spender, value); } } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "@openzeppelin/contracts/utils/math/SafeCast.sol"; import "./ERC20Initializable.sol"; import "../libraries/TokenHelper.sol"; import "../interfaces/IDividendPayingERC20.sol"; /// @dev A mintable ERC20 token that allows anyone to pay and distribute ether/erc20 /// to token holders as dividends and allows token holders to withdraw their dividends. /// Reference: https://github.com/Roger-Wu/erc1726-dividend-paying-token/blob/master/contracts/DividendPayingToken.sol abstract contract DividendPayingERC20 is ERC20Initializable, IDividendPayingERC20 { using SafeCast for uint256; using SafeCast for int256; using TokenHelper for address; // For more discussion about choosing the value of `magnitude`, // see https://github.com/ethereum/EIPs/issues/1726#issuecomment-472352728 uint256 public constant override MAGNITUDE = 2**128; address public override dividendToken; uint256 public override totalDividend; uint256 internal magnifiedDividendPerShare; function __DividendPayingERC20_init( string memory _name, string memory _symbol, address _dividendToken ) internal initializer { __ERC20_init(_name, _symbol); dividendToken = _dividendToken; } // About dividendCorrection: // If the token balance of a `_user` is never changed, the dividend of `_user` can be computed with: // `dividendOf(_user) = dividendPerShare * balanceOf(_user)`. // When `balanceOf(_user)` is changed (via minting/burning/transferring tokens), // `dividendOf(_user)` should not be changed, // but the computed value of `dividendPerShare * balanceOf(_user)` is changed. // To keep the `dividendOf(_user)` unchanged, we add a correction term: // `dividendOf(_user) = dividendPerShare * balanceOf(_user) + dividendCorrectionOf(_user)`, // where `dividendCorrectionOf(_user)` is updated whenever `balanceOf(_user)` is changed: // `dividendCorrectionOf(_user) = dividendPerShare * (old balanceOf(_user)) - (new balanceOf(_user))`. // So now `dividendOf(_user)` returns the same value before and after `balanceOf(_user)` is changed. mapping(address => int256) internal magnifiedDividendCorrections; mapping(address => uint256) internal withdrawnDividends; /// @dev Syncs dividends whenever ether is paid to this contract. receive() external payable { if (msg.value > 0) { require(dividendToken == TokenHelper.ETH, "SHOYU: UNABLE_TO_RECEIVE_ETH"); sync(); } } /// @notice Syncs the amount of ether/erc20 increased to token holders as dividends. /// @dev It reverts if the total supply of tokens is 0. /// @return increased The amount of total dividend increased /// It emits the `Sync` event if the amount of received ether/erc20 is greater than 0. /// About undistributed ether/erc20: /// In each distribution, there is a small amount of ether/erc20 not distributed, /// the magnified amount of which is /// `(msg.value * magnitude) % totalSupply()`. /// With a well-chosen `magnitude`, the amount of undistributed ether/erc20 /// (de-magnified) in a distribution can be less than 1 wei. /// We can actually keep track of the undistributed ether/erc20 in a distribution /// and try to distribute it in the next distribution, /// but keeping track of such data on-chain costs much more than /// the saved ether/erc20, so we don't do that. function sync() public payable override returns (uint256 increased) { uint256 _totalSupply = totalSupply(); require(_totalSupply > 0, "SHOYU: NO_SUPPLY"); uint256 balance = dividendToken.balanceOf(address(this)); increased = balance - totalDividend; require(increased > 0, "SHOYU: INSUFFICIENT_AMOUNT"); magnifiedDividendPerShare += (increased * MAGNITUDE) / _totalSupply; totalDividend = balance; emit Sync(increased); } /// @notice Withdraws the ether/erc20 distributed to the sender. /// @dev It emits a `DividendWithdrawn` event if the amount of withdrawn ether/erc20 is greater than 0. function withdrawDividend() public override { uint256 _withdrawableDividend = withdrawableDividendOf(msg.sender); if (_withdrawableDividend > 0) { withdrawnDividends[msg.sender] += _withdrawableDividend; emit DividendWithdrawn(msg.sender, _withdrawableDividend); totalDividend -= _withdrawableDividend; dividendToken.safeTransfer(msg.sender, _withdrawableDividend); } } /// @notice View the amount of dividend in wei that an address can withdraw. /// @param account The address of a token holder. /// @return The amount of dividend in wei that `account` can withdraw. function dividendOf(address account) public view override returns (uint256) { return withdrawableDividendOf(account); } /// @notice View the amount of dividend in wei that an address can withdraw. /// @param account The address of a token holder. /// @return The amount of dividend in wei that `account` can withdraw. function withdrawableDividendOf(address account) public view override returns (uint256) { return accumulativeDividendOf(account) - withdrawnDividends[account]; } /// @notice View the amount of dividend in wei that an address has withdrawn. /// @param account The address of a token holder. /// @return The amount of dividend in wei that `account` has withdrawn. function withdrawnDividendOf(address account) public view override returns (uint256) { return withdrawnDividends[account]; } /// @notice View the amount of dividend in wei that an address has earned in total. /// @dev accumulativeDividendOf(account) = withdrawableDividendOf(account) + withdrawnDividendOf(account) /// = (magnifiedDividendPerShare * balanceOf(account) + magnifiedDividendCorrections[account]) / magnitude /// @param account The address of a token holder. /// @return The amount of dividend in wei that `account` has earned in total. function accumulativeDividendOf(address account) public view override returns (uint256) { return ((magnifiedDividendPerShare * balanceOf(account)).toInt256() + magnifiedDividendCorrections[account]) .toUint256() / MAGNITUDE; } /// @dev Internal function that transfer tokens from one address to another. /// Update magnifiedDividendCorrections to keep dividends unchanged. /// @param from The address to transfer from. /// @param to The address to transfer to. /// @param value The amount to be transferred. function _transfer( address from, address to, uint256 value ) internal override { super._transfer(from, to, value); int256 _magCorrection = (magnifiedDividendPerShare * value).toInt256(); magnifiedDividendCorrections[from] += _magCorrection; magnifiedDividendCorrections[to] -= _magCorrection; } /// @dev Internal function that mints tokens to an account. /// Update magnifiedDividendCorrections to keep dividends unchanged. /// @param account The account that will receive the created tokens. /// @param value The amount that will be created. function _mint(address account, uint256 value) internal override { super._mint(account, value); magnifiedDividendCorrections[account] -= (magnifiedDividendPerShare * value).toInt256(); } /// @dev Internal function that burns an amount of the token of a given account. /// Update magnifiedDividendCorrections to keep dividends unchanged. /// @param account The account whose tokens will be burnt. /// @param value The amount that will be burnt. function _burn(address account, uint256 value) internal override { super._burn(account, value); magnifiedDividendCorrections[account] += (magnifiedDividendPerShare * value).toInt256(); } } // SPDX-License-Identifier: MIT pragma solidity ^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); } } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "@openzeppelin/contracts/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.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 ERC20Initializable is Initializable, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal initializer { __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(msg.sender, 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(msg.sender, 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][msg.sender]; require(currentAllowance >= amount, "SHOYU: INSUFFICIENT_ALLOWANCE"); _approve(sender, msg.sender, 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(msg.sender, spender, _allowances[msg.sender][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[msg.sender][spender]; require(currentAllowance >= subtractedValue, "SHOYU: ALLOWANCE_UNDERFLOW"); _approve(msg.sender, spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "SHOYU: INVALID_SENDER"); require(recipient != address(0), "SHOYU: INVALID_RECIPIENT"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "SHOYU: INSUFFICIENT_BALANCE"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "SHOYU: INVALID_ACCOUNT"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "SHOYU: INVALID_ACCOUNT"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "SHOYU: INSUFFICIENT_BALANCE"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "SHOYU: INVALID_OWNER"); require(spender != address(0), "SHOYU: INVALID_SPENDER"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC1155.sol"; import "./IERC1155Receiver.sol"; import "./extensions/IERC1155MetadataURI.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using Address for address; // Mapping from token ID to account balances mapping (uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping (address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /** * @dev See {_setURI}. */ constructor (string memory uri_) { _setURI(uri_); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) public view virtual override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch( address[] memory accounts, uint256[] memory ids ) public view virtual override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(_msgSender() != operator, "ERC1155: setting approval status for self"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require(to != address(0), "ERC1155: transfer to the zero address"); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); _balances[id][from] = fromBalance - amount; _balances[id][to] += amount; emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); _balances[id][from] = fromBalance - amount; _balances[id][to] += amount; } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `account`. * * Emits a {TransferSingle} event. * * Requirements: * * - `account` cannot be the zero address. * - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint(address account, uint256 id, uint256 amount, bytes memory data) internal virtual { require(account != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][account] += amount; emit TransferSingle(operator, address(0), account, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch(address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint i = 0; i < ids.length; i++) { _balances[ids[i]][to] += amounts[i]; } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `account` * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens of token type `id`. */ function _burn(address account, uint256 id, uint256 amount) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); uint256 accountBalance = _balances[id][account]; require(accountBalance >= amount, "ERC1155: burn amount exceeds balance"); _balances[id][account] = accountBalance - amount; emit TransferSingle(operator, account, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch(address account, uint256[] memory ids, uint256[] memory amounts) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), ids, amounts, ""); for (uint i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 accountBalance = _balances[id][account]; require(accountBalance >= amount, "ERC1155: burn amount exceeds balance"); _balances[id][account] = accountBalance - amount; } emit TransferBatch(operator, account, address(0), ids, amounts); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { } function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver(to).onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (bytes4 response) { if (response != IERC1155Receiver(to).onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; import "../interfaces/IERC2981.sol"; contract ERC1155RoyaltyMock is ERC1155("MOCK") { address public owner; constructor() { owner = msg.sender; } function mint( address account, uint256 id, uint256 amount, bytes memory data ) external { _mint(account, id, amount, data); } function mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) external { _mintBatch(to, ids, amounts, data); } function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == 0x2a55205a || super.supportsInterface(interfaceId); } function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view returns (address, uint256) { uint256 fee = 100; if (_tokenId < 10) fee = 10; return (owner, (_salePrice * fee) / 1000); } } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; contract ERC1155Mock is ERC1155("MOCK") { function mint( address account, uint256 id, uint256 amount, bytes memory data ) external { _mint(account, id, amount, data); } function mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) external { _mintBatch(to, ids, amounts, data); } } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "./base/BaseExchange.sol"; contract ERC1155ExchangeV0 is BaseExchange { bytes32 internal immutable _DOMAIN_SEPARATOR; uint256 internal immutable _CACHED_CHAIN_ID; address internal immutable _factory; constructor(address factory_) { __BaseNFTExchange_init(); _factory = factory_; _CACHED_CHAIN_ID = block.chainid; _DOMAIN_SEPARATOR = keccak256( abi.encode( // keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)') 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f, keccak256(bytes(Strings.toHexString(uint160(address(this))))), 0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6, // keccak256(bytes("1")) block.chainid, address(this) ) ); } function DOMAIN_SEPARATOR() public view override returns (bytes32) { bytes32 domainSeparator; if (_CACHED_CHAIN_ID == block.chainid) domainSeparator = _DOMAIN_SEPARATOR; else { domainSeparator = keccak256( abi.encode( // keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)') 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f, keccak256(bytes(Strings.toHexString(uint160(address(this))))), 0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6, // keccak256(bytes("1")) block.chainid, address(this) ) ); } return domainSeparator; } function factory() public view override returns (address) { return _factory; } function canTrade(address nft) public view override returns (bool) { return !ITokenFactory(_factory).isNFT1155(nft); } function _transfer( address nft, address from, address to, uint256 tokenId, uint256 amount ) internal override { IERC1155(nft).safeTransferFrom(from, to, tokenId, amount, ""); } } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "./base/BaseExchange.sol"; contract ERC721ExchangeV0 is BaseExchange { bytes32 internal immutable _DOMAIN_SEPARATOR; uint256 internal immutable _CACHED_CHAIN_ID; address internal immutable _factory; constructor(address factory_) { __BaseNFTExchange_init(); _factory = factory_; _CACHED_CHAIN_ID = block.chainid; _DOMAIN_SEPARATOR = keccak256( abi.encode( // keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)') 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f, keccak256(bytes(Strings.toHexString(uint160(address(this))))), 0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6, // keccak256(bytes("1")) block.chainid, address(this) ) ); } function DOMAIN_SEPARATOR() public view override returns (bytes32) { bytes32 domainSeparator; if (_CACHED_CHAIN_ID == block.chainid) domainSeparator = _DOMAIN_SEPARATOR; else { domainSeparator = keccak256( abi.encode( // keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)') 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f, keccak256(bytes(Strings.toHexString(uint160(address(this))))), 0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6, // keccak256(bytes("1")) block.chainid, address(this) ) ); } return domainSeparator; } function factory() public view override returns (address) { return _factory; } function canTrade(address nft) public view override returns (bool) { return !ITokenFactory(_factory).isNFT721(nft); } function _transfer( address nft, address from, address to, uint256 tokenId, uint256 ) internal override { IERC721(nft).safeTransferFrom(from, to, tokenId); } } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; contract ERC721Mock is ERC721("Mock", "MOCK") { function safeMint( address to, uint256 tokenId, bytes memory data ) external { _safeMint(to, tokenId, data); } function safeMintBatch0( address[] calldata to, uint256[] calldata tokenId, bytes memory data ) external { require(to.length == tokenId.length); for (uint256 i = 0; i < to.length; i++) { _safeMint(to[i], tokenId[i], data); } } function safeMintBatch1( address to, uint256[] calldata tokenId, bytes memory data ) external { for (uint256 i = 0; i < tokenId.length; i++) { _safeMint(to, tokenId[i], data); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; contract ERC20Mock is ERC20("Mock", "MOCK") { function mint(address to, uint256 amount) external { _mint(to, amount); } } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; interface IERC20Snapshot is IERC20, IERC20Metadata { function balanceOfAt(address account, uint256 snapshotId) external view returns (uint256); function totalSupplyAt(uint256 snapshotId) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "../interfaces/IStrategy.sol"; contract FixedPriceSale is IStrategy { function canClaim( address proxy, uint256 deadline, bytes memory params, address, uint256 bidPrice, address, uint256, uint256 ) external view override returns (bool) { uint256 price = abi.decode(params, (uint256)); require(price > 0, "SHOYU: INVALID_PRICE"); return (proxy != address(0) || block.timestamp <= deadline) && bidPrice == price; } function canBid( address, uint256, bytes memory, address, uint256, address, uint256, uint256 ) external pure override returns (bool) { return false; } } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "../interfaces/IStrategy.sol"; contract EnglishAuction is IStrategy { function canClaim( address proxy, uint256 deadline, bytes memory params, address bidder, uint256 bidPrice, address bestBidder, uint256 bestBidPrice, uint256 ) external view override returns (bool) { if (proxy == address(0)) { return bidder == bestBidder && bidPrice == bestBidPrice && deadline < block.timestamp; } else { uint256 startPrice = abi.decode(params, (uint256)); require(startPrice > 0, "SHOYU: INVALID_START_PRICE"); return bidPrice >= startPrice && deadline < block.timestamp; } } function canBid( address proxy, uint256 deadline, bytes memory params, address, uint256 bidPrice, address, uint256 bestBidPrice, uint256 ) external view override returns (bool) { if (proxy == address(0)) { uint256 startPrice = abi.decode(params, (uint256)); require(startPrice > 0, "SHOYU: INVALID_START_PRICE"); return block.timestamp <= deadline && bidPrice >= startPrice && bidPrice > bestBidPrice; } else { return false; } } } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "../interfaces/IStrategy.sol"; contract DutchAuction is IStrategy { function canClaim( address proxy, uint256 deadline, bytes memory params, address, uint256 bidPrice, address, uint256, uint256 ) external view override returns (bool) { (uint256 startPrice, uint256 endPrice, uint256 startedAt) = abi.decode(params, (uint256, uint256, uint256)); require(startPrice > endPrice, "SHOYU: INVALID_PRICE_RANGE"); require(startedAt < deadline, "SHOYU: INVALID_STARTED_AT"); uint256 tickPerBlock = (startPrice - endPrice) / (deadline - startedAt); uint256 currentPrice = block.timestamp >= deadline ? endPrice : startPrice - ((block.timestamp - startedAt) * tickPerBlock); return (proxy != address(0) || block.timestamp <= deadline) && bidPrice >= currentPrice; } function canBid( address, uint256, bytes memory, address, uint256, address, uint256, uint256 ) external pure override returns (bool) { return false; } }
This function should be called by a multi-sig `owner`, not an EOA
function setStrategyWhitelisted(address strategy, bool whitelisted) external override onlyOwner { require(strategy != address(0), "SHOYU: INVALID_ADDRESS"); isStrategyWhitelisted[strategy] = whitelisted; emit SetStrategyWhitelisted(strategy, whitelisted); }
96,698
[ 1, 2503, 445, 1410, 506, 2566, 635, 279, 3309, 17, 7340, 1375, 8443, 9191, 486, 392, 512, 28202, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 444, 4525, 18927, 329, 12, 2867, 6252, 16, 1426, 26944, 13, 3903, 3849, 1338, 5541, 288, 203, 3639, 2583, 12, 14914, 480, 1758, 12, 20, 3631, 315, 2664, 51, 61, 57, 30, 10071, 67, 15140, 8863, 203, 203, 3639, 353, 4525, 18927, 329, 63, 14914, 65, 273, 26944, 31, 203, 203, 3639, 3626, 1000, 4525, 18927, 329, 12, 14914, 16, 26944, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x7C923AB2e3680F22811eC696a321b80F37655C0c/sources/ShibariumFrens.sol
2% from total supply maxTransactionAmountTxn
maxTransactionAmount = 20_000_000 * 1e18;
4,250,297
[ 1, 22, 9, 628, 2078, 14467, 943, 3342, 6275, 13789, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 943, 3342, 6275, 273, 4200, 67, 3784, 67, 3784, 380, 404, 73, 2643, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x6c9829e5aF58E993daC721e3c2de6A1d32e3b37C/sources/contracts/ERC721/ERC721KODACreator.sol
@dev Internal logic for updating edition level funds handler overriding default
function _updateEditionFundsHandler( uint256 _editionId, address _fundsHandler ) internal { if (_fundsHandler == address(0)) revert ZeroAddress(); if (!_editionExists(_editionId)) revert EditionDoesNotExist(); if (_editionFundsHandler[_editionId] != address(0)) revert AlreadySet(); _editionFundsHandler[_editionId] = _fundsHandler; emit EditionFundsHandlerUpdated(_editionId, _fundsHandler); }
9,815,339
[ 1, 3061, 4058, 364, 9702, 28432, 1801, 284, 19156, 1838, 19488, 805, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 2725, 41, 1460, 42, 19156, 1503, 12, 203, 3639, 2254, 5034, 389, 329, 608, 548, 16, 203, 3639, 1758, 389, 74, 19156, 1503, 203, 565, 262, 2713, 288, 203, 3639, 309, 261, 67, 74, 19156, 1503, 422, 1758, 12, 20, 3719, 15226, 12744, 1887, 5621, 203, 3639, 309, 16051, 67, 329, 608, 4002, 24899, 329, 608, 548, 3719, 15226, 512, 1460, 15264, 5621, 203, 3639, 309, 261, 67, 329, 608, 42, 19156, 1503, 63, 67, 329, 608, 548, 65, 480, 1758, 12, 20, 3719, 15226, 17009, 694, 5621, 203, 3639, 389, 329, 608, 42, 19156, 1503, 63, 67, 329, 608, 548, 65, 273, 389, 74, 19156, 1503, 31, 203, 3639, 3626, 512, 1460, 42, 19156, 1503, 7381, 24899, 329, 608, 548, 16, 389, 74, 19156, 1503, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT /* * Semaphore - Zero-knowledge signaling on Ethereum * Copyright (C) 2020 Barry WhiteHat <[email protected]>, Kobi * Gurkan <[email protected]> and Koh Wei Jie ([email protected]) * * This file is part of Semaphore. * * Semaphore is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Semaphore is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Semaphore. If not, see <http://www.gnu.org/licenses/>. */ pragma solidity ^0.6.12; import { SnarkConstants } from "./SnarkConstants.sol"; import { Hasher } from "./Hasher.sol"; import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol"; import { MerkleZeros } from "./MerkleBinaryMaci.sol"; contract IncrementalMerkleTree is Ownable, Hasher, MerkleZeros { // The maximum tree depth uint8 internal constant MAX_DEPTH = 32; // The tree depth uint8 internal treeLevels; // The number of inserted leaves uint256 internal nextLeafIndex = 0; // The Merkle root uint256 public root; // Allows you to compute the path to the element (but it's not the path to // the elements). Caching these values is essential to efficient appends. uint256[MAX_DEPTH] internal filledSubtrees; // Whether the contract has already seen a particular Merkle tree root mapping (uint256 => bool) public rootHistory; event LeafInsertion(uint256 indexed leaf, uint256 indexed leafIndex); string constant ERROR_LEAF_TOO_LARGE = "E01"; string constant ERROR_TREE_FULL = "E02"; string constant ERROR_INVALID_LEVELS = "E03"; string constant ERROR_INVALID_ZERO = "E04"; constructor(uint8 _treeLevels, uint256 _zeroValue, bool _isPreCalc) public { // Limit the Merkle tree to MAX_DEPTH levels require( _treeLevels > 0 && _treeLevels <= MAX_DEPTH, ERROR_INVALID_LEVELS ); if (_isPreCalc) { // Use pre-calculated zero values (see MerkleZeros.sol.template) populateZeros(); require(_zeroValue == zeros[0], ERROR_INVALID_ZERO); treeLevels = _treeLevels; root = zeros[_treeLevels]; } else { /* To initialise the Merkle tree, we need to calculate the Merkle root assuming that each leaf is the zero value. H(H(a,b), H(c,d)) / \ H(a,b) H(c,d) / \ / \ a b c d `zeros` and `filledSubtrees` will come in handy later when we do inserts or updates. e.g when we insert a value in index 1, we will need to look up values from those arrays to recalculate the Merkle root. */ treeLevels = _treeLevels; zeros[0] = _zeroValue; uint256 currentZero = _zeroValue; for (uint8 i = 1; i < _treeLevels; i++) { uint256 hashed = hashLeftRight(currentZero, currentZero); zeros[i] = hashed; currentZero = hashed; } root = hashLeftRight(currentZero, currentZero); } } /* * Inserts a leaf into the Merkle tree and updates the root and filled * subtrees. * @param _leaf The value to insert. It must be less than the snark scalar * field or this function will throw. * @return The leaf index. */ function insertLeaf(uint256 _leaf) public onlyOwner returns (uint256) { require(_leaf < SNARK_SCALAR_FIELD, ERROR_LEAF_TOO_LARGE); uint256 currentIndex = nextLeafIndex; uint256 depth = uint256(treeLevels); require(currentIndex < uint256(2) ** depth, ERROR_TREE_FULL); uint256 currentLevelHash = _leaf; uint256 left; uint256 right; for (uint8 i = 0; i < treeLevels; i++) { // if current_index is 5, for instance, over the iterations it will // look like this: 5, 2, 1, 0, 0, 0 ... if (currentIndex % 2 == 0) { // For later values of `i`, use the previous hash as `left`, and // the (hashed) zero value for `right` left = currentLevelHash; right = zeros[i]; filledSubtrees[i] = currentLevelHash; } else { left = filledSubtrees[i]; right = currentLevelHash; } currentLevelHash = hashLeftRight(left, right); // equivalent to currentIndex /= 2; currentIndex >>= 1; } root = currentLevelHash; rootHistory[root] = true; uint256 n = nextLeafIndex; nextLeafIndex += 1; emit LeafInsertion(_leaf, n); return currentIndex; } }
Limit the Merkle tree to MAX_DEPTH levels Use pre-calculated zero values (see MerkleZeros.sol.template)/
constructor(uint8 _treeLevels, uint256 _zeroValue, bool _isPreCalc) public { require( _treeLevels > 0 && _treeLevels <= MAX_DEPTH, ERROR_INVALID_LEVELS ); if (_isPreCalc) { populateZeros(); require(_zeroValue == zeros[0], ERROR_INVALID_ZERO); treeLevels = _treeLevels; root = zeros[_treeLevels]; To initialise the Merkle tree, we need to calculate the Merkle root assuming that each leaf is the zero value. H(H(a,b), H(c,d)) / \ H(a,b) H(c,d) / \ / \ a b c d `zeros` and `filledSubtrees` will come in handy later when we do inserts or updates. e.g when we insert a value in index 1, we will need to look up values from those arrays to recalculate the Merkle root. treeLevels = _treeLevels; zeros[0] = _zeroValue; uint256 currentZero = _zeroValue; for (uint8 i = 1; i < _treeLevels; i++) { uint256 hashed = hashLeftRight(currentZero, currentZero); zeros[i] = hashed; currentZero = hashed; } root = hashLeftRight(currentZero, currentZero); } }
5,396,397
[ 1, 3039, 326, 31827, 2151, 358, 4552, 67, 27479, 7575, 2672, 675, 17, 22113, 3634, 924, 261, 5946, 31827, 20801, 18, 18281, 18, 3202, 13176, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 12, 11890, 28, 389, 3413, 12240, 16, 2254, 5034, 389, 7124, 620, 16, 1426, 389, 291, 1386, 25779, 13, 1071, 288, 203, 3639, 2583, 12, 203, 5411, 389, 3413, 12240, 405, 374, 597, 389, 3413, 12240, 1648, 4552, 67, 27479, 16, 203, 5411, 5475, 67, 9347, 67, 10398, 55, 203, 3639, 11272, 203, 540, 203, 3639, 309, 261, 67, 291, 1386, 25779, 13, 288, 203, 5411, 6490, 20801, 5621, 203, 5411, 2583, 24899, 7124, 620, 422, 4922, 63, 20, 6487, 5475, 67, 9347, 67, 24968, 1769, 203, 5411, 2151, 12240, 273, 389, 3413, 12240, 31, 203, 203, 5411, 1365, 273, 4922, 63, 67, 3413, 12240, 15533, 203, 9079, 2974, 21301, 326, 31827, 2151, 16, 732, 1608, 358, 4604, 326, 31827, 1365, 203, 9079, 15144, 716, 1517, 7839, 353, 326, 3634, 460, 18, 203, 203, 7734, 670, 12, 44, 12, 69, 16, 70, 3631, 670, 12, 71, 16, 72, 3719, 203, 1171, 342, 2398, 521, 203, 7734, 670, 12, 69, 16, 70, 13, 3639, 670, 12, 71, 16, 72, 13, 203, 1171, 342, 282, 521, 3639, 342, 565, 521, 203, 7734, 279, 377, 324, 1377, 276, 1377, 302, 203, 203, 9079, 1375, 22008, 68, 471, 1375, 13968, 1676, 17204, 68, 903, 12404, 316, 948, 93, 5137, 1347, 732, 741, 203, 9079, 15607, 578, 4533, 18, 425, 18, 75, 1347, 732, 2243, 279, 460, 316, 770, 404, 16, 732, 903, 203, 9079, 1608, 358, 2324, 731, 924, 628, 5348, 5352, 358, 26657, 326, 31827, 203, 9079, 1365, 18, 203, 5411, 2151, 12240, 273, 389, 2 ]
pragma solidity 0.5.17; pragma experimental ABIEncoderV2; // External Libraries import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20Detailed.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/utils/Address.sol"; // Common import "../../../util/AddressLib.sol"; //Contracts import "../BaseEscrowDapp.sol"; // Interfaces import "./IPoolTogetherDapp.sol"; import "../../../providers/pooltogether/PrizePoolInterface.sol"; /*****************************************************************************************************/ /** WARNING **/ /** DAPP CONTRACT IS AN EXTENSION OF THE ESCROW CONTRACT **/ /** --------------------------------------------------------------------------------------------- **/ /** Because there are multiple dApp contracts, and they all extend the Escrow contract that is **/ /** itself upgradeable, they cannot have their own storage variables as they would cause the the **/ /** storage slots to be overwritten on the Escrow proxy contract! **/ /** **/ /** Visit https://docs.openzeppelin.com/upgrades/2.6/proxies#upgrading-via-the-proxy-pattern for **/ /** more information. **/ /*****************************************************************************************************/ /** @notice This contract is used to define the Pool Together dApp actions available. All dapp actions are invoked via delegatecalls from Escrow contract, so this contract's state is really Escrow. @author [email protected] */ contract PoolTogetherDapp is IPoolTogetherDapp, BaseEscrowDapp { using AddressLib for address; using Address for address; using SafeERC20 for IERC20; /** State Variables */ /** External Functions */ /** @notice This function deposits the users funds into a Pool Together Prize Pool for a ticket. @param tokenAddress address of the token. @param amount of tokens to deposit. */ function depositTicket(address tokenAddress, uint256 amount) public onlyBorrower { require( _balanceOf(tokenAddress) >= amount, "POOL_INSUFFICIENT_UNDERLYING" ); PrizePoolInterface prizePool = _getPrizePool(tokenAddress); address ticketAddress = _getTicketAddress(tokenAddress); uint256 balanceBefore = _balanceOf(ticketAddress); IERC20(tokenAddress).safeApprove(address(prizePool), amount); prizePool.depositTo( address(this), amount, ticketAddress, address(this) ); uint256 balanceAfter = _balanceOf(ticketAddress); require(balanceAfter > balanceBefore, "DEPOSIT_ERROR"); _tokenUpdated(address(ticketAddress)); _tokenUpdated(tokenAddress); emit PoolTogetherDeposited( tokenAddress, ticketAddress, amount, _balanceOf(tokenAddress), balanceAfter ); } /** @notice This function withdraws the users funds from a Pool Together Prize Pool. @param tokenAddress address of the token. @param amount The amount of tokens to withdraw. */ function withdraw(address tokenAddress, uint256 amount) public onlyBorrower { PrizePoolInterface prizePool = _getPrizePool(tokenAddress); address ticketAddress = _getTicketAddress(tokenAddress); uint256 balanceBefore = _balanceOf(ticketAddress); ( uint256 maxExitFee, /* uint256 burnedCredit */ ) = prizePool.calculateEarlyExitFee( address(this), ticketAddress, amount ); prizePool.withdrawInstantlyFrom( address(this), amount, ticketAddress, maxExitFee ); uint256 balanceAfter = _balanceOf(ticketAddress); require(balanceAfter < balanceBefore, "WITHDRAW_ERROR"); _tokenUpdated(address(ticketAddress)); _tokenUpdated(tokenAddress); emit PoolTogetherWithdrawal( tokenAddress, ticketAddress, amount, _balanceOf(tokenAddress), balanceAfter ); } /** @notice This function withdraws the users funds from a Pool Together Prize Pool. @param tokenAddress address of the token. */ function withdrawAll(address tokenAddress) public onlyBorrower { PrizePoolInterface prizePool = _getPrizePool(tokenAddress); address ticketAddress = _getTicketAddress(tokenAddress); uint256 balanceBefore = _balanceOf(ticketAddress); (uint256 maxExitFee, ) = prizePool.calculateEarlyExitFee( address(this), ticketAddress, balanceBefore ); prizePool.withdrawInstantlyFrom( address(this), balanceBefore, ticketAddress, maxExitFee ); uint256 balanceAfter = _balanceOf(ticketAddress); require(balanceAfter < balanceBefore, "WITHDRAW_ERROR"); _tokenUpdated(address(ticketAddress)); _tokenUpdated(tokenAddress); emit PoolTogetherWithdrawal( tokenAddress, ticketAddress, balanceBefore, _balanceOf(tokenAddress), balanceAfter ); } /** Internal Functions */ /** @notice Grabs the Pool Together Prize Pool address for an token from the asset settings. @notice The pool underlying address must match the supplied token address. @param tokenAddress The token address to get the cToken for. @return PrizePool instance. */ function _getPrizePool(address tokenAddress) internal view returns (PrizePoolInterface) { return PrizePoolInterface( settings.assetSettings().getPrizePoolAddress(tokenAddress) ); } /** @notice Grabs the controlled ticket token address for the prize pool @notice The pool underlying address must match the supplied token address. @param tokenAddress The token address to get the cToken for. @return The address of the ticket token contract. */ function _getTicketAddress(address tokenAddress) internal view returns (address) { return _getPrizePool(tokenAddress).tokens()[1]; } }
* State Variables */* External Functions */*/
{ require( _balanceOf(tokenAddress) >= amount, "POOL_INSUFFICIENT_UNDERLYING" ); PrizePoolInterface prizePool = _getPrizePool(tokenAddress); address ticketAddress = _getTicketAddress(tokenAddress); uint256 balanceBefore = _balanceOf(ticketAddress); IERC20(tokenAddress).safeApprove(address(prizePool), amount); prizePool.depositTo( address(this), amount, ticketAddress, address(this) ); uint256 balanceAfter = _balanceOf(ticketAddress); require(balanceAfter > balanceBefore, "DEPOSIT_ERROR"); _tokenUpdated(address(ticketAddress)); _tokenUpdated(tokenAddress); emit PoolTogetherDeposited( tokenAddress, ticketAddress, amount, _balanceOf(tokenAddress), balanceAfter ); }
12,831,499
[ 1, 1119, 23536, 342, 11352, 15486, 368, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 288, 203, 3639, 2583, 12, 203, 5411, 389, 12296, 951, 12, 2316, 1887, 13, 1545, 3844, 16, 203, 5411, 315, 20339, 67, 706, 6639, 42, 1653, 7266, 2222, 67, 31625, 7076, 1360, 6, 203, 3639, 11272, 203, 203, 3639, 2301, 554, 2864, 1358, 846, 554, 2864, 273, 389, 588, 2050, 554, 2864, 12, 2316, 1887, 1769, 203, 203, 3639, 1758, 9322, 1887, 273, 389, 588, 13614, 1887, 12, 2316, 1887, 1769, 203, 3639, 2254, 5034, 11013, 4649, 273, 389, 12296, 951, 12, 16282, 1887, 1769, 203, 3639, 467, 654, 39, 3462, 12, 2316, 1887, 2934, 4626, 12053, 537, 12, 2867, 12, 683, 554, 2864, 3631, 3844, 1769, 203, 203, 3639, 846, 554, 2864, 18, 323, 1724, 774, 12, 203, 5411, 1758, 12, 2211, 3631, 203, 5411, 3844, 16, 203, 5411, 9322, 1887, 16, 203, 5411, 1758, 12, 2211, 13, 203, 3639, 11272, 203, 203, 3639, 2254, 5034, 11013, 4436, 273, 389, 12296, 951, 12, 16282, 1887, 1769, 203, 3639, 2583, 12, 12296, 4436, 405, 11013, 4649, 16, 315, 1639, 28284, 67, 3589, 8863, 203, 203, 3639, 389, 2316, 7381, 12, 2867, 12, 16282, 1887, 10019, 203, 3639, 389, 2316, 7381, 12, 2316, 1887, 1769, 203, 203, 3639, 3626, 8828, 56, 717, 2437, 758, 1724, 329, 12, 203, 5411, 1147, 1887, 16, 203, 5411, 9322, 1887, 16, 203, 5411, 3844, 16, 203, 5411, 389, 12296, 951, 12, 2316, 1887, 3631, 203, 5411, 11013, 4436, 203, 3639, 11272, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: GPL-3.0 pragma solidity 0.7.6; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol"; import "@pooltogether/fixed-point/contracts/FixedPoint.sol"; import "@pooltogether/yield-source-interface/contracts/IYieldSource.sol"; import "./access/AssetManager.sol"; /// @title Swappable yield source contract to allow a PoolTogether prize pool to swap between different yield sources. /// @dev This contract adheres to the PoolTogether yield source interface. /// @dev This contract inherits AssetManager which extends OwnableUpgradable. /// @notice Swappable yield source for a PoolTogether prize pool that generates yield by depositing into the specified yield source. contract SwappableYieldSource is ERC20Upgradeable, AssetManager, ReentrancyGuardUpgradeable { using SafeMathUpgradeable for uint256; using SafeERC20Upgradeable for IERC20Upgradeable; ERC20Upgradeable public yieldSource = ERC20Upgradeable(0x0cEC1A9154Ff802e7934Fc916Ed7Ca50bDE6844e); address immutable depositToken; constructor(address _depositToken){ depositToken = _depositToken; __Ownable_init(); // owned by msg.sender // Not max so we simulate using approveMaxAmount IERC20Upgradeable(_depositToken).safeApprove(address(yieldSource), 600); } function approveMaxAmount() external onlyOwner returns (bool) { IERC20Upgradeable _yieldSource = yieldSource; IERC20Upgradeable _depositToken = IERC20Upgradeable(depositToken); // Set to max via modifying math = No gas refund uint256 allowance = _depositToken.allowance(address(this), address(_yieldSource)); _depositToken.safeIncreaseAllowance(address(_yieldSource), type(uint256).max.sub(allowance)); return true; } function approveMaxAmountWithReset() external onlyOwner returns (bool) { IERC20Upgradeable _yieldSource = yieldSource; IERC20Upgradeable _depositToken = IERC20Upgradeable(depositToken); // Set to 0, then set to max should get gas refund? _depositToken.safeApprove(address(_yieldSource), 0); _depositToken.safeApprove(address(_yieldSource), type(uint256).max); return true; } }
@title Swappable yield source contract to allow a PoolTogether prize pool to swap between different yield sources. @dev This contract adheres to the PoolTogether yield source interface. @dev This contract inherits AssetManager which extends OwnableUpgradable. @notice Swappable yield source for a PoolTogether prize pool that generates yield by depositing into the specified yield source.
contract SwappableYieldSource is ERC20Upgradeable, AssetManager, ReentrancyGuardUpgradeable { using SafeMathUpgradeable for uint256; using SafeERC20Upgradeable for IERC20Upgradeable; ERC20Upgradeable public yieldSource = ERC20Upgradeable(0x0cEC1A9154Ff802e7934Fc916Ed7Ca50bDE6844e); address immutable depositToken; constructor(address _depositToken){ depositToken = _depositToken; IERC20Upgradeable(_depositToken).safeApprove(address(yieldSource), 600); } function approveMaxAmount() external onlyOwner returns (bool) { IERC20Upgradeable _yieldSource = yieldSource; IERC20Upgradeable _depositToken = IERC20Upgradeable(depositToken); uint256 allowance = _depositToken.allowance(address(this), address(_yieldSource)); _depositToken.safeIncreaseAllowance(address(_yieldSource), type(uint256).max.sub(allowance)); return true; } function approveMaxAmountWithReset() external onlyOwner returns (bool) { IERC20Upgradeable _yieldSource = yieldSource; IERC20Upgradeable _depositToken = IERC20Upgradeable(depositToken); _depositToken.safeApprove(address(_yieldSource), 0); _depositToken.safeApprove(address(_yieldSource), type(uint256).max); return true; } }
12,964,515
[ 1, 6050, 2910, 429, 2824, 1084, 6835, 358, 1699, 279, 8828, 56, 717, 2437, 846, 554, 2845, 358, 7720, 3086, 3775, 2824, 5550, 18, 225, 1220, 6835, 1261, 27629, 358, 326, 8828, 56, 717, 2437, 2824, 1084, 1560, 18, 225, 1220, 6835, 24664, 10494, 1318, 1492, 3231, 14223, 6914, 1211, 9974, 429, 18, 225, 5434, 2910, 429, 2824, 1084, 364, 279, 8828, 56, 717, 2437, 846, 554, 2845, 716, 6026, 2824, 635, 443, 1724, 310, 1368, 326, 1269, 2824, 1084, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 5434, 2910, 429, 16348, 1830, 353, 4232, 39, 3462, 10784, 429, 16, 10494, 1318, 16, 868, 8230, 12514, 16709, 10784, 429, 288, 203, 225, 1450, 14060, 10477, 10784, 429, 364, 2254, 5034, 31, 203, 225, 1450, 14060, 654, 39, 3462, 10784, 429, 364, 467, 654, 39, 3462, 10784, 429, 31, 203, 203, 225, 4232, 39, 3462, 10784, 429, 1071, 2824, 1830, 273, 4232, 39, 3462, 10784, 429, 12, 20, 92, 20, 71, 7228, 21, 37, 29, 29003, 42, 74, 31644, 73, 7235, 5026, 42, 71, 29, 2313, 2671, 27, 23508, 3361, 70, 1639, 26, 5193, 24, 73, 1769, 203, 203, 225, 1758, 11732, 443, 1724, 1345, 31, 203, 203, 203, 225, 3885, 12, 2867, 389, 323, 1724, 1345, 15329, 203, 203, 565, 443, 1724, 1345, 273, 389, 323, 1724, 1345, 31, 203, 203, 203, 565, 467, 654, 39, 3462, 10784, 429, 24899, 323, 1724, 1345, 2934, 4626, 12053, 537, 12, 2867, 12, 23604, 1830, 3631, 14707, 1769, 7010, 225, 289, 203, 203, 225, 445, 6617, 537, 2747, 6275, 1435, 3903, 1338, 5541, 1135, 261, 6430, 13, 288, 203, 565, 467, 654, 39, 3462, 10784, 429, 389, 23604, 1830, 273, 2824, 1830, 31, 203, 565, 467, 654, 39, 3462, 10784, 429, 389, 323, 1724, 1345, 273, 467, 654, 39, 3462, 10784, 429, 12, 323, 1724, 1345, 1769, 203, 203, 565, 2254, 5034, 1699, 1359, 273, 389, 323, 1724, 1345, 18, 5965, 1359, 12, 2867, 12, 2211, 3631, 1758, 24899, 23604, 1830, 10019, 203, 565, 389, 323, 1724, 1345, 18, 4626, 382, 11908, 7009, 1359, 2 ]
pragma solidity ^0.4.24; /** * @title ERC721 Non-Fungible Token Standard Basic Interface * @dev Based on openzepplin open source ERC721 examples. * See (https://github.com/OpenZeppelin/openzeppelin-solidity) */ contract ERC721 { /** * @dev 0x01ffc9a7 === * bytes4(keccak256('supportsInterface(bytes4)')) */ bytes4 public constant InterfaceId_ERC165 = 0x01ffc9a7; /** * @dev 0x80ac58cd === * bytes4(keccak256('balanceOf(address)')) ^ * bytes4(keccak256('ownerOf(uint256)')) ^ * bytes4(keccak256('approve(address,uint256)')) ^ * bytes4(keccak256('getApproved(uint256)')) ^ * bytes4(keccak256('setApprovalForAll(address,bool)')) ^ * bytes4(keccak256('isApprovedForAll(address,address)')) ^ * bytes4(keccak256('transferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) */ bytes4 internal constant InterfaceId_ERC721 = 0x80ac58cd; /** * @dev 0x780e9d63 === * bytes4(keccak256('totalSupply()')) ^ * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^ * bytes4(keccak256('tokenByIndex(uint256)')) */ bytes4 internal constant InterfaceId_ERC721Enumerable = 0x780e9d63; /** * @dev 0x5b5e139f === * bytes4(keccak256('name()')) ^ * bytes4(keccak256('symbol()')) ^ * bytes4(keccak256('tokenURI(uint256)')) */ bytes4 internal constant InterfaceId_ERC721Metadata = 0x5b5e139f; /** @dev A mapping of interface id to whether or not it is supported */ mapping(bytes4 => bool) internal supportedInterfaces; /** @dev Token events */ 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); /** @dev Registers ERC-165, ERC-721, ERC-721 Enumerable and ERC-721 Metadata as supported interfaces */ constructor() public { registerInterface(InterfaceId_ERC165); registerInterface(InterfaceId_ERC721); registerInterface(InterfaceId_ERC721Enumerable); registerInterface(InterfaceId_ERC721Metadata); } /** @dev Internal function for registering an interface */ function registerInterface(bytes4 _interfaceId) internal { require(_interfaceId != 0xffffffff); supportedInterfaces[_interfaceId] = true; } /** @dev ERC-165 interface implementation */ function supportsInterface(bytes4 _interfaceId) external view returns(bool) { return supportedInterfaces[_interfaceId]; } /** @dev ERC-721 interface */ function balanceOf(address _owner) public view returns(uint256 _balance); function ownerOf(uint256 _tokenId) public view returns(address _owner); function approve(address _to, uint256 _tokenId) public; function getApproved(uint256 _tokenId) public view returns(address _operator); function setApprovalForAll(address _operator, bool _approved) public; function isApprovedForAll(address _owner, address _operator) public view returns(bool); function transferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes _data) public; /** @dev ERC-721 Enumerable interface */ function totalSupply() public view returns(uint256 _total); function tokenByIndex(uint256 _index) public view returns(uint256 _tokenId); function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns(uint256 _tokenId); /** @dev ERC-721 Metadata interface */ function name() public view returns(string _name); function symbol() public view returns(string _symbol); function tokenURI(uint256 _tokenId) public view returns(string); } /** * @title PixelCons Core * @notice The purpose of this contract is to provide a shared ecosystem of minimal pixel art tokens for everyone to use. All users are treated * equally with the exception of an admin user who only controls the ERC721 metadata function which points to the app website. No fees are * required to interact with this contract beyond base gas fees. Here are a few notes on the basic workings of the contract: * PixelCons [The core ERC721 token of this contract] * -Each PixelCon is unique with an ID that encodes all its pixel data * -PixelCons can be identified by both TokenIDs and TokenIndexes (index requires fewer bits to store) * -A PixelCon can never be destroyed * -Total number of PixelCons is limited to 18,446,744,073,709,551,616 (2^64) * -A single account can only hold 4,294,967,296 PixelCons (2^32) * Collections [Grouping mechanism for associating PixelCons together] * -Collections are identified by an index (zero is invalid) * -Collections can only be created by a user who both created and currently owns all its PixelCons * -Total number of collections is limited to 18,446,744,073,709,551,616 (2^64) * For more information about PixelCons, please visit (https://pixelcons.io) * @dev This contract follows the ERC721 token standard with additional functions for creating, grouping, etc. * See (https://github.com/OpenZeppelin/openzeppelin-solidity) * @author PixelCons */ contract PixelCons is ERC721 { using AddressUtils for address; /** @dev Equal to 'bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))' */ bytes4 private constant ERC721_RECEIVED = 0x150b7a02; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// Structs /////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** @dev The main PixelCon struct */ struct PixelCon { uint256 tokenId; //// ^256bits //// address creator; uint64 collectionIndex; uint32 dateCreated; } /** @dev A struct linking a token owner with its token index */ struct TokenLookup { address owner; uint64 tokenIndex; uint32 ownedIndex; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// Storage /////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** @dev The address thats allowed to withdraw volunteered funds sent to this contract */ address internal admin; /** @dev The URI template for retrieving token metadata */ string internal tokenURITemplate; ////////////////// PixelCon Tokens ////////////////// /** @dev Mapping from token ID to owner/index */ mapping(uint256 => TokenLookup) internal tokenLookup; /** @dev Mapping from owner to token indexes */ mapping(address => uint64[]) internal ownedTokens; /** @dev Mapping from creator to token indexes */ mapping(address => uint64[]) internal createdTokens; /** @dev Mapping from token ID to approved address */ mapping(uint256 => address) internal tokenApprovals; /** @dev Mapping from owner to operator approvals */ mapping(address => mapping(address => bool)) internal operatorApprovals; /** @dev An array containing all PixelCons in existence */ PixelCon[] internal pixelcons; /** @dev An array that mirrors 'pixelcons' in terms of indexing, but stores only name data */ bytes8[] internal pixelconNames; ////////////////// Collections ////////////////// /** @dev Mapping from collection index to token indexes */ mapping(uint64 => uint64[]) internal collectionTokens; /** @dev An array that mirrors 'collectionTokens' in terms of indexing, but stores only name data */ bytes8[] internal collectionNames; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// Events //////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** @dev PixelCon token events */ event Create(uint256 indexed _tokenId, address indexed _creator, uint64 _tokenIndex, address _to); event Rename(uint256 indexed _tokenId, bytes8 _newName); /** @dev PixelCon collection events */ event CreateCollection(address indexed _creator, uint64 indexed _collectionIndex); event RenameCollection(uint64 indexed _collectionIndex, bytes8 _newName); event ClearCollection(uint64 indexed _collectionIndex); ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// Modifiers /////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** @dev Small validators for quick validation of function parameters */ modifier validIndex(uint64 _index) { require(_index != uint64(0), "Invalid index"); _; } modifier validId(uint256 _id) { require(_id != uint256(0), "Invalid ID"); _; } modifier validAddress(address _address) { require(_address != address(0), "Invalid address"); _; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////// PixelCons Core /////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * @notice Contract constructor */ constructor() public { //admin defaults to the contract creator admin = msg.sender; //fill zero index pixelcon collection collectionNames.length++; } /** * @notice Get the current admin * @return The current admin */ function getAdmin() public view returns(address) { return admin; } /** * @notice Withdraw all volunteered funds to `(_to)` * @param _to Address to withdraw the funds to */ function adminWithdraw(address _to) public { require(msg.sender == admin, "Only the admin can call this function"); _to.transfer(address(this).balance); } /** * @notice Change the admin to `(_to)` * @param _newAdmin New admin address */ function adminChange(address _newAdmin) public { require(msg.sender == admin, "Only the admin can call this function"); admin = _newAdmin; } /** * @notice Change the token URI template * @param _newTokenURITemplate New token URI template */ function adminSetTokenURITemplate(string _newTokenURITemplate) public { require(msg.sender == admin, "Only the admin can call this function"); tokenURITemplate = _newTokenURITemplate; } ////////////////// PixelCon Tokens ////////////////// /** * @notice Create PixelCon `(_tokenId)` * @dev Throws if the token ID already exists * @param _to Address that will own the PixelCon * @param _tokenId ID of the PixelCon to be creates * @param _name PixelCon name (not required) * @return The index of the new PixelCon */ function create(address _to, uint256 _tokenId, bytes8 _name) public payable validAddress(_to) validId(_tokenId) returns(uint64) { TokenLookup storage lookupData = tokenLookup[_tokenId]; require(pixelcons.length < uint256(2 ** 64) - 1, "Max number of PixelCons has been reached"); require(lookupData.owner == address(0), "PixelCon already exists"); //get created timestamp (zero as date indicates null) uint32 dateCreated = 0; if (now < uint256(2 ** 32)) dateCreated = uint32(now); //create PixelCon token and set owner uint64 index = uint64(pixelcons.length); lookupData.tokenIndex = index; pixelcons.length++; pixelconNames.length++; PixelCon storage pixelcon = pixelcons[index]; pixelcon.tokenId = _tokenId; pixelcon.creator = msg.sender; pixelcon.dateCreated = dateCreated; pixelconNames[index] = _name; uint64[] storage createdList = createdTokens[msg.sender]; uint createdListIndex = createdList.length; createdList.length++; createdList[createdListIndex] = index; addTokenTo(_to, _tokenId); emit Create(_tokenId, msg.sender, index, _to); emit Transfer(address(0), _to, _tokenId); return index; } /** * @notice Rename PixelCon `(_tokenId)` * @dev Throws if the caller is not the owner and creator of the token * @param _tokenId ID of the PixelCon to rename * @param _name New name * @return The index of the PixelCon */ function rename(uint256 _tokenId, bytes8 _name) public validId(_tokenId) returns(uint64) { require(isCreatorAndOwner(msg.sender, _tokenId), "Sender is not the creator and owner"); //update name TokenLookup storage lookupData = tokenLookup[_tokenId]; pixelconNames[lookupData.tokenIndex] = _name; emit Rename(_tokenId, _name); return lookupData.tokenIndex; } /** * @notice Check if PixelCon `(_tokenId)` exists * @param _tokenId ID of the PixelCon to query the existence of * @return True if the PixelCon exists */ function exists(uint256 _tokenId) public view validId(_tokenId) returns(bool) { address owner = tokenLookup[_tokenId].owner; return owner != address(0); } /** * @notice Get the creator of PixelCon `(_tokenId)` * @dev Throws if PixelCon does not exist * @param _tokenId ID of the PixelCon to query the creator of * @return Creator address for PixelCon */ function creatorOf(uint256 _tokenId) public view validId(_tokenId) returns(address) { TokenLookup storage lookupData = tokenLookup[_tokenId]; require(lookupData.owner != address(0), "PixelCon does not exist"); return pixelcons[lookupData.tokenIndex].creator; } /** * @notice Get the total number of PixelCons created by `(_creator)` * @param _creator Address to query the total of * @return Total number of PixelCons created by given address */ function creatorTotal(address _creator) public view validAddress(_creator) returns(uint256) { return createdTokens[_creator].length; } /** * @notice Enumerate PixelCon created by `(_creator)` * @dev Throws if index is out of bounds * @param _creator Creator address * @param _index Counter less than `creatorTotal(_creator)` * @return PixelCon ID for the `(_index)`th PixelCon created by `(_creator)` */ function tokenOfCreatorByIndex(address _creator, uint256 _index) public view validAddress(_creator) returns(uint256) { require(_index < createdTokens[_creator].length, "Index is out of bounds"); PixelCon storage pixelcon = pixelcons[createdTokens[_creator][_index]]; return pixelcon.tokenId; } /** * @notice Get all details of PixelCon `(_tokenId)` * @dev Throws if PixelCon does not exist * @param _tokenId ID of the PixelCon to get details for * @return PixelCon details */ function getTokenData(uint256 _tokenId) public view validId(_tokenId) returns(uint256 _tknId, uint64 _tknIdx, uint64 _collectionIdx, address _owner, address _creator, bytes8 _name, uint32 _dateCreated) { TokenLookup storage lookupData = tokenLookup[_tokenId]; require(lookupData.owner != address(0), "PixelCon does not exist"); PixelCon storage pixelcon = pixelcons[lookupData.tokenIndex]; return (pixelcon.tokenId, lookupData.tokenIndex, pixelcon.collectionIndex, lookupData.owner, pixelcon.creator, pixelconNames[lookupData.tokenIndex], pixelcon.dateCreated); } /** * @notice Get all details of PixelCon #`(_tokenIndex)` * @dev Throws if PixelCon does not exist * @param _tokenIndex Index of the PixelCon to get details for * @return PixelCon details */ function getTokenDataByIndex(uint64 _tokenIndex) public view returns(uint256 _tknId, uint64 _tknIdx, uint64 _collectionIdx, address _owner, address _creator, bytes8 _name, uint32 _dateCreated) { require(_tokenIndex < totalSupply(), "PixelCon index is out of bounds"); PixelCon storage pixelcon = pixelcons[_tokenIndex]; TokenLookup storage lookupData = tokenLookup[pixelcon.tokenId]; return (pixelcon.tokenId, lookupData.tokenIndex, pixelcon.collectionIndex, lookupData.owner, pixelcon.creator, pixelconNames[lookupData.tokenIndex], pixelcon.dateCreated); } /** * @notice Get the index of PixelCon `(_tokenId)` * @dev Throws if PixelCon does not exist * @param _tokenId ID of the PixelCon to query the index of * @return Index of the given PixelCon ID */ function getTokenIndex(uint256 _tokenId) validId(_tokenId) public view returns(uint64) { TokenLookup storage lookupData = tokenLookup[_tokenId]; require(lookupData.owner != address(0), "PixelCon does not exist"); return lookupData.tokenIndex; } ////////////////// Collections ////////////////// /** * @notice Create PixelCon collection * @dev Throws if the message sender is not the owner and creator of the given tokens * @param _tokenIndexes Token indexes to group together into a collection * @param _name Name of the collection * @return Index of the new collection */ function createCollection(uint64[] _tokenIndexes, bytes8 _name) public returns(uint64) { require(collectionNames.length < uint256(2 ** 64) - 1, "Max number of collections has been reached"); require(_tokenIndexes.length > 1, "Collection must contain more than one PixelCon"); //loop through given indexes to add to collection and check additional requirements uint64 collectionIndex = uint64(collectionNames.length); uint64[] storage collection = collectionTokens[collectionIndex]; collection.length = _tokenIndexes.length; for (uint i = 0; i < _tokenIndexes.length; i++) { uint64 tokenIndex = _tokenIndexes[i]; require(tokenIndex < totalSupply(), "PixelCon index is out of bounds"); PixelCon storage pixelcon = pixelcons[tokenIndex]; require(isCreatorAndOwner(msg.sender, pixelcon.tokenId), "Sender is not the creator and owner of the PixelCons"); require(pixelcon.collectionIndex == uint64(0), "PixelCon is already in a collection"); pixelcon.collectionIndex = collectionIndex; collection[i] = tokenIndex; } collectionNames.length++; collectionNames[collectionIndex] = _name; emit CreateCollection(msg.sender, collectionIndex); return collectionIndex; } /** * @notice Rename collection #`(_collectionIndex)` * @dev Throws if the message sender is not the owner and creator of all collection tokens * @param _collectionIndex Index of the collection to rename * @param _name New name * @return Index of the collection */ function renameCollection(uint64 _collectionIndex, bytes8 _name) validIndex(_collectionIndex) public returns(uint64) { require(_collectionIndex < totalCollections(), "Collection does not exist"); //loop through the collections token indexes and check additional requirements uint64[] storage collection = collectionTokens[_collectionIndex]; require(collection.length > 0, "Collection has been cleared"); for (uint i = 0; i < collection.length; i++) { PixelCon storage pixelcon = pixelcons[collection[i]]; require(isCreatorAndOwner(msg.sender, pixelcon.tokenId), "Sender is not the creator and owner of the PixelCons"); } //update collectionNames[_collectionIndex] = _name; emit RenameCollection(_collectionIndex, _name); return _collectionIndex; } /** * @notice Clear collection #`(_collectionIndex)` * @dev Throws if the message sender is not the owner and creator of all collection tokens * @param _collectionIndex Index of the collection to clear out * @return Index of the collection */ function clearCollection(uint64 _collectionIndex) validIndex(_collectionIndex) public returns(uint64) { require(_collectionIndex < totalCollections(), "Collection does not exist"); //loop through the collections token indexes and check additional requirements while clearing pixelcon collection index uint64[] storage collection = collectionTokens[_collectionIndex]; require(collection.length > 0, "Collection is already cleared"); for (uint i = 0; i < collection.length; i++) { PixelCon storage pixelcon = pixelcons[collection[i]]; require(isCreatorAndOwner(msg.sender, pixelcon.tokenId), "Sender is not the creator and owner of the PixelCons"); pixelcon.collectionIndex = 0; } //clear out collection data delete collectionNames[_collectionIndex]; delete collectionTokens[_collectionIndex]; emit ClearCollection(_collectionIndex); return _collectionIndex; } /** * @notice Check if collection #`(_collectionIndex)` exists * @param _collectionIndex Index of the collection to query the existence of * @return True if collection exists */ function collectionExists(uint64 _collectionIndex) public view validIndex(_collectionIndex) returns(bool) { return _collectionIndex < totalCollections(); } /** * @notice Check if collection #`(_collectionIndex)` has been cleared * @dev Throws if the collection index is out of bounds * @param _collectionIndex Index of the collection to query the state of * @return True if collection has been cleared */ function collectionCleared(uint64 _collectionIndex) public view validIndex(_collectionIndex) returns(bool) { require(_collectionIndex < totalCollections(), "Collection does not exist"); return collectionTokens[_collectionIndex].length == uint256(0); } /** * @notice Get the total number of collections * @return Total number of collections */ function totalCollections() public view returns(uint256) { return collectionNames.length; } /** * @notice Get the collection index of PixelCon `(_tokenId)` * @dev Throws if the PixelCon does not exist * @param _tokenId ID of the PixelCon to query the collection of * @return Collection index of given PixelCon */ function collectionOf(uint256 _tokenId) public view validId(_tokenId) returns(uint256) { TokenLookup storage lookupData = tokenLookup[_tokenId]; require(lookupData.owner != address(0), "PixelCon does not exist"); return pixelcons[tokenLookup[_tokenId].tokenIndex].collectionIndex; } /** * @notice Get the total number of PixelCons in collection #`(_collectionIndex)` * @dev Throws if the collection does not exist * @param _collectionIndex Collection index to query the total of * @return Total number of PixelCons in the collection */ function collectionTotal(uint64 _collectionIndex) public view validIndex(_collectionIndex) returns(uint256) { require(_collectionIndex < totalCollections(), "Collection does not exist"); return collectionTokens[_collectionIndex].length; } /** * @notice Get the name of collection #`(_collectionIndex)` * @dev Throws if the collection does not exist * @param _collectionIndex Collection index to query the name of * @return Collection name */ function getCollectionName(uint64 _collectionIndex) public view validIndex(_collectionIndex) returns(bytes8) { require(_collectionIndex < totalCollections(), "Collection does not exist"); return collectionNames[_collectionIndex]; } /** * @notice Enumerate PixelCon in collection #`(_collectionIndex)` * @dev Throws if the collection does not exist or index is out of bounds * @param _collectionIndex Collection index * @param _index Counter less than `collectionTotal(_collection)` * @return PixelCon ID for the `(_index)`th PixelCon in collection #`(_collectionIndex)` */ function tokenOfCollectionByIndex(uint64 _collectionIndex, uint256 _index) public view validIndex(_collectionIndex) returns(uint256) { require(_collectionIndex < totalCollections(), "Collection does not exist"); require(_index < collectionTokens[_collectionIndex].length, "Index is out of bounds"); PixelCon storage pixelcon = pixelcons[collectionTokens[_collectionIndex][_index]]; return pixelcon.tokenId; } ////////////////// Web3 Only ////////////////// /** * @notice Get the indexes of all PixelCons owned by `(_owner)` * @dev This function is for web3 calls only, as it returns a dynamic array * @param _owner Owner address * @return PixelCon indexes */ function getForOwner(address _owner) public view validAddress(_owner) returns(uint64[]) { return ownedTokens[_owner]; } /** * @notice Get the indexes of all PixelCons created by `(_creator)` * @dev This function is for web3 calls only, as it returns a dynamic array * @param _creator Creator address * @return PixelCon indexes */ function getForCreator(address _creator) public view validAddress(_creator) returns(uint64[]) { return createdTokens[_creator]; } /** * @notice Get the indexes of all PixelCons in collection #`(_collectionIndex)` * @dev This function is for web3 calls only, as it returns a dynamic array * @param _collectionIndex Collection index * @return PixelCon indexes */ function getForCollection(uint64 _collectionIndex) public view validIndex(_collectionIndex) returns(uint64[]) { return collectionTokens[_collectionIndex]; } /** * @notice Get the basic data for the given PixelCon indexes * @dev This function is for web3 calls only, as it returns a dynamic array * @param _tokenIndexes List of PixelCon indexes * @return All PixelCon basic data */ function getBasicData(uint64[] _tokenIndexes) public view returns(uint256[], bytes8[], address[], uint64[]) { uint256[] memory tokenIds = new uint256[](_tokenIndexes.length); bytes8[] memory names = new bytes8[](_tokenIndexes.length); address[] memory owners = new address[](_tokenIndexes.length); uint64[] memory collectionIdxs = new uint64[](_tokenIndexes.length); for (uint i = 0; i < _tokenIndexes.length; i++) { uint64 tokenIndex = _tokenIndexes[i]; require(tokenIndex < totalSupply(), "PixelCon index is out of bounds"); tokenIds[i] = pixelcons[tokenIndex].tokenId; names[i] = pixelconNames[tokenIndex]; owners[i] = tokenLookup[pixelcons[tokenIndex].tokenId].owner; collectionIdxs[i] = pixelcons[tokenIndex].collectionIndex; } return (tokenIds, names, owners, collectionIdxs); } /** * @notice Get the names of all PixelCons * @dev This function is for web3 calls only, as it returns a dynamic array * @return The names of all PixelCons in existence */ function getAllNames() public view returns(bytes8[]) { return pixelconNames; } /** * @notice Get the names of all PixelCons from index `(_startIndex)` to `(_endIndex)` * @dev This function is for web3 calls only, as it returns a dynamic array * @return The names of the PixelCons in the given range */ function getNamesInRange(uint64 _startIndex, uint64 _endIndex) public view returns(bytes8[]) { require(_startIndex <= totalSupply(), "Start index is out of bounds"); require(_endIndex <= totalSupply(), "End index is out of bounds"); require(_startIndex <= _endIndex, "End index is less than the start index"); uint64 length = _endIndex - _startIndex; bytes8[] memory names = new bytes8[](length); for (uint i = 0; i < length; i++) { names[i] = pixelconNames[_startIndex + i]; } return names; } /** * @notice Get details of collection #`(_collectionIndex)` * @dev This function is for web3 calls only, as it returns a dynamic array * @param _collectionIndex Index of the collection to get the data of * @return Collection name and included PixelCon indexes */ function getCollectionData(uint64 _collectionIndex) public view validIndex(_collectionIndex) returns(bytes8, uint64[]) { require(_collectionIndex < totalCollections(), "Collection does not exist"); return (collectionNames[_collectionIndex], collectionTokens[_collectionIndex]); } /** * @notice Get the names of all collections * @dev This function is for web3 calls only, as it returns a dynamic array * @return The names of all PixelCon collections in existence */ function getAllCollectionNames() public view returns(bytes8[]) { return collectionNames; } /** * @notice Get the names of all collections from index `(_startIndex)` to `(_endIndex)` * @dev This function is for web3 calls only, as it returns a dynamic array * @return The names of the collections in the given range */ function getCollectionNamesInRange(uint64 _startIndex, uint64 _endIndex) public view returns(bytes8[]) { require(_startIndex <= totalCollections(), "Start index is out of bounds"); require(_endIndex <= totalCollections(), "End index is out of bounds"); require(_startIndex <= _endIndex, "End index is less than the start index"); uint64 length = _endIndex - _startIndex; bytes8[] memory names = new bytes8[](length); for (uint i = 0; i < length; i++) { names[i] = collectionNames[_startIndex + i]; } return names; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////// ERC-721 Implementation /////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * @notice Get the balance of `(_owner)` * @param _owner Owner address * @return Owner balance */ function balanceOf(address _owner) public view validAddress(_owner) returns(uint256) { return ownedTokens[_owner].length; } /** * @notice Get the owner of PixelCon `(_tokenId)` * @dev Throws if PixelCon does not exist * @param _tokenId ID of the token * @return Owner of the given PixelCon */ function ownerOf(uint256 _tokenId) public view validId(_tokenId) returns(address) { address owner = tokenLookup[_tokenId].owner; require(owner != address(0), "PixelCon does not exist"); return owner; } /** * @notice Approve `(_to)` to transfer PixelCon `(_tokenId)` (zero indicates no approved address) * @dev Throws if not called by the owner or an approved operator * @param _to Address to be approved * @param _tokenId ID of the token to be approved */ function approve(address _to, uint256 _tokenId) public validId(_tokenId) { address owner = tokenLookup[_tokenId].owner; require(_to != owner, "Cannot approve PixelCon owner"); require(msg.sender == owner || operatorApprovals[owner][msg.sender], "Sender does not have permission to approve address"); tokenApprovals[_tokenId] = _to; emit Approval(owner, _to, _tokenId); } /** * @notice Get the approved address for PixelCon `(_tokenId)` * @dev Throws if the PixelCon does not exist * @param _tokenId ID of the token * @return Address currently approved for the given PixelCon */ function getApproved(uint256 _tokenId) public view validId(_tokenId) returns(address) { address owner = tokenLookup[_tokenId].owner; require(owner != address(0), "PixelCon does not exist"); return tokenApprovals[_tokenId]; } /** * @notice Set or unset the approval of operator `(_to)` * @dev An operator is allowed to transfer all tokens of the sender on their behalf * @param _to Operator address to set the approval * @param _approved Flag for setting approval */ function setApprovalForAll(address _to, bool _approved) public validAddress(_to) { require(_to != msg.sender, "Cannot approve self"); operatorApprovals[msg.sender][_to] = _approved; emit ApprovalForAll(msg.sender, _to, _approved); } /** * @notice Get if `(_operator)` is an approved operator for owner `(_owner)` * @param _owner Owner address * @param _operator Operator address * @return True if the given operator is approved by the given owner */ function isApprovedForAll(address _owner, address _operator) public view validAddress(_owner) validAddress(_operator) returns(bool) { return operatorApprovals[_owner][_operator]; } /** * @notice Transfer the ownership of PixelCon `(_tokenId)` to `(_to)` (try to use 'safeTransferFrom' instead) * @dev Throws if the sender is not the owner, approved, or operator * @param _from Current owner * @param _to Address to receive the PixelCon * @param _tokenId ID of the PixelCon to be transferred */ function transferFrom(address _from, address _to, uint256 _tokenId) public validAddress(_from) validAddress(_to) validId(_tokenId) { require(isApprovedOrOwner(msg.sender, _tokenId), "Sender does not have permission to transfer PixelCon"); clearApproval(_from, _tokenId); removeTokenFrom(_from, _tokenId); addTokenTo(_to, _tokenId); emit Transfer(_from, _to, _tokenId); } /** * @notice Safely transfer the ownership of PixelCon `(_tokenId)` to `(_to)` * @dev Throws if receiver is a contract that does not respond or the sender is not the owner, approved, or operator * @param _from Current owner * @param _to Address to receive the PixelCon * @param _tokenId ID of the PixelCon to be transferred */ function safeTransferFrom(address _from, address _to, uint256 _tokenId) public { //requirements are checked in 'transferFrom' function safeTransferFrom(_from, _to, _tokenId, ""); } /** * @notice Safely transfer the ownership of PixelCon `(_tokenId)` to `(_to)` * @dev Throws if receiver is a contract that does not respond or the sender is not the owner, approved, or operator * @param _from Current owner * @param _to Address to receive the PixelCon * @param _tokenId ID of the PixelCon to be transferred * @param _data Data to send along with a safe transfer check */ function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes _data) public { //requirements are checked in 'transferFrom' function transferFrom(_from, _to, _tokenId); require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data), "Transfer was not safe"); } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////// ERC-721 Enumeration Implementation ///////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * @notice Get the total number of PixelCons in existence * @return Total number of PixelCons in existence */ function totalSupply() public view returns(uint256) { return pixelcons.length; } /** * @notice Get the ID of PixelCon #`(_tokenIndex)` * @dev Throws if index is out of bounds * @param _tokenIndex Counter less than `totalSupply()` * @return `_tokenIndex`th PixelCon ID */ function tokenByIndex(uint256 _tokenIndex) public view returns(uint256) { require(_tokenIndex < totalSupply(), "PixelCon index is out of bounds"); return pixelcons[_tokenIndex].tokenId; } /** * @notice Enumerate PixelCon assigned to owner `(_owner)` * @dev Throws if the index is out of bounds * @param _owner Owner address * @param _index Counter less than `balanceOf(_owner)` * @return PixelCon ID for the `(_index)`th PixelCon in owned by `(_owner)` */ function tokenOfOwnerByIndex(address _owner, uint256 _index) public view validAddress(_owner) returns(uint256) { require(_index < ownedTokens[_owner].length, "Index is out of bounds"); PixelCon storage pixelcon = pixelcons[ownedTokens[_owner][_index]]; return pixelcon.tokenId; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////// ERC-721 Metadata Implementation ////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * @notice Get the name of this contract token * @return Contract token name */ function name() public view returns(string) { return "PixelCons"; } /** * @notice Get the symbol for this contract token * @return Contract token symbol */ function symbol() public view returns(string) { return "PXCN"; } /** * @notice Get a distinct Uniform Resource Identifier (URI) for PixelCon `(_tokenId)` * @dev Throws if the given PixelCon does not exist * @return PixelCon URI */ function tokenURI(uint256 _tokenId) public view returns(string) { TokenLookup storage lookupData = tokenLookup[_tokenId]; require(lookupData.owner != address(0), "PixelCon does not exist"); PixelCon storage pixelcon = pixelcons[lookupData.tokenIndex]; bytes8 pixelconName = pixelconNames[lookupData.tokenIndex]; //Available values: <tokenId>, <tokenIndex>, <name>, <owner>, <creator>, <dateCreated>, <collectionIndex> //start with the token URI template and replace in the appropriate values string memory finalTokenURI = tokenURITemplate; finalTokenURI = StringUtils.replace(finalTokenURI, "<tokenId>", StringUtils.toHexString(_tokenId, 32)); finalTokenURI = StringUtils.replace(finalTokenURI, "<tokenIndex>", StringUtils.toHexString(uint256(lookupData.tokenIndex), 8)); finalTokenURI = StringUtils.replace(finalTokenURI, "<name>", StringUtils.toHexString(uint256(pixelconName), 8)); finalTokenURI = StringUtils.replace(finalTokenURI, "<owner>", StringUtils.toHexString(uint256(lookupData.owner), 20)); finalTokenURI = StringUtils.replace(finalTokenURI, "<creator>", StringUtils.toHexString(uint256(pixelcon.creator), 20)); finalTokenURI = StringUtils.replace(finalTokenURI, "<dateCreated>", StringUtils.toHexString(uint256(pixelcon.dateCreated), 8)); finalTokenURI = StringUtils.replace(finalTokenURI, "<collectionIndex>", StringUtils.toHexString(uint256(pixelcon.collectionIndex), 8)); return finalTokenURI; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////// Utils //////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * @notice Check whether the given editor is the current owner and original creator of a given token ID * @param _address Address to check for * @param _tokenId ID of the token to be edited * @return True if the editor is approved for the given token ID, is an operator of the owner, or is the owner of the token */ function isCreatorAndOwner(address _address, uint256 _tokenId) internal view returns(bool) { TokenLookup storage lookupData = tokenLookup[_tokenId]; address owner = lookupData.owner; address creator = pixelcons[lookupData.tokenIndex].creator; return (_address == owner && _address == creator); } /** * @notice Check whether the given spender can transfer a given token ID * @dev Throws if the PixelCon does not exist * @param _address Address of the spender to query * @param _tokenId ID of the token to be transferred * @return True if the spender is approved for the given token ID, is an operator of the owner, or is the owner of the token */ function isApprovedOrOwner(address _address, uint256 _tokenId) internal view returns(bool) { address owner = tokenLookup[_tokenId].owner; require(owner != address(0), "PixelCon does not exist"); return (_address == owner || tokenApprovals[_tokenId] == _address || operatorApprovals[owner][_address]); } /** * @notice Clear current approval of a given token ID * @dev Throws if the given address is not indeed the owner of the token * @param _owner Owner of the token * @param _tokenId ID of the token to be transferred */ function clearApproval(address _owner, uint256 _tokenId) internal { require(tokenLookup[_tokenId].owner == _owner, "Incorrect PixelCon owner"); if (tokenApprovals[_tokenId] != address(0)) { tokenApprovals[_tokenId] = address(0); } } /** * @notice Add a token ID to the list of a given address * @dev Throws if the receiver address has hit ownership limit or the PixelCon already has an owner * @param _to Address representing the new owner of the given token ID * @param _tokenId ID of the token to be added to the tokens list of the given address */ function addTokenTo(address _to, uint256 _tokenId) internal { uint64[] storage ownedList = ownedTokens[_to]; TokenLookup storage lookupData = tokenLookup[_tokenId]; require(ownedList.length < uint256(2 ** 32) - 1, "Max number of PixelCons per owner has been reached"); require(lookupData.owner == address(0), "PixelCon already has an owner"); lookupData.owner = _to; //update ownedTokens references uint ownedListIndex = ownedList.length; ownedList.length++; lookupData.ownedIndex = uint32(ownedListIndex); ownedList[ownedListIndex] = lookupData.tokenIndex; } /** * @notice Remove a token ID from the list of a given address * @dev Throws if the given address is not indeed the owner of the token * @param _from Address representing the previous owner of the given token ID * @param _tokenId ID of the token to be removed from the tokens list of the given address */ function removeTokenFrom(address _from, uint256 _tokenId) internal { uint64[] storage ownedList = ownedTokens[_from]; TokenLookup storage lookupData = tokenLookup[_tokenId]; require(lookupData.owner == _from, "From address is incorrect"); lookupData.owner = address(0); //update ownedTokens references uint64 replacementTokenIndex = ownedList[ownedList.length - 1]; delete ownedList[ownedList.length - 1]; ownedList.length--; if (lookupData.ownedIndex < ownedList.length) { //we just removed the last token index in the array, but if this wasn't the one to remove, then swap it with the one to remove ownedList[lookupData.ownedIndex] = replacementTokenIndex; tokenLookup[pixelcons[replacementTokenIndex].tokenId].ownedIndex = lookupData.ownedIndex; } lookupData.ownedIndex = 0; } /** * @notice Invoke `onERC721Received` on a target address (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 ID of the token to be transferred * @param _data Optional data to send along with the call * @return True if the call correctly returned the expected value */ function checkAndCallSafeTransfer(address _from, address _to, uint256 _tokenId, bytes _data) internal returns(bool) { if (!_to.isContract()) return true; bytes4 retval = ERC721Receiver(_to).onERC721Received(msg.sender, _from, _tokenId, _data); return (retval == ERC721_RECEIVED); } } /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers from ERC721 asset contracts. * See (https://github.com/OpenZeppelin/openzeppelin-solidity) */ contract ERC721Receiver { /** * @dev Magic value to be returned upon successful reception of an NFT. * Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`, * which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` */ bytes4 internal constant ERC721_RECEIVED = 0x150b7a02; /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a `safetransfer`. This function MAY throw to revert and reject the * transfer. Return of other than the magic value MUST result in the * transaction being reverted. * Note: the contract address is always the message sender. * @param _operator The address which called `safeTransferFrom` function * @param _from The address which previously owned the token * @param _tokenId The NFT identifier which is being transferred * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received(address _operator, address _from, uint256 _tokenId, bytes _data) public returns(bytes4); } /** * @title AddressUtils Library * @dev Utility library of inline functions on addresses. * See (https://github.com/OpenZeppelin/openzeppelin-solidity) */ library AddressUtils { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param _account address of the account to check * @return whether the target address is a contract */ function isContract(address _account) internal view returns(bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. assembly { size := extcodesize(_account) } return size > 0; } } /** * @title StringUtils Library * @dev Utility library of inline functions on strings. * These functions are very expensive and are only intended for web3 calls * @author PixelCons */ library StringUtils { /** * @dev Replaces the given key with the given value in the given string * @param _str String to find and replace in * @param _key Value to search for * @param _value Value to replace key with * @return The replaced string */ function replace(string _str, string _key, string _value) internal pure returns(string) { bytes memory bStr = bytes(_str); bytes memory bKey = bytes(_key); bytes memory bValue = bytes(_value); uint index = indexOf(bStr, bKey); if (index < bStr.length) { bytes memory rStr = new bytes((bStr.length + bValue.length) - bKey.length); uint i; for (i = 0; i < index; i++) rStr[i] = bStr[i]; for (i = 0; i < bValue.length; i++) rStr[index + i] = bValue[i]; for (i = 0; i < bStr.length - (index + bKey.length); i++) rStr[index + bValue.length + i] = bStr[index + bKey.length + i]; return string(rStr); } return string(bStr); } /** * @dev Converts a given number into a string with hex representation * @param _num Number to convert * @param _byteSize Size of the number in bytes * @return The hex representation as string */ function toHexString(uint256 _num, uint _byteSize) internal pure returns(string) { bytes memory s = new bytes(_byteSize * 2 + 2); s[0] = 0x30; s[1] = 0x78; for (uint i = 0; i < _byteSize; i++) { byte b = byte(uint8(_num / (2 ** (8 * (_byteSize - 1 - i))))); byte hi = byte(uint8(b) / 16); byte lo = byte(uint8(b) - 16 * uint8(hi)); s[2 + 2 * i] = char(hi); s[3 + 2 * i] = char(lo); } return string(s); } /** * @dev Gets the ascii hex character for the given value (0-15) * @param _b Byte to get ascii code for * @return The ascii hex character */ function char(byte _b) internal pure returns(byte c) { if (_b < 10) return byte(uint8(_b) + 0x30); else return byte(uint8(_b) + 0x57); } /** * @dev Gets the index of the key string in the given string * @param _str String to search in * @param _key Value to search for * @return The index of the key in the string (string length if not found) */ function indexOf(bytes _str, bytes _key) internal pure returns(uint) { for (uint i = 0; i < _str.length - (_key.length - 1); i++) { bool matchFound = true; for (uint j = 0; j < _key.length; j++) { if (_str[i + j] != _key[j]) { matchFound = false; break; } } if (matchFound) { return i; } } return _str.length; } }
* @dev Gets the ascii hex character for the given value (0-15) @param _b Byte to get ascii code for @return The ascii hex character/
function char(byte _b) internal pure returns(byte c) { if (_b < 10) return byte(uint8(_b) + 0x30); else return byte(uint8(_b) + 0x57); }
1,805,024
[ 1, 3002, 326, 11384, 3827, 3351, 364, 326, 864, 460, 261, 20, 17, 3600, 13, 225, 389, 70, 3506, 358, 336, 11384, 981, 364, 327, 1021, 11384, 3827, 3351, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 1149, 12, 7229, 389, 70, 13, 2713, 16618, 1135, 12, 7229, 276, 13, 203, 202, 95, 203, 202, 202, 430, 261, 67, 70, 411, 1728, 13, 327, 1160, 12, 11890, 28, 24899, 70, 13, 397, 374, 92, 5082, 1769, 203, 202, 202, 12107, 327, 1160, 12, 11890, 28, 24899, 70, 13, 397, 374, 92, 10321, 1769, 203, 202, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.3; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "@openzeppelin/contracts/utils/structs/EnumerableMap.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "./interfaces/IDescendingPriceAuction.sol"; contract DescendingPriceAuction is IDescendingPriceAuction, ReentrancyGuard { using SafeERC20 for IERC20; using Counters for Counters.Counter; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; mapping(uint256 => DPA) private auctions; EnumerableMap.UintToAddressMap private collections; EnumerableMap.UintToAddressMap private auctioneers; Counters.Counter private collectionCount; Counters.Counter private auctionCount; // Mapping from aucitoneer address to their (enumerable) set of auctions mapping(address => EnumerableSet.UintSet) private _byNeer; // Mapping from collectionId to its (enumerable) set of auctions mapping(uint256 => EnumerableSet.UintSet) private _byColl; constructor() { // Start the counts at 1 // the 0th collection is available to all auctionCount.increment(); collectionCount.increment(); } function _msgSender() internal view returns (address) { return msg.sender; } modifier onlyAuctioneer(uint256 _id) { (bool success, address neer) = auctioneers.tryGet(_id); require(success, "non-existent-auction"); require(_msgSender() == neer, "caller-not-auctioneer"); _; } modifier onlyCollectionOwner(uint256 _id) { // anyone can create an auction in the 0th collection if (_id != 0) { (bool success, address owner) = collections.tryGet(_id); require(success, "non-existent-collection"); require(_msgSender() == owner, "caller-not-collection-owner"); } _; } function getAuction(uint256 _id) external view override returns (DPA memory) { return auctions[_id]; } function totalAuctions() external view override returns (uint256) { return auctioneers.length(); } function totalCollections() external view override returns (uint256) { return collections.length(); } function collectionLength(uint256 _id) external view override returns (uint256) { return _byColl[_id].length(); } function neerGroupLength(address _neer) external view override returns (uint256) { return _byNeer[_neer].length(); } // return AuctionId function auctionOfNeerByIndex(address _neer, uint256 i) external view override returns (uint256) { return _byNeer[_neer].at(i); } // return AuctionId function auctionOfCollByIndex(uint256 _id, uint256 i) external view override returns (uint256) { return _byColl[_id].at(i); } function _auctionExists(uint256 _auctionId) internal view virtual returns (bool) { return auctioneers.contains(_auctionId); } function createAuction(DPAConfig memory _auction) external override onlyCollectionOwner(_auction.collectionId) nonReentrant returns (uint256) { require(_auction.endBlock > block.number, "end-block-passed"); require(_auction.ceiling != 0, "start-price-zero"); require(_auction.ceiling >= _auction.floor, "invalid-pricing"); require(_auction.paymentToken != address(0x0), "invalid-payment-token"); require(_auction.payee != address(0x0), "invalid-payee"); require(_auction.tokens.length != 0, "no-line-items"); require( _auction.tokens.length == _auction.tokenAmounts.length, "improper-line-items" ); require(_auction.tokens.length < 8, "too-many-line-items"); return _createAuction(_auction); } function _createAuction(DPAConfig memory _auction) internal returns (uint256) { _pullTokens(_auction.tokens, _auction.tokenAmounts); uint256 id = auctionCount.current(); uint256 decay = _calulateAbsoluteDecay( _auction.ceiling, _auction.floor, block.number, _auction.endBlock ); auctions[id] = DPA({ id: id, ceiling: _auction.ceiling, floor: _auction.floor, absoluteDecay: decay, collectionId: _auction.collectionId, paymentToken: _auction.paymentToken, payee: _auction.payee, startBlock: block.number, endBlock: _auction.endBlock, stopped: false, winner: address(0x0), winningBlock: 0, winningPrice: 0, tokens: _auction.tokens, tokenAmounts: _auction.tokenAmounts }); address neer = _msgSender(); auctioneers.set(id, neer); _byNeer[neer].add(id); _byColl[_auction.collectionId].add(id); auctionCount.increment(); emit AuctionCreated(id, _auction.collectionId, neer); return id; } function _pullTokens(address[] memory tokens, uint256[] memory amounts) internal { for (uint256 i = 0; i < tokens.length; i++) { _pullToken(tokens[i], amounts[i]); } } function _pullToken(address _token, uint256 _amount) internal { require(_amount != 0, "invalid-token-amount"); _safeTransferFromExact(_token, _msgSender(), address(this), _amount); } function _sendTokens( address recipient, address[] memory tokens, uint256[] memory amounts ) internal { for (uint256 i = 0; i < tokens.length; i++) { IERC20(tokens[i]).safeTransfer(recipient, amounts[i]); } } function stopAuction(uint256 _id) external override onlyAuctioneer(_id) nonReentrant { DPA storage auction = auctions[_id]; require( auction.winner == address(0x0) && !auction.stopped, "cant-be-stopped" ); _sendTokens(_msgSender(), auction.tokens, auction.tokenAmounts); auctions[_id].stopped = true; emit AuctionStopped(_id); } function bid(uint256 _id) external override nonReentrant { require(_auctionExists(_id), "no-such-auction-id"); DPA storage auction = auctions[_id]; require(auction.winner == address(0x0), "auction-has-ended"); require(!auction.stopped, "auction-has-been-stopped"); uint256 price = _getCurrentPrice( auction.absoluteDecay, auction.floor, auction.endBlock, block.number ); address bidder = _msgSender(); _safeTransferFromExact( auction.paymentToken, bidder, auction.payee, price ); _sendTokens(bidder, auction.tokens, auction.tokenAmounts); auction.stopped = true; auction.winner = bidder; auction.winningBlock = block.number; auction.winningPrice = price; auctions[_id] = auction; emit AuctionWon(_id, price, auction.paymentToken, bidder); } function getCurrentPrice(uint256 _id) external view override returns (uint256) { require(_auctionExists(_id), "no-such-auction-id"); DPA storage a = auctions[_id]; return _getCurrentPrice( a.absoluteDecay, a.floor, a.endBlock, block.number ); } function _getCurrentPrice( uint256 m, uint256 f, uint256 e, uint256 t ) internal pure returns (uint256 p) { if (t > e) return f; if (m == 0) return f; // compute price starting from floor p = f + (m * (e - t)) / 1e18; } function _calulateAbsoluteDecay( uint256 c, uint256 f, uint256 s, uint256 e ) internal pure returns (uint256) { require(e > s, "invalid-ramp"); require(c >= f, "price-not-descending-or-const"); return ((c - f) * 1e18) / (e - s); } function _safeTransferFromExact( address _token, address _from, address _to, uint256 _amount ) internal { IERC20 token = IERC20(_token); uint256 before = token.balanceOf(_to); token.safeTransferFrom(_from, _to, _amount); require( token.balanceOf(_to) - before == _amount, "not-enough-transferred" ); } function createCollection() external override nonReentrant returns (uint256) { uint256 id = collectionCount.current(); address owner = _msgSender(); collections.set(id, owner); collectionCount.increment(); emit CollectionCreated(id, owner); return id; } function transferCollection(address _to, uint256 _id) external override onlyCollectionOwner(_id) nonReentrant { collections.set(_id, _to); emit CollectionTransfer(_id, _msgSender(), _to); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. 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; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // 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] = 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) { 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.8.0; import "./EnumerableSet.sol"; /** * @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 { using EnumerableSet for EnumerableSet.Bytes32Set; // 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 Map { // Storage of keys EnumerableSet.Bytes32Set _keys; mapping (bytes32 => bytes32) _values; } /** * @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) { map._values[key] = value; return map._keys.add(key); } /** * @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) { delete map._values[key]; return map._keys.remove(key); } /** * @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._keys.contains(key); } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._keys.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) { bytes32 key = map._keys.at(index); return (key, map._values[key]); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { bytes32 value = map._values[key]; if (value == bytes32(0)) { return (_contains(map, key), bytes32(0)); } else { return (true, 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) { bytes32 value = map._values[key]; require(value != 0 || _contains(map, key), "EnumerableMap: nonexistent key"); return value; } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { bytes32 value = map._values[key]; require(value != 0 || _contains(map, key), errorMessage); return value; } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; struct DPAConfig { uint256 ceiling; uint256 floor; uint256 collectionId; address paymentToken; address payee; uint256 endBlock; address[] tokens; uint256[] tokenAmounts; } struct DPA { uint256 id; uint256 ceiling; uint256 floor; uint256 absoluteDecay; uint256 collectionId; address paymentToken; address payee; uint256 startBlock; uint256 endBlock; bool stopped; address winner; uint256 winningBlock; uint256 winningPrice; address[] tokens; uint256[] tokenAmounts; } interface IDescendingPriceAuction { event AuctionCreated(uint256 id, uint256 collectionId, address auctioneer); event CollectionCreated(uint256 id, address owner); event CollectionTransfer(uint256 id, address from, address to); event AuctionStopped(uint256 id); event AuctionWon( uint256 id, uint256 price, address paymentToken, address winner ); function getAuction(uint256 _id) external view returns (DPA memory); function totalAuctions() external view returns (uint256); function totalCollections() external view returns (uint256); function collectionLength(uint256 _id) external view returns (uint256); function neerGroupLength(address _neer) external view returns (uint256); function auctionOfNeerByIndex(address _neer, uint256 i) external view returns (uint256); function auctionOfCollByIndex(uint256 _id, uint256 i) external view returns (uint256); function createAuction(DPAConfig memory _auction) external returns (uint256); function stopAuction(uint256 _id) external; function bid(uint256 _id) external; function getCurrentPrice(uint256 _id) external view returns (uint256); function createCollection() external returns (uint256); function transferCollection(address _to, uint256 _id) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
Mapping from aucitoneer address to their (enumerable) set of auctions Mapping from collectionId to its (enumerable) set of auctions
contract DescendingPriceAuction is IDescendingPriceAuction, ReentrancyGuard { using SafeERC20 for IERC20; using Counters for Counters.Counter; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; mapping(uint256 => DPA) private auctions; EnumerableMap.UintToAddressMap private collections; EnumerableMap.UintToAddressMap private auctioneers; Counters.Counter private collectionCount; Counters.Counter private auctionCount; mapping(address => EnumerableSet.UintSet) private _byNeer; mapping(uint256 => EnumerableSet.UintSet) private _byColl; constructor() { auctionCount.increment(); collectionCount.increment(); } function _msgSender() internal view returns (address) { return msg.sender; } modifier onlyAuctioneer(uint256 _id) { (bool success, address neer) = auctioneers.tryGet(_id); require(success, "non-existent-auction"); require(_msgSender() == neer, "caller-not-auctioneer"); _; } modifier onlyCollectionOwner(uint256 _id) { if (_id != 0) { (bool success, address owner) = collections.tryGet(_id); require(success, "non-existent-collection"); require(_msgSender() == owner, "caller-not-collection-owner"); } _; } modifier onlyCollectionOwner(uint256 _id) { if (_id != 0) { (bool success, address owner) = collections.tryGet(_id); require(success, "non-existent-collection"); require(_msgSender() == owner, "caller-not-collection-owner"); } _; } function getAuction(uint256 _id) external view override returns (DPA memory) { return auctions[_id]; } function totalAuctions() external view override returns (uint256) { return auctioneers.length(); } function totalCollections() external view override returns (uint256) { return collections.length(); } function collectionLength(uint256 _id) external view override returns (uint256) { return _byColl[_id].length(); } function neerGroupLength(address _neer) external view override returns (uint256) { return _byNeer[_neer].length(); } function auctionOfNeerByIndex(address _neer, uint256 i) external view override returns (uint256) { return _byNeer[_neer].at(i); } function auctionOfCollByIndex(uint256 _id, uint256 i) external view override returns (uint256) { return _byColl[_id].at(i); } function _auctionExists(uint256 _auctionId) internal view virtual returns (bool) { return auctioneers.contains(_auctionId); } function createAuction(DPAConfig memory _auction) external override onlyCollectionOwner(_auction.collectionId) nonReentrant returns (uint256) { require(_auction.endBlock > block.number, "end-block-passed"); require(_auction.ceiling != 0, "start-price-zero"); require(_auction.ceiling >= _auction.floor, "invalid-pricing"); require(_auction.paymentToken != address(0x0), "invalid-payment-token"); require(_auction.payee != address(0x0), "invalid-payee"); require(_auction.tokens.length != 0, "no-line-items"); require( _auction.tokens.length == _auction.tokenAmounts.length, "improper-line-items" ); require(_auction.tokens.length < 8, "too-many-line-items"); return _createAuction(_auction); } function _createAuction(DPAConfig memory _auction) internal returns (uint256) { _pullTokens(_auction.tokens, _auction.tokenAmounts); uint256 id = auctionCount.current(); uint256 decay = _calulateAbsoluteDecay( _auction.ceiling, _auction.floor, block.number, _auction.endBlock ); auctions[id] = DPA({ id: id, ceiling: _auction.ceiling, floor: _auction.floor, absoluteDecay: decay, collectionId: _auction.collectionId, paymentToken: _auction.paymentToken, payee: _auction.payee, startBlock: block.number, endBlock: _auction.endBlock, stopped: false, winner: address(0x0), winningBlock: 0, winningPrice: 0, tokens: _auction.tokens, tokenAmounts: _auction.tokenAmounts }); address neer = _msgSender(); auctioneers.set(id, neer); _byNeer[neer].add(id); _byColl[_auction.collectionId].add(id); auctionCount.increment(); emit AuctionCreated(id, _auction.collectionId, neer); return id; } function _createAuction(DPAConfig memory _auction) internal returns (uint256) { _pullTokens(_auction.tokens, _auction.tokenAmounts); uint256 id = auctionCount.current(); uint256 decay = _calulateAbsoluteDecay( _auction.ceiling, _auction.floor, block.number, _auction.endBlock ); auctions[id] = DPA({ id: id, ceiling: _auction.ceiling, floor: _auction.floor, absoluteDecay: decay, collectionId: _auction.collectionId, paymentToken: _auction.paymentToken, payee: _auction.payee, startBlock: block.number, endBlock: _auction.endBlock, stopped: false, winner: address(0x0), winningBlock: 0, winningPrice: 0, tokens: _auction.tokens, tokenAmounts: _auction.tokenAmounts }); address neer = _msgSender(); auctioneers.set(id, neer); _byNeer[neer].add(id); _byColl[_auction.collectionId].add(id); auctionCount.increment(); emit AuctionCreated(id, _auction.collectionId, neer); return id; } function _pullTokens(address[] memory tokens, uint256[] memory amounts) internal { for (uint256 i = 0; i < tokens.length; i++) { _pullToken(tokens[i], amounts[i]); } } function _pullTokens(address[] memory tokens, uint256[] memory amounts) internal { for (uint256 i = 0; i < tokens.length; i++) { _pullToken(tokens[i], amounts[i]); } } function _pullToken(address _token, uint256 _amount) internal { require(_amount != 0, "invalid-token-amount"); _safeTransferFromExact(_token, _msgSender(), address(this), _amount); } function _sendTokens( address recipient, address[] memory tokens, uint256[] memory amounts ) internal { for (uint256 i = 0; i < tokens.length; i++) { IERC20(tokens[i]).safeTransfer(recipient, amounts[i]); } } function _sendTokens( address recipient, address[] memory tokens, uint256[] memory amounts ) internal { for (uint256 i = 0; i < tokens.length; i++) { IERC20(tokens[i]).safeTransfer(recipient, amounts[i]); } } function stopAuction(uint256 _id) external override onlyAuctioneer(_id) nonReentrant { DPA storage auction = auctions[_id]; require( auction.winner == address(0x0) && !auction.stopped, "cant-be-stopped" ); _sendTokens(_msgSender(), auction.tokens, auction.tokenAmounts); auctions[_id].stopped = true; emit AuctionStopped(_id); } function bid(uint256 _id) external override nonReentrant { require(_auctionExists(_id), "no-such-auction-id"); DPA storage auction = auctions[_id]; require(auction.winner == address(0x0), "auction-has-ended"); require(!auction.stopped, "auction-has-been-stopped"); uint256 price = _getCurrentPrice( auction.absoluteDecay, auction.floor, auction.endBlock, block.number ); address bidder = _msgSender(); _safeTransferFromExact( auction.paymentToken, bidder, auction.payee, price ); _sendTokens(bidder, auction.tokens, auction.tokenAmounts); auction.stopped = true; auction.winner = bidder; auction.winningBlock = block.number; auction.winningPrice = price; auctions[_id] = auction; emit AuctionWon(_id, price, auction.paymentToken, bidder); } function getCurrentPrice(uint256 _id) external view override returns (uint256) { require(_auctionExists(_id), "no-such-auction-id"); DPA storage a = auctions[_id]; return _getCurrentPrice( a.absoluteDecay, a.floor, a.endBlock, block.number ); } function _getCurrentPrice( uint256 m, uint256 f, uint256 e, uint256 t ) internal pure returns (uint256 p) { if (t > e) return f; if (m == 0) return f; p = f + (m * (e - t)) / 1e18; } function _calulateAbsoluteDecay( uint256 c, uint256 f, uint256 s, uint256 e ) internal pure returns (uint256) { require(e > s, "invalid-ramp"); require(c >= f, "price-not-descending-or-const"); return ((c - f) * 1e18) / (e - s); } function _safeTransferFromExact( address _token, address _from, address _to, uint256 _amount ) internal { IERC20 token = IERC20(_token); uint256 before = token.balanceOf(_to); token.safeTransferFrom(_from, _to, _amount); require( token.balanceOf(_to) - before == _amount, "not-enough-transferred" ); } function createCollection() external override nonReentrant returns (uint256) { uint256 id = collectionCount.current(); address owner = _msgSender(); collections.set(id, owner); collectionCount.increment(); emit CollectionCreated(id, owner); return id; } function transferCollection(address _to, uint256 _id) external override onlyCollectionOwner(_id) nonReentrant { collections.set(_id, _to); emit CollectionTransfer(_id, _msgSender(), _to); } }
10,440,408
[ 1, 3233, 628, 279, 5286, 305, 476, 264, 1758, 358, 3675, 261, 7924, 25121, 13, 444, 434, 279, 4062, 87, 9408, 628, 1849, 548, 358, 2097, 261, 7924, 25121, 13, 444, 434, 279, 4062, 87, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 13913, 2846, 5147, 37, 4062, 353, 1599, 742, 2846, 5147, 37, 4062, 16, 868, 8230, 12514, 16709, 288, 203, 565, 1450, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 203, 565, 1450, 9354, 87, 364, 9354, 87, 18, 4789, 31, 203, 565, 1450, 6057, 25121, 694, 364, 6057, 25121, 694, 18, 5487, 694, 31, 203, 565, 1450, 6057, 25121, 863, 364, 6057, 25121, 863, 18, 5487, 774, 1887, 863, 31, 203, 203, 565, 2874, 12, 11890, 5034, 516, 463, 4066, 13, 3238, 279, 4062, 87, 31, 203, 565, 6057, 25121, 863, 18, 5487, 774, 1887, 863, 3238, 6980, 31, 203, 565, 6057, 25121, 863, 18, 5487, 774, 1887, 863, 3238, 279, 4062, 73, 414, 31, 203, 565, 9354, 87, 18, 4789, 3238, 1849, 1380, 31, 203, 565, 9354, 87, 18, 4789, 3238, 279, 4062, 1380, 31, 203, 203, 565, 2874, 12, 2867, 516, 6057, 25121, 694, 18, 5487, 694, 13, 3238, 389, 1637, 50, 4943, 31, 203, 203, 565, 2874, 12, 11890, 5034, 516, 6057, 25121, 694, 18, 5487, 694, 13, 3238, 389, 1637, 13535, 31, 203, 203, 203, 565, 3885, 1435, 288, 203, 3639, 279, 4062, 1380, 18, 15016, 5621, 203, 3639, 1849, 1380, 18, 15016, 5621, 203, 565, 289, 203, 203, 565, 445, 389, 3576, 12021, 1435, 2713, 1476, 1135, 261, 2867, 13, 288, 203, 3639, 327, 1234, 18, 15330, 31, 203, 565, 289, 203, 203, 565, 9606, 1338, 37, 4062, 4943, 12, 11890, 5034, 389, 350, 13, 288, 203, 3639, 261, 6430, 2216, 16, 1758, 1073, 264, 13, 2 ]
./full_match/1/0xEe3B337070Fe655b62a844E85FA09C9cFDC01794/sources/contracts/WastelandsGenesis1.sol
Verify whitelist requirements
function whitelistMint(uint256 _mintAmount, bytes32[] calldata _merkleProof) external payable mintCompliance(_mintAmount) mintPriceCompliance(_mintAmount) nonReentrant { require(mintWithETH, "Mint with ETH is turned off"); require(whitelistMintEnabled, "The whitelist sale is not enabled!"); bytes32 leaf = keccak256(abi.encodePacked(_msgSender())); require( MerkleProof.verify(_merkleProof, merkleRoot, leaf), "Invalid proof!" ); require( balanceOf(_msgSender()) <= maxMintAmountPerWallet, "Max NFTs per wallet" ); _safeMint(_msgSender(), _mintAmount); }
3,849,637
[ 1, 8097, 10734, 8433, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 10734, 49, 474, 12, 11890, 5034, 389, 81, 474, 6275, 16, 1731, 1578, 8526, 745, 892, 389, 6592, 15609, 20439, 13, 203, 3639, 3903, 203, 3639, 8843, 429, 203, 3639, 312, 474, 16687, 24899, 81, 474, 6275, 13, 203, 3639, 312, 474, 5147, 16687, 24899, 81, 474, 6275, 13, 203, 3639, 1661, 426, 8230, 970, 203, 565, 288, 203, 3639, 2583, 12, 81, 474, 1190, 1584, 44, 16, 315, 49, 474, 598, 512, 2455, 353, 21826, 3397, 8863, 203, 203, 3639, 2583, 12, 20409, 49, 474, 1526, 16, 315, 1986, 10734, 272, 5349, 353, 486, 3696, 4442, 1769, 203, 3639, 1731, 1578, 7839, 273, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 24899, 3576, 12021, 1435, 10019, 203, 3639, 2583, 12, 203, 5411, 31827, 20439, 18, 8705, 24899, 6592, 15609, 20439, 16, 30235, 2375, 16, 7839, 3631, 203, 5411, 315, 1941, 14601, 4442, 203, 3639, 11272, 203, 203, 3639, 2583, 12, 203, 5411, 11013, 951, 24899, 3576, 12021, 10756, 1648, 943, 49, 474, 6275, 2173, 16936, 16, 203, 5411, 315, 2747, 423, 4464, 87, 1534, 9230, 6, 203, 3639, 11272, 377, 203, 203, 3639, 389, 4626, 49, 474, 24899, 3576, 12021, 9334, 389, 81, 474, 6275, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0xf0691A2F53Ea2D172D863eac0F6875A5d609BFF3/sources/contracts/test.sol
* @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the account that deploys the contract. See {ERC20-constructor}./
constructor(string memory name, string memory symbol) ERC20(name, symbol) { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); _setupRole(PAUSER_ROLE, _msgSender()); _setupRole(BURNER_ROLE, _msgSender()); }
12,342,620
[ 1, 29598, 1375, 5280, 67, 15468, 67, 16256, 9191, 1375, 6236, 2560, 67, 16256, 68, 471, 1375, 4066, 4714, 67, 16256, 68, 358, 326, 2236, 716, 5993, 383, 1900, 326, 6835, 18, 2164, 288, 654, 39, 3462, 17, 12316, 5496, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 12, 1080, 3778, 508, 16, 533, 3778, 3273, 13, 4232, 39, 3462, 12, 529, 16, 3273, 13, 288, 203, 3639, 389, 8401, 2996, 12, 5280, 67, 15468, 67, 16256, 16, 389, 3576, 12021, 10663, 203, 203, 3639, 389, 8401, 2996, 12, 6236, 2560, 67, 16256, 16, 389, 3576, 12021, 10663, 203, 3639, 389, 8401, 2996, 12, 4066, 4714, 67, 16256, 16, 389, 3576, 12021, 10663, 203, 3639, 389, 8401, 2996, 12, 38, 8521, 654, 67, 16256, 16, 389, 3576, 12021, 10663, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// Based on https://github.com/HausDAO/Molochv2.1 // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; // import "hardhat/console.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom( address from, address to, uint256 value ) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval( address indexed owner, address indexed spender, uint256 value ); } contract Moloch is ReentrancyGuard { /*************** GLOBAL CONSTANTS ***************/ uint256 public periodDuration; // default = 17280 = 4.8 hours in seconds (5 periods per day) uint256 public votingPeriodLength; // default = 35 periods (7 days) uint256 public gracePeriodLength; // default = 35 periods (7 days) uint256 public proposalDeposit; // default = 10 ETH (~$1,000 worth of ETH at contract deployment) uint256 public dilutionBound; // default = 3 - maximum multiplier a YES voter will be obligated to pay in case of mass ragequit uint256 public processingReward; // default = 0.1 - amount of ETH to give to whoever processes a proposal uint256 public summoningTime; // needed to determine the current period bool private initialized; // internally tracks deployment under eip-1167 proxy pattern address public depositToken; // deposit token contract reference; default = wETH uint256 public spamPrevention; address public spamPreventionAddr; // can have multiple shamans mapping(address => bool) public shamans; // HARD-CODED LIMITS // These numbers are quite arbitrary; they are small enough to avoid overflows when doing calculations // with periods or shares, yet big enough to not limit reasonable use cases. uint256 constant MAX_VOTING_PERIOD_LENGTH = 10**18; // maximum length of voting period uint256 constant MAX_GRACE_PERIOD_LENGTH = 10**18; // maximum length of grace period uint256 constant MAX_DILUTION_BOUND = 10**18; // maximum dilution bound uint256 constant MAX_NUMBER_OF_SHARES_AND_LOOT = 10**18; // maximum number of shares that can be minted uint256 constant MAX_TOKEN_WHITELIST_COUNT = 400; // maximum number of whitelisted tokens uint256 constant MAX_TOKEN_GUILDBANK_COUNT = 200; // maximum number of tokens with non-zero balance in guildbank // *************** // EVENTS // *************** event SummonComplete( address indexed summoner, address[] tokens, uint256 summoningTime, uint256 periodDuration, uint256 votingPeriodLength, uint256 gracePeriodLength, uint256 proposalDeposit, uint256 dilutionBound, uint256 processingReward ); event SubmitProposal( address indexed applicant, uint256 sharesRequested, uint256 lootRequested, uint256 tributeOffered, address tributeToken, uint256 paymentRequested, address paymentToken, string details, bool[6] flags, uint256 proposalId, address indexed delegateKey, address indexed memberAddress ); event SponsorProposal( address indexed delegateKey, address indexed memberAddress, uint256 proposalId, uint256 proposalIndex, uint256 startingPeriod ); event SubmitVote( uint256 proposalId, uint256 indexed proposalIndex, address indexed delegateKey, address indexed memberAddress, uint8 uintVote ); event ProcessProposal( uint256 indexed proposalIndex, uint256 indexed proposalId, bool didPass ); event ProcessWhitelistProposal( uint256 indexed proposalIndex, uint256 indexed proposalId, bool didPass ); event ProcessGuildKickProposal( uint256 indexed proposalIndex, uint256 indexed proposalId, bool didPass ); event Ragequit( address indexed memberAddress, uint256 sharesToBurn, uint256 lootToBurn ); event TokensCollected(address indexed token, uint256 amountToCollect); event CancelProposal(uint256 indexed proposalId, address applicantAddress); event UpdateDelegateKey( address indexed memberAddress, address newDelegateKey ); event Withdraw( address indexed memberAddress, address token, uint256 amount ); event Shaman( address indexed memberAddress, uint256 shares, uint256 loot, bool mint ); event SetSpamPrevention(address spamPreventionAddr, uint256 spamPrevention); event SetShaman(address indexed shaman, bool isEnabled); event SetConfig( uint256 periodDuration, uint256 votingPeriodLength, uint256 gracePeriodLength, uint256 proposalDeposit, uint256 dilutionBound, uint256 processingReward ); // ******************* // INTERNAL ACCOUNTING // ******************* uint256 public proposalCount = 0; // total proposals submitted uint256 public totalShares = 0; // total shares across all members uint256 public totalLoot = 0; // total loot across all members uint256 public totalGuildBankTokens = 0; // total tokens with non-zero balance in guild bank address public constant GUILD = address(0xdead); address public constant ESCROW = address(0xbeef); address public constant TOTAL = address(0xbabe); mapping(address => mapping(address => uint256)) public userTokenBalances; // userTokenBalances[userAddress][tokenAddress] enum Vote { Null, // default value, counted as abstention Yes, No } struct Member { address delegateKey; // the key responsible for submitting proposals and voting - defaults to member address unless updated uint256 shares; // the # of voting shares assigned to this member uint256 loot; // the loot amount available to this member (combined with shares on ragequit) bool exists; // always true once a member has been created uint256 highestIndexYesVote; // highest proposal index # on which the member voted YES uint256 jailed; // set to proposalIndex of a passing guild kick proposal for this member, prevents voting on and sponsoring proposals } struct Proposal { address applicant; // the applicant who wishes to become a member - this key will be used for withdrawals (doubles as guild kick target for gkick proposals) address proposer; // the account that submitted the proposal (can be non-member) address sponsor; // the member that sponsored the proposal (moving it into the queue) uint256 sharesRequested; // the # of shares the applicant is requesting uint256 lootRequested; // the amount of loot the applicant is requesting uint256 tributeOffered; // amount of tokens offered as tribute address tributeToken; // tribute token contract reference uint256 paymentRequested; // amount of tokens requested as payment address paymentToken; // payment token contract reference uint256 startingPeriod; // the period in which voting can start for this proposal uint256 yesVotes; // the total number of YES votes for this proposal uint256 noVotes; // the total number of NO votes for this proposal bool[6] flags; // [sponsored, processed, didPass, cancelled, whitelist, guildkick] string details; // proposal details - could be IPFS hash, plaintext, or JSON uint256 maxTotalSharesAndLootAtYesVote; // the maximum # of total shares encountered at a yes vote on this proposal } mapping(uint256 => mapping(address => Vote)) voteHistory; // maps voting decisions on proposals proposal => member => voted mapping(address => bool) public tokenWhitelist; address[] public approvedTokens; mapping(address => bool) public proposedToWhitelist; mapping(address => bool) public proposedToKick; mapping(address => Member) public members; mapping(address => address) public memberAddressByDelegateKey; // TODO: whats this for? address[] public memberList; mapping(uint256 => Proposal) public proposals; uint256[] public proposalQueue; modifier onlyMember() { require( members[msg.sender].shares > 0 || members[msg.sender].loot > 0, "not a member" ); _; } modifier onlyShareholder() { require(members[msg.sender].shares > 0, "not a shareholder"); _; } modifier onlyDelegate() { require( members[memberAddressByDelegateKey[msg.sender]].shares > 0, "not a delegate" ); _; } modifier onlyDelegateOrShaman() { require( members[memberAddressByDelegateKey[msg.sender]].shares > 0 || shamans[msg.sender], "!delegate || !shaman" ); _; } modifier onlyShaman() { require(shamans[msg.sender], "!shaman"); _; } function setShaman(address _shaman, bool _enable) public onlyShaman { shamans[_shaman] = _enable; emit SetShaman(_shaman, _enable); } function setConfig(address _spamPreventionAddr, uint256 _spamPrevention) public onlyShaman { spamPreventionAddr = _spamPreventionAddr; spamPrevention = _spamPrevention; emit SetSpamPrevention(_spamPreventionAddr, _spamPrevention); } // allow member to do this if no active props function setSharesLoot( address[] memory _applicants, uint256[] memory _applicantShares, uint256[] memory _applicantLoot, bool mint ) public onlyShaman { require(_applicants.length == _applicantShares.length, "mismatch"); require(_applicants.length == _applicantLoot.length, "mismatch"); for (uint256 i = 0; i < _applicants.length; i++) { _setSharesLoot( _applicants[i], _applicantShares[i], _applicantLoot[i], mint ); // TODO: maybe emit only once in the future emit Shaman( _applicants[i], _applicantShares[i], _applicantLoot[i], mint ); } } function setSingleSharesLoot( address _applicant, uint256 _applicantShares, uint256 _applicantLoot, bool mint ) public onlyShaman { _setSharesLoot( _applicant, _applicantShares, _applicantLoot, mint ); // TODO: maybe emit only once in the future emit Shaman(_applicant, _applicantShares, _applicantLoot, mint); } function _setSharesLoot( address applicant, uint256 shares, uint256 loot, bool mint ) internal { if (mint) { if (members[applicant].exists) { members[applicant].shares = members[applicant].shares + shares; members[applicant].loot = members[applicant].loot + loot; // the applicant is a new member, create a new record for them } else { // if the applicant address is already taken by a member's delegateKey, reset it to their member address if (members[memberAddressByDelegateKey[applicant]].exists) { address memberToOverride = memberAddressByDelegateKey[ applicant ]; memberAddressByDelegateKey[ memberToOverride ] = memberToOverride; members[memberToOverride].delegateKey = memberToOverride; } // use applicant address as delegateKey by default members[applicant] = Member( applicant, shares, loot, true, 0, 0 ); memberAddressByDelegateKey[applicant] = applicant; } totalShares = totalShares + shares; totalLoot = totalLoot + loot; } else { members[applicant].shares = members[applicant].shares - shares; members[applicant].loot = members[applicant].loot - loot; totalShares = totalShares - shares; totalLoot = totalLoot - loot; } require( (totalShares + shares + loot) <= MAX_NUMBER_OF_SHARES_AND_LOOT, "too many shares requested" ); } function _setConfig( uint256 _periodDuration, uint256 _votingPeriodLength, uint256 _gracePeriodLength, uint256 _proposalDeposit, uint256 _dilutionBound, uint256 _processingReward ) internal { require(_periodDuration > 0, "_periodDuration cannot be 0"); require(_votingPeriodLength > 0, "_votingPeriodLength cannot be 0"); require( _votingPeriodLength <= MAX_VOTING_PERIOD_LENGTH, "_votingPeriodLength exceeds limit" ); require( _gracePeriodLength <= MAX_GRACE_PERIOD_LENGTH, "_gracePeriodLength exceeds limit" ); require(_dilutionBound > 0, "_dilutionBound cannot be 0"); require( _dilutionBound <= MAX_DILUTION_BOUND, "_dilutionBound exceeds limit" ); require( _proposalDeposit >= _processingReward, "_proposalDeposit cannot be smaller than _processingReward" ); periodDuration = _periodDuration; votingPeriodLength = _votingPeriodLength; gracePeriodLength = _gracePeriodLength; proposalDeposit = _proposalDeposit; dilutionBound = _dilutionBound; processingReward = _processingReward; } function init( // address _summoner, address _shaman, address[] calldata _approvedTokens, uint256 _periodDuration, uint256 _votingPeriodLength, uint256 _gracePeriodLength, uint256 _proposalDeposit, uint256 _dilutionBound, uint256 _processingReward ) external { require(!initialized, "initialized"); require(_approvedTokens.length > 0, "need at least one approved token"); require( _approvedTokens.length <= MAX_TOKEN_WHITELIST_COUNT, "too many tokens" ); _setConfig( _periodDuration, _votingPeriodLength, _gracePeriodLength, _proposalDeposit, _dilutionBound, _processingReward ); summoningTime = block.timestamp; initialized = true; depositToken = _approvedTokens[0]; shamans[_shaman] = true; require( totalShares <= MAX_NUMBER_OF_SHARES_AND_LOOT, "too many shares requested" ); for (uint256 i = 0; i < _approvedTokens.length; i++) { require( _approvedTokens[i] != address(0), "_approvedToken cannot be 0" ); require( !tokenWhitelist[_approvedTokens[i]], "duplicate approved token" ); tokenWhitelist[_approvedTokens[i]] = true; approvedTokens.push(_approvedTokens[i]); } } /***************** PROPOSAL FUNCTIONS *****************/ function submitProposal( address applicant, uint256 sharesRequested, uint256 lootRequested, uint256 tributeOffered, address tributeToken, uint256 paymentRequested, address paymentToken, string memory details ) public nonReentrant returns (uint256 proposalId) { require( (sharesRequested + lootRequested) <= MAX_NUMBER_OF_SHARES_AND_LOOT, "too many shares requested" ); require( tokenWhitelist[tributeToken], "tributeToken is not whitelisted" ); require(tokenWhitelist[paymentToken], "payment is not whitelisted"); require(applicant != address(0), "applicant cannot be 0"); require( applicant != GUILD && applicant != ESCROW && applicant != TOTAL, "applicant address cannot be reserved" ); require( members[applicant].jailed == 0, "proposal applicant must not be jailed" ); if (tributeOffered > 0 && userTokenBalances[GUILD][tributeToken] == 0) { require( totalGuildBankTokens < MAX_TOKEN_GUILDBANK_COUNT, "cannot submit more tribute proposals for new tokens - guildbank is full" ); } // collect tribute from proposer and store it in the Moloch until the proposal is processed require( IERC20(tributeToken).transferFrom( msg.sender, address(this), tributeOffered ), "tribute token transfer failed" ); unsafeAddToBalance(ESCROW, tributeToken, tributeOffered); bool[6] memory flags; // [sponsored, processed, didPass, cancelled, whitelist, guildkick] _submitProposal( applicant, sharesRequested, lootRequested, tributeOffered, tributeToken, paymentRequested, paymentToken, details, flags ); return proposalCount - 1; // return proposalId - contracts calling submit might want it } function submitWhitelistProposal( address tokenToWhitelist, string memory details ) public nonReentrant returns (uint256 proposalId) { require(tokenToWhitelist != address(0), "must provide token address"); require( !tokenWhitelist[tokenToWhitelist], "cannot already have whitelisted the token" ); require( approvedTokens.length < MAX_TOKEN_WHITELIST_COUNT, "cannot submit more whitelist proposals" ); bool[6] memory flags; // [sponsored, processed, didPass, cancelled, whitelist, guildkick] flags[4] = true; // whitelist _submitProposal( address(0), 0, 0, 0, tokenToWhitelist, 0, address(0), details, flags ); return proposalCount - 1; } function submitGuildKickProposal( address memberToKick, string memory details ) public nonReentrant returns (uint256 proposalId) { Member memory member = members[memberToKick]; require( member.shares > 0 || member.loot > 0, "member must have at least one share or one loot" ); require( members[memberToKick].jailed == 0, "member must not already be jailed" ); bool[6] memory flags; // [sponsored, processed, didPass, cancelled, whitelist, guildkick] flags[5] = true; // guild kick _submitProposal( memberToKick, 0, 0, 0, address(0), 0, address(0), details, flags ); return proposalCount - 1; } function _submitProposal( address applicant, uint256 sharesRequested, uint256 lootRequested, uint256 tributeOffered, address tributeToken, uint256 paymentRequested, address paymentToken, string memory details, bool[6] memory flags ) internal { require(msg.value >= spamPrevention, "spam prevention on"); if (spamPrevention > 0 && !shamans[msg.sender]) { (bool success, ) = spamPreventionAddr.call{value: msg.value}(""); require(success, "failed"); } Proposal memory proposal = Proposal({ applicant: applicant, proposer: msg.sender, sponsor: address(0), sharesRequested: sharesRequested, lootRequested: lootRequested, tributeOffered: tributeOffered, tributeToken: tributeToken, paymentRequested: paymentRequested, paymentToken: paymentToken, startingPeriod: 0, yesVotes: 0, noVotes: 0, flags: flags, details: details, maxTotalSharesAndLootAtYesVote: 0 }); proposals[proposalCount] = proposal; address memberAddress = memberAddressByDelegateKey[msg.sender]; // NOTE: argument order matters, avoid stack too deep emit SubmitProposal( applicant, sharesRequested, lootRequested, tributeOffered, tributeToken, paymentRequested, paymentToken, details, flags, proposalCount, msg.sender, memberAddress ); proposalCount += 1; } function sponsorProposal(uint256 proposalId) public nonReentrant onlyDelegate { // collect proposal deposit from sponsor and store it in the Moloch until the proposal is processed require( IERC20(depositToken).transferFrom( msg.sender, address(this), proposalDeposit ), "proposal deposit token transfer failed" ); unsafeAddToBalance(ESCROW, depositToken, proposalDeposit); Proposal storage proposal = proposals[proposalId]; require( proposal.proposer != address(0), "proposal must have been proposed" ); require(!proposal.flags[0], "proposal has already been sponsored"); require(!proposal.flags[3], "proposal has been cancelled"); require( members[proposal.applicant].jailed == 0, "proposal applicant must not be jailed" ); if ( proposal.tributeOffered > 0 && userTokenBalances[GUILD][proposal.tributeToken] == 0 ) { require( totalGuildBankTokens < MAX_TOKEN_GUILDBANK_COUNT, "cannot sponsor more tribute proposals for new tokens - guildbank is full" ); } // whitelist proposal if (proposal.flags[4]) { require( !tokenWhitelist[address(proposal.tributeToken)], "cannot already have whitelisted the token" ); require( !proposedToWhitelist[address(proposal.tributeToken)], "already proposed to whitelist" ); require( approvedTokens.length < MAX_TOKEN_WHITELIST_COUNT, "cannot sponsor more whitelist proposals" ); proposedToWhitelist[address(proposal.tributeToken)] = true; // guild kick proposal } else if (proposal.flags[5]) { require( !proposedToKick[proposal.applicant], "already proposed to kick" ); proposedToKick[proposal.applicant] = true; } // compute startingPeriod for proposal uint256 startingPeriod = max( getCurrentPeriod(), proposalQueue.length == 0 ? 0 : proposals[proposalQueue[proposalQueue.length - 1]] .startingPeriod ) + 1; proposal.startingPeriod = startingPeriod; address memberAddress = memberAddressByDelegateKey[msg.sender]; proposal.sponsor = memberAddress; proposal.flags[0] = true; // sponsored // append proposal to the queue proposalQueue.push(proposalId); emit SponsorProposal( msg.sender, memberAddress, proposalId, proposalQueue.length - 1, startingPeriod ); } // NOTE: In MolochV2 proposalIndex !== proposalId function submitVote(uint256 proposalIndex, uint8 uintVote) public nonReentrant onlyDelegate { address memberAddress = memberAddressByDelegateKey[msg.sender]; Member storage member = members[memberAddress]; require( proposalIndex < proposalQueue.length, "proposal does not exist" ); Proposal storage proposal = proposals[proposalQueue[proposalIndex]]; require(uintVote < 3, "must be less than 3"); Vote vote = Vote(uintVote); require( getCurrentPeriod() >= proposal.startingPeriod, "voting period has not started" ); require( !hasVotingPeriodExpired(proposal.startingPeriod), "proposal voting period has expired" ); require( voteHistory[proposalIndex][memberAddress] == Vote.Null, "member has already voted" ); require( vote == Vote.Yes || vote == Vote.No, "vote must be either Yes or No" ); voteHistory[proposalIndex][memberAddress] = vote; if (vote == Vote.Yes) { proposal.yesVotes = proposal.yesVotes + member.shares; // set highest index (latest) yes vote - must be processed for member to ragequit if (proposalIndex > member.highestIndexYesVote) { member.highestIndexYesVote = proposalIndex; } // set maximum of total shares encountered at a yes vote - used to bound dilution for yes voters if ( (totalShares + totalLoot) > proposal.maxTotalSharesAndLootAtYesVote ) { proposal.maxTotalSharesAndLootAtYesVote = totalShares + totalLoot; } } else if (vote == Vote.No) { proposal.noVotes = proposal.noVotes + member.shares; } // NOTE: subgraph indexes by proposalId not proposalIndex since proposalIndex isn't set untill it's been sponsored but proposal is created on submission emit SubmitVote( proposalQueue[proposalIndex], proposalIndex, msg.sender, memberAddress, uintVote ); } function processProposal(uint256 proposalIndex) public nonReentrant { _validateProposalForProcessing(proposalIndex); uint256 proposalId = proposalQueue[proposalIndex]; Proposal storage proposal = proposals[proposalId]; require( !proposal.flags[4] && !proposal.flags[5], "must be a standard proposal" ); proposal.flags[1] = true; // processed bool didPass = _didPass(proposalIndex); // Make the proposal fail if the new total number of shares and loot exceeds the limit if ( (totalShares + totalLoot + proposal.sharesRequested + proposal.lootRequested) > MAX_NUMBER_OF_SHARES_AND_LOOT ) { didPass = false; } // Make the proposal fail if it is requesting more tokens as payment than the available guild bank balance if ( proposal.paymentRequested > userTokenBalances[GUILD][proposal.paymentToken] ) { didPass = false; } // Make the proposal fail if it would result in too many tokens with non-zero balance in guild bank if ( proposal.tributeOffered > 0 && userTokenBalances[GUILD][proposal.tributeToken] == 0 && totalGuildBankTokens >= MAX_TOKEN_GUILDBANK_COUNT ) { didPass = false; } // PROPOSAL PASSED if (didPass) { proposal.flags[2] = true; // didPass _setSharesLoot( proposal.applicant, proposal.sharesRequested, proposal.lootRequested, true ); // if the proposal tribute is the first tokens of its kind to make it into the guild bank, increment total guild bank tokens if ( userTokenBalances[GUILD][proposal.tributeToken] == 0 && proposal.tributeOffered > 0 ) { totalGuildBankTokens += 1; } unsafeInternalTransfer( ESCROW, GUILD, proposal.tributeToken, proposal.tributeOffered ); unsafeInternalTransfer( GUILD, proposal.applicant, proposal.paymentToken, proposal.paymentRequested ); // if the proposal spends 100% of guild bank balance for a token, decrement total guild bank tokens if ( userTokenBalances[GUILD][proposal.paymentToken] == 0 && proposal.paymentRequested > 0 ) { totalGuildBankTokens -= 1; } // PROPOSAL FAILED } else { // return all tokens to the proposer (not the applicant, because funds come from proposer) unsafeInternalTransfer( ESCROW, proposal.proposer, proposal.tributeToken, proposal.tributeOffered ); } _returnDeposit(proposal.sponsor); emit ProcessProposal(proposalIndex, proposalId, didPass); } function processWhitelistProposal(uint256 proposalIndex) public nonReentrant { _validateProposalForProcessing(proposalIndex); uint256 proposalId = proposalQueue[proposalIndex]; Proposal storage proposal = proposals[proposalId]; require(proposal.flags[4], "must be a whitelist proposal"); proposal.flags[1] = true; // processed bool didPass = _didPass(proposalIndex); if (approvedTokens.length >= MAX_TOKEN_WHITELIST_COUNT) { didPass = false; } if (didPass) { proposal.flags[2] = true; // didPass tokenWhitelist[address(proposal.tributeToken)] = true; approvedTokens.push(proposal.tributeToken); } proposedToWhitelist[address(proposal.tributeToken)] = false; _returnDeposit(proposal.sponsor); emit ProcessWhitelistProposal(proposalIndex, proposalId, didPass); } function processGuildKickProposal(uint256 proposalIndex) public nonReentrant { _validateProposalForProcessing(proposalIndex); uint256 proposalId = proposalQueue[proposalIndex]; Proposal storage proposal = proposals[proposalId]; require(proposal.flags[5], "must be a guild kick proposal"); proposal.flags[1] = true; // processed bool didPass = _didPass(proposalIndex); if (didPass) { proposal.flags[2] = true; // didPass Member storage member = members[proposal.applicant]; member.jailed = proposalIndex; // transfer shares to loot member.loot = member.loot + member.shares; totalShares = totalShares - member.shares; totalLoot = totalLoot + member.shares; member.shares = 0; // revoke all shares } proposedToKick[proposal.applicant] = false; _returnDeposit(proposal.sponsor); emit ProcessGuildKickProposal(proposalIndex, proposalId, didPass); } function _didPass(uint256 proposalIndex) internal view returns (bool didPass) { Proposal memory proposal = proposals[proposalQueue[proposalIndex]]; didPass = proposal.yesVotes > proposal.noVotes; // Make the proposal fail if the dilutionBound is exceeded if ( (totalShares + totalLoot) * (dilutionBound) < proposal.maxTotalSharesAndLootAtYesVote ) { didPass = false; } // Make the proposal fail if the applicant is jailed // - for standard proposals, we don't want the applicant to get any shares/loot/payment // - for guild kick proposals, we should never be able to propose to kick a jailed member (or have two kick proposals active), so it doesn't matter if (members[proposal.applicant].jailed != 0) { didPass = false; } return didPass; } function _validateProposalForProcessing(uint256 proposalIndex) internal view { require( proposalIndex < proposalQueue.length, "proposal does not exist" ); Proposal memory proposal = proposals[proposalQueue[proposalIndex]]; require( getCurrentPeriod() >= (proposal.startingPeriod + votingPeriodLength + gracePeriodLength), "proposal is not ready to be processed" ); require( proposal.flags[1] == false, "proposal has already been processed" ); require( proposalIndex == 0 || proposals[proposalQueue[proposalIndex - 1]].flags[1], "previous proposal must be processed" ); } function _returnDeposit(address sponsor) internal { unsafeInternalTransfer( ESCROW, msg.sender, depositToken, processingReward ); unsafeInternalTransfer( ESCROW, sponsor, depositToken, proposalDeposit - processingReward ); } function ragequit(uint256 sharesToBurn, uint256 lootToBurn) public nonReentrant onlyMember { _ragequit(msg.sender, sharesToBurn, lootToBurn); } function _ragequit( address memberAddress, uint256 sharesToBurn, uint256 lootToBurn ) internal { uint256 initialTotalSharesAndLoot = totalShares + totalLoot; Member storage member = members[memberAddress]; require(member.shares >= sharesToBurn, "insufficient shares"); require(member.loot >= lootToBurn, "insufficient loot"); require( canRagequit(member.highestIndexYesVote), "cannot ragequit until highest index proposal member voted YES on is processed" ); uint256 sharesAndLootToBurn = sharesToBurn + lootToBurn; // burn shares and loot _setSharesLoot(memberAddress, sharesToBurn, lootToBurn, false); for (uint256 i = 0; i < approvedTokens.length; i++) { uint256 amountToRagequit = fairShare( userTokenBalances[GUILD][approvedTokens[i]], sharesAndLootToBurn, initialTotalSharesAndLoot ); if (amountToRagequit > 0) { // gas optimization to allow a higher maximum token limit // deliberately not using safemath here to keep overflows from preventing the function execution (which would break ragekicks) // if a token overflows, it is because the supply was artificially inflated to oblivion, so we probably don't care about it anyways userTokenBalances[GUILD][approvedTokens[i]] -= amountToRagequit; userTokenBalances[memberAddress][ approvedTokens[i] ] += amountToRagequit; } } emit Ragequit(memberAddress, sharesToBurn, lootToBurn); } function ragekick(address memberToKick) public nonReentrant { Member storage member = members[memberToKick]; require(member.jailed != 0, "member must be in jail"); require(member.loot > 0, "member must have some loot"); // note - should be impossible for jailed member to have shares require( canRagequit(member.highestIndexYesVote), "cannot ragequit until highest index proposal member voted YES on is processed" ); _ragequit(memberToKick, 0, member.loot); } function withdrawBalance(address token, uint256 amount) public nonReentrant { _withdrawBalance(token, amount); } function withdrawBalances( address[] memory tokens, uint256[] memory amounts, bool shouldWithdrawMax ) public nonReentrant { require( tokens.length == amounts.length, "tokens and amounts arrays must be matching lengths" ); for (uint256 i = 0; i < tokens.length; i++) { uint256 withdrawAmount = amounts[i]; if (shouldWithdrawMax) { // withdraw the maximum balance withdrawAmount = userTokenBalances[msg.sender][tokens[i]]; } _withdrawBalance(tokens[i], withdrawAmount); } } function _withdrawBalance(address token, uint256 amount) internal { require( userTokenBalances[msg.sender][token] >= amount, "insufficient balance" ); unsafeSubtractFromBalance(msg.sender, token, amount); require(IERC20(token).transfer(msg.sender, amount), "transfer failed"); emit Withdraw(msg.sender, token, amount); } function collectTokens(address token) public onlyDelegateOrShaman nonReentrant { uint256 amountToCollect = IERC20(token).balanceOf(address(this)) - userTokenBalances[TOTAL][token]; // only collect if 1) there are tokens to collect 2) token is whitelisted 3) token has non-zero balance require(amountToCollect > 0, "no tokens to collect"); require(tokenWhitelist[token], "token to collect must be whitelisted"); require( userTokenBalances[GUILD][token] > 0 || totalGuildBankTokens < MAX_TOKEN_GUILDBANK_COUNT, "token to collect must have non-zero guild bank balance" ); if (userTokenBalances[GUILD][token] == 0) { totalGuildBankTokens += 1; } unsafeAddToBalance(GUILD, token, amountToCollect); emit TokensCollected(token, amountToCollect); } // NOTE: requires that delegate key which sent the original proposal cancels, msg.sender == proposal.proposer function cancelProposal(uint256 proposalId) public nonReentrant { Proposal storage proposal = proposals[proposalId]; require(!proposal.flags[0], "proposal has already been sponsored"); require(!proposal.flags[3], "proposal has already been cancelled"); require( msg.sender == proposal.proposer, "solely the proposer can cancel" ); proposal.flags[3] = true; // cancelled unsafeInternalTransfer( ESCROW, proposal.proposer, proposal.tributeToken, proposal.tributeOffered ); emit CancelProposal(proposalId, msg.sender); } function updateDelegateKey(address newDelegateKey) public nonReentrant onlyShareholder { require(newDelegateKey != address(0), "newDelegateKey cannot be 0"); // skip checks if member is setting the delegate key to their member address if (newDelegateKey != msg.sender) { require( !members[newDelegateKey].exists, "cannot overwrite existing members" ); require( !members[memberAddressByDelegateKey[newDelegateKey]].exists, "cannot overwrite existing delegate keys" ); } Member storage member = members[msg.sender]; memberAddressByDelegateKey[member.delegateKey] = address(0); memberAddressByDelegateKey[newDelegateKey] = msg.sender; member.delegateKey = newDelegateKey; emit UpdateDelegateKey(msg.sender, newDelegateKey); } // can only ragequit if the latest proposal you voted YES on has been processed function canRagequit(uint256 highestIndexYesVote) public view returns (bool) { // TODO: fixed to allow ragequit before any proposals, write test if(proposalQueue.length == 0){ return true; } require( highestIndexYesVote < proposalQueue.length, "proposal does not exist" ); return proposals[proposalQueue[highestIndexYesVote]].flags[1]; } function hasVotingPeriodExpired(uint256 startingPeriod) public view returns (bool) { return getCurrentPeriod() >= (startingPeriod + votingPeriodLength); } /*************** GETTER FUNCTIONS ***************/ function max(uint256 x, uint256 y) internal pure returns (uint256) { return x >= y ? x : y; } function getCurrentPeriod() public view returns (uint256) { return (block.timestamp - summoningTime) / (periodDuration); } function getProposalQueueLength() public view returns (uint256) { return proposalQueue.length; } function getProposalFlags(uint256 proposalId) public view returns (bool[6] memory) { return proposals[proposalId].flags; } function getUserTokenBalance(address user, address token) public view returns (uint256) { return userTokenBalances[user][token]; } function getMemberProposalVote(address memberAddress, uint256 proposalIndex) public view returns (Vote) { require(members[memberAddress].exists, "member does not exist"); require( proposalIndex < proposalQueue.length, "proposal does not exist" ); return voteHistory[proposalIndex][memberAddress]; } function getTokenCount() public view returns (uint256) { return approvedTokens.length; } /*************** HELPER FUNCTIONS ***************/ function unsafeAddToBalance( address user, address token, uint256 amount ) internal { userTokenBalances[user][token] += amount; userTokenBalances[TOTAL][token] += amount; } function unsafeSubtractFromBalance( address user, address token, uint256 amount ) internal { userTokenBalances[user][token] -= amount; userTokenBalances[TOTAL][token] -= amount; } function unsafeInternalTransfer( address from, address to, address token, uint256 amount ) internal { unsafeSubtractFromBalance(from, token, amount); unsafeAddToBalance(to, token, amount); } function fairShare( uint256 balance, uint256 shares, uint256 _totalShares ) internal pure returns (uint256) { require(_totalShares != 0); if (balance == 0) { return 0; } uint256 prod = balance * shares; if (prod / balance == shares) { // no overflow in multiplication above? return prod / _totalShares; } return (balance / _totalShares) * shares; } } /* The MIT License (MIT) Copyright (c) 2018 Murray Software, LLC. 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 SOFTWARE. */ contract CloneFactory { // implementation of eip-1167 - see https://eips.ethereum.org/EIPS/eip-1167 function createClone(address target) internal returns (address result) { bytes20 targetBytes = bytes20(target); assembly { let clone := mload(0x40) mstore( clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000 ) mstore(add(clone, 0x14), targetBytes) mstore( add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000 ) result := create(0, clone, 0x37) } } } contract MolochSummoner is CloneFactory { address public template; mapping(uint256 => address) public daos; uint256 public daoIdx = 0; // Moloch private moloch; // moloch contract constructor(address _template) { template = _template; } event SummonComplete( address indexed moloch, address _summoner, address _shaman, address[] tokens, uint256 summoningTime, uint256 periodDuration, uint256 votingPeriodLength, uint256 gracePeriodLength, uint256 proposalDeposit, uint256 dilutionBound, uint256 processingReward ); function summonMoloch( address _summoner, address _shaman, address[] memory _approvedTokens, uint256 _periodDuration, uint256 _votingPeriodLength, uint256 _gracePeriodLength, uint256 _proposalDeposit, uint256 _dilutionBound, uint256 _processingReward ) public returns (address) { Moloch moloch = Moloch(createClone(template)); moloch.init( // _summoner, _shaman, _approvedTokens, _periodDuration, _votingPeriodLength, _gracePeriodLength, _proposalDeposit, _dilutionBound, _processingReward ); daoIdx = daoIdx + 1; daos[daoIdx] = address(moloch); emit SummonComplete( address(moloch), _summoner, _shaman, _approvedTokens, block.timestamp, _periodDuration, _votingPeriodLength, _gracePeriodLength, _proposalDeposit, _dilutionBound, _processingReward ); return address(moloch); } }
Make the proposal fail if the dilutionBound is exceeded Make the proposal fail if the applicant is jailed - for standard proposals, we don't want the applicant to get any shares/loot/payment - for guild kick proposals, we should never be able to propose to kick a jailed member (or have two kick proposals active), so it doesn't matter
function _didPass(uint256 proposalIndex) internal view returns (bool didPass) { Proposal memory proposal = proposals[proposalQueue[proposalIndex]]; didPass = proposal.yesVotes > proposal.noVotes; if ( (totalShares + totalLoot) * (dilutionBound) < proposal.maxTotalSharesAndLootAtYesVote ) { didPass = false; } if (members[proposal.applicant].jailed != 0) { didPass = false; } return didPass; }
32,977
[ 1, 6464, 326, 14708, 2321, 309, 326, 302, 330, 1421, 3499, 353, 12428, 4344, 326, 14708, 2321, 309, 326, 513, 1780, 970, 353, 525, 1708, 300, 364, 4529, 450, 22536, 16, 732, 2727, 1404, 2545, 326, 513, 1780, 970, 358, 336, 1281, 24123, 19, 383, 352, 19, 9261, 300, 364, 15488, 23228, 450, 22536, 16, 732, 1410, 5903, 506, 7752, 358, 450, 4150, 358, 23228, 279, 525, 1708, 3140, 261, 280, 1240, 2795, 23228, 450, 22536, 2695, 3631, 1427, 518, 3302, 1404, 15177, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 14044, 6433, 12, 11890, 5034, 14708, 1016, 13, 203, 3639, 2713, 203, 3639, 1476, 203, 3639, 1135, 261, 6430, 5061, 6433, 13, 203, 565, 288, 203, 3639, 19945, 3778, 14708, 273, 450, 22536, 63, 685, 8016, 3183, 63, 685, 8016, 1016, 13563, 31, 203, 203, 3639, 5061, 6433, 273, 14708, 18, 9707, 29637, 405, 14708, 18, 2135, 29637, 31, 203, 203, 3639, 309, 261, 203, 5411, 261, 4963, 24051, 397, 2078, 1504, 352, 13, 380, 261, 72, 330, 1421, 3499, 13, 411, 203, 5411, 14708, 18, 1896, 5269, 24051, 1876, 1504, 352, 861, 22352, 19338, 203, 3639, 262, 288, 203, 5411, 5061, 6433, 273, 629, 31, 203, 3639, 289, 203, 203, 3639, 309, 261, 7640, 63, 685, 8016, 18, 438, 1780, 970, 8009, 78, 1708, 480, 374, 13, 288, 203, 5411, 5061, 6433, 273, 629, 31, 203, 3639, 289, 203, 203, 3639, 327, 5061, 6433, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/3/0xDFa70558a8DBaaB073431e82AFBf682AD07091e9/sources/Student_Transcripts_flat.sol
this is the owner of the contract: The Student once the contract is deployed the constructor is call and assign the owner is assigned to the contract
{ string public FirstName; string private LastName; uint256 private StudentID; uint256 private courseCount = 0; uint256 public TranscriptCount = 0; address owner; constructor () { owner = msg.sender; } struct Course { uint256 ID; uint256 SchoolID; string SchoolName; string CourseName; string CourseNumber; string Grade; uint256 CreditForCourse; } struct Transcript { uint256 ID; uint256 SchoolID; string SchoolName; string Country; uint256 TotalCredits; uint256 TotalCourses; string GPA; } mapping(uint => Course) public courses; mapping(uint => Transcript) public transcripts; modifier onlyOwner () { require (msg.sender == owner); _; } function createOwner (string memory _firstName, string memory _lastName, uint256 _studentID) { FirstName = _firstName; LastName = _lastName; StudentID = _studentID; } function addCourse (string memory _courseName, string memory _courseNumber, string memory _grade, uint256 _credit) public { courses[courseCount] = Course(courseCount, 0,"", _courseName, _courseNumber, _grade, _credit); courseCount += 1; } function createTranscript ( uint256 _schoolID, string memory _schoolName, string memory _country, string memory _gpa ) public { transcripts[TranscriptCount] = Transcript(TranscriptCount, _schoolID, _schoolName, _country, 0, 0, _gpa); updateCources(_schoolID, _schoolName); transcripts[TranscriptCount].TotalCredits = Total_Credits_For_Transactions(_schoolID); transcripts[TranscriptCount].TotalCourses = Total_Courses_For_Transcript(_schoolID); TranscriptCount += 1; } function getFirstName()public view returns(string memory) { return FirstName; } function getLastName()public view returns(string memory) { return LastName; } function getStudentID()public view returns(uint256) { return StudentID; } function Total_Credits_For_Transactions(uint256 _schoolID) public view returns(uint256 totalValue) { uint256 i = 0; for(i; i<courseCount; i++) { if(courses[i].SchoolID == _schoolID) { totalValue = totalValue + courses[i].CreditForCourse; } } return totalValue; } function Total_Credits_For_Transactions(uint256 _schoolID) public view returns(uint256 totalValue) { uint256 i = 0; for(i; i<courseCount; i++) { if(courses[i].SchoolID == _schoolID) { totalValue = totalValue + courses[i].CreditForCourse; } } return totalValue; } function Total_Credits_For_Transactions(uint256 _schoolID) public view returns(uint256 totalValue) { uint256 i = 0; for(i; i<courseCount; i++) { if(courses[i].SchoolID == _schoolID) { totalValue = totalValue + courses[i].CreditForCourse; } } return totalValue; } function Total_Courses_For_Transcript(uint256 _schoolID) public view returns (uint256 totalValue) { uint256 i = 0; for(i; i<courseCount; i++) { if(courses[i].SchoolID == _schoolID) { totalValue++; } } return totalValue; } function Total_Courses_For_Transcript(uint256 _schoolID) public view returns (uint256 totalValue) { uint256 i = 0; for(i; i<courseCount; i++) { if(courses[i].SchoolID == _schoolID) { totalValue++; } } return totalValue; } function Total_Courses_For_Transcript(uint256 _schoolID) public view returns (uint256 totalValue) { uint256 i = 0; for(i; i<courseCount; i++) { if(courses[i].SchoolID == _schoolID) { totalValue++; } } return totalValue; } function Total_Credits_For_Student() public view returns(uint256 totalValue) { uint256 i = 0; for(i; i<courseCount; i++) { totalValue = totalValue + courses[i].CreditForCourse; } return totalValue; } function Total_Credits_For_Student() public view returns(uint256 totalValue) { uint256 i = 0; for(i; i<courseCount; i++) { totalValue = totalValue + courses[i].CreditForCourse; } return totalValue; } function getStudentsTotalCourses()public view returns(uint256) { return courseCount; } function updateCources(uint256 _schoolID, string memory _schoolName) internal { uint256 i = 0; for(i; i<courseCount; i++) { if(courses[i].SchoolID == 0) { courses[i].SchoolID = _schoolID; courses[i].SchoolName = _schoolName; } } } function updateCources(uint256 _schoolID, string memory _schoolName) internal { uint256 i = 0; for(i; i<courseCount; i++) { if(courses[i].SchoolID == 0) { courses[i].SchoolID = _schoolID; courses[i].SchoolName = _schoolName; } } } function updateCources(uint256 _schoolID, string memory _schoolName) internal { uint256 i = 0; for(i; i<courseCount; i++) { if(courses[i].SchoolID == 0) { courses[i].SchoolID = _schoolID; courses[i].SchoolName = _schoolName; } } } }
14,155,082
[ 1, 2211, 353, 326, 3410, 434, 326, 6835, 30, 1021, 934, 1100, 319, 3647, 326, 6835, 353, 19357, 326, 3885, 353, 745, 471, 2683, 326, 3410, 353, 6958, 358, 326, 6835, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 95, 203, 565, 533, 1071, 5783, 461, 31, 203, 565, 533, 3238, 6825, 461, 31, 203, 565, 2254, 5034, 3238, 934, 1100, 319, 734, 31, 203, 565, 2254, 5034, 3238, 4362, 1380, 273, 374, 31, 203, 565, 2254, 5034, 1071, 2604, 9118, 1380, 273, 374, 31, 203, 377, 203, 565, 1758, 3410, 31, 203, 27699, 565, 3885, 1832, 7010, 203, 203, 565, 288, 203, 3639, 3410, 273, 1234, 18, 15330, 31, 203, 540, 203, 565, 289, 203, 27699, 377, 1958, 385, 3117, 203, 377, 288, 203, 540, 2254, 5034, 1599, 31, 203, 540, 2254, 5034, 348, 343, 1371, 734, 31, 203, 540, 533, 348, 343, 1371, 461, 31, 203, 540, 533, 385, 3117, 461, 31, 203, 540, 533, 385, 3117, 1854, 31, 203, 540, 533, 10812, 323, 31, 203, 540, 2254, 5034, 30354, 1290, 39, 3117, 31, 203, 377, 289, 203, 1377, 203, 377, 1958, 2604, 9118, 203, 377, 288, 203, 540, 2254, 5034, 1599, 31, 203, 540, 2254, 5034, 348, 343, 1371, 734, 31, 203, 540, 533, 348, 343, 1371, 461, 31, 203, 540, 533, 19394, 31, 203, 540, 2254, 5034, 10710, 24201, 1282, 31, 203, 540, 2254, 5034, 10710, 39, 10692, 31, 203, 540, 533, 611, 4066, 31, 203, 377, 289, 203, 377, 203, 377, 203, 377, 203, 377, 203, 565, 2874, 12, 11890, 516, 385, 3117, 13, 1071, 17224, 31, 203, 565, 2874, 12, 11890, 516, 2604, 9118, 13, 1071, 906, 28230, 31, 203, 565, 9606, 1338, 5541, 1832, 203, 565, 288, 203, 3639, 2583, 261, 3576, 18, 15330, 422, 3410, 2 ]
pragma solidity 0.6.6; import "../IKyberMatchingEngine.sol"; import "./IKyberRateHelper.sol"; import "../IKyberDao.sol"; import "../IKyberStorage.sol"; import "../IKyberReserve.sol"; import "../utils/Utils5.sol"; import "../utils/WithdrawableNoModifiers.sol"; contract KyberRateHelper is IKyberRateHelper, WithdrawableNoModifiers, Utils5 { uint256 public constant DEFAULT_SPREAD_QUERY_AMOUNT_WEI = 10 ether; uint256 public constant DEFAULT_SLIPPAGE_QUERY_BASE_AMOUNT_WEI = 0.01 ether; uint256 public constant DEFAULT_SLIPPAGE_QUERY_AMOUNT_WEI = 10 ether; uint256 public constant DEFAULT_RATE_QUERY_AMOUNT_WEI = 1 ether; IKyberDao public kyberDao; IKyberStorage public kyberStorage; //reserves are queried directly bytes32[] public reserveIds; constructor(address _admin) public WithdrawableNoModifiers(_admin) { /* empty body */ } event KyberDaoContractSet(IKyberDao kyberDao); event KyberStorageSet(IKyberStorage kyberStorage); event AddKyberReserve(bytes32 reserveId, bool add); function setContracts( IKyberDao _kyberDao, IKyberStorage _kyberStorage ) public { onlyAdmin(); require(_kyberDao != IKyberDao(0), "kyberDao 0"); require(_kyberStorage != IKyberStorage(0), "kyberStorage 0"); if (kyberDao != _kyberDao) { kyberDao = _kyberDao; emit KyberDaoContractSet(_kyberDao); } if (kyberStorage != _kyberStorage) { kyberStorage = _kyberStorage; emit KyberStorageSet(_kyberStorage); } } function addReserve(bytes32 reserveId) public { onlyAdmin(); require(reserveId != bytes32(0), "reserve 0"); reserveIds.push(reserveId); emit AddKyberReserve(reserveId, true); } function removeReserve(bytes32 reserveId) public { onlyAdmin(); for (uint256 i = 0; i < reserveIds.length; i++) { if (reserveIds[i] == reserveId) { reserveIds[i] = reserveIds[reserveIds.length - 1]; reserveIds.pop(); emit AddKyberReserve(reserveId, false); break; } } } function getPricesForToken( IERC20 token, uint256 optionalBuyAmountWei, uint256 optionalSellAmountTwei ) public view override returns ( bytes32[] memory buyReserves, uint256[] memory buyRates, bytes32[] memory sellReserves, uint256[] memory sellRates ) { return getRatesForTokenWithCustomFee(token, optionalBuyAmountWei, optionalSellAmountTwei, 0); } /// @dev function to cover backward compatible with old network interface /// @dev get rate from eth to token, use the best token amount to get rate from token to eth /// @param token Token to get rate /// @param optionalAmountWei Eth amount to get rate (default: 0) function getReservesRates(IERC20 token, uint256 optionalAmountWei) public override view returns ( bytes32[] memory buyReserves, uint256[] memory buyRates, bytes32[] memory sellReserves, uint256[] memory sellRates ) { (uint256 networkFeeBps, ) = kyberDao.getLatestNetworkFeeData(); uint256 buyAmountWei = optionalAmountWei > 0 ? optionalAmountWei : DEFAULT_RATE_QUERY_AMOUNT_WEI; (buyReserves, buyRates) = getBuyInfo(token, buyAmountWei, networkFeeBps); uint256 bestRate = 0; for (uint256 i = 0; i < buyRates.length; i++) { if (buyRates[i] > bestRate) { bestRate = buyRates[i]; } } if (bestRate == 0) { return (buyReserves, buyRates, sellReserves, sellRates); } uint256 sellAmountTwei = calcDstQty(buyAmountWei, ETH_DECIMALS, getDecimals(token), bestRate); (sellReserves, sellRates) = getSellInfo(token, sellAmountTwei, networkFeeBps); } function getReservesRatesWithConfigReserves(IERC20 token, uint256 optionalAmountWei) public view returns ( bytes32[] memory reserves, uint256[] memory buyRates, uint256[] memory sellRates ) { (uint256 networkFeeBps, ) = kyberDao.getLatestNetworkFeeData(); uint256 buyAmountWei = optionalAmountWei > 0 ? optionalAmountWei : DEFAULT_RATE_QUERY_AMOUNT_WEI; reserves = reserveIds; buyRates = getBuyRate(token, buyAmountWei, networkFeeBps, reserves); uint256 bestRate = 0; for (uint256 i = 0; i < buyRates.length; i++) { if (buyRates[i] > bestRate) { bestRate = buyRates[i]; } } if (bestRate == 0) { sellRates = new uint256[](reserves.length); return (reserves, buyRates, sellRates); } uint256 sellAmountTwei = calcDstQty(buyAmountWei, ETH_DECIMALS, getDecimals(token), bestRate); sellRates = getSellRate(token, sellAmountTwei, networkFeeBps, reserves); } function getRatesForToken( IERC20 token, uint256 optionalBuyAmountWei, uint256 optionalSellAmountTwei ) public view override returns ( bytes32[] memory buyReserves, uint256[] memory buyRates, bytes32[] memory sellReserves, uint256[] memory sellRates ) { (uint256 feeBps, ) = kyberDao.getLatestNetworkFeeData(); return getRatesForTokenWithCustomFee(token, optionalBuyAmountWei, optionalSellAmountTwei, feeBps); } function getRatesForTokenWithCustomFee( IERC20 token, uint256 optionalBuyAmountWei, uint256 optionalSellAmountTwei, uint256 networkFeeBps ) public view override returns ( bytes32[] memory buyReserves, uint256[] memory buyRates, bytes32[] memory sellReserves, uint256[] memory sellRates ) { uint256 buyAmountWei = optionalBuyAmountWei > 0 ? optionalBuyAmountWei : DEFAULT_RATE_QUERY_AMOUNT_WEI; (buyReserves, buyRates) = getBuyInfo(token, buyAmountWei, networkFeeBps); uint256 sellAmountTwei = optionalSellAmountTwei; if (sellAmountTwei == 0) { uint256 bestRate = 0; for (uint256 i = 0; i < buyRates.length; i++) { if (buyRates[i] > bestRate) { bestRate = buyRates[i]; } } if (bestRate != 0) { sellAmountTwei = calcDstQty(buyAmountWei, ETH_DECIMALS, getDecimals(token), bestRate); } } (sellReserves, sellRates) = getSellInfo(token, sellAmountTwei, networkFeeBps); } function getBuyInfo( IERC20 token, uint256 buyAmountWei, uint256 networkFeeBps ) internal view returns (bytes32[] memory buyReserves, uint256[] memory buyRates) { buyReserves = kyberStorage.getReserveIdsPerTokenDest(token); buyRates = getBuyRate(token, buyAmountWei, networkFeeBps, buyReserves); } function getBuyRate( IERC20 token, uint256 buyAmountWei, uint256 networkFeeBps, bytes32[] memory buyReserves ) internal view returns (uint256[] memory buyRates) { bool[] memory isFeeAccountedFlags = kyberStorage.getFeeAccountedData(buyReserves); address[] memory buyReserveAddresses = kyberStorage.getReserveAddressesFromIds( buyReserves ); buyRates = new uint256[](buyReserves.length); uint256 buyAmountWithFee = buyAmountWei - ((buyAmountWei * networkFeeBps) / BPS); for (uint256 i = 0; i < buyReserves.length; i++) { if (networkFeeBps == 0 || !isFeeAccountedFlags[i]) { buyRates[i] = IKyberReserve(buyReserveAddresses[i]).getConversionRate( ETH_TOKEN_ADDRESS, token, buyAmountWei, block.number ); continue; } buyRates[i] = IKyberReserve(buyReserveAddresses[i]).getConversionRate( ETH_TOKEN_ADDRESS, token, buyAmountWithFee, block.number ); uint256 destAmount = calcDstQty( buyAmountWithFee, ETH_DECIMALS, getDecimals(token), buyRates[i] ); //use amount instead of ethSrcAmount to account for network fee buyRates[i] = calcRateFromQty(buyAmountWei, destAmount, ETH_DECIMALS, getDecimals(token)); } } function getSellInfo( IERC20 token, uint256 sellAmountTwei, uint256 networkFeeBps ) internal view returns (bytes32[] memory sellReserves, uint256[] memory sellRates) { sellReserves = kyberStorage.getReserveIdsPerTokenSrc(token); sellRates = getSellRate(token, sellAmountTwei, networkFeeBps, sellReserves); } function getSellRate( IERC20 token, uint256 sellAmountTwei, uint256 networkFeeBps, bytes32[] memory sellReserves ) internal view returns (uint256[] memory sellRates) { bool[] memory isFeeAccountedFlags = kyberStorage.getFeeAccountedData(sellReserves); address[] memory sellReserveAddresses = kyberStorage.getReserveAddressesFromIds( sellReserves ); sellRates = new uint256[](sellReserves.length); for (uint256 i = 0; i < sellReserves.length; i++) { sellRates[i] = IKyberReserve(sellReserveAddresses[i]).getConversionRate( token, ETH_TOKEN_ADDRESS, sellAmountTwei, block.number ); if (networkFeeBps == 0 || !isFeeAccountedFlags[i]) { continue; } uint256 destAmount = calcDstQty( sellAmountTwei, getDecimals(token), ETH_DECIMALS, sellRates[i] ); destAmount -= (networkFeeBps * destAmount) / BPS; sellRates[i] = calcRateFromQty( sellAmountTwei, destAmount, getDecimals(token), ETH_DECIMALS ); } } function getSpreadInfo(IERC20 token, uint256 optionalAmountWei) public view override returns (bytes32[] memory reserves, int256[] memory spreads) { uint256 amountWei = optionalAmountWei > 0 ? optionalAmountWei : DEFAULT_SPREAD_QUERY_AMOUNT_WEI; ( bytes32[] memory buyReserves, uint256[] memory buyRates, bytes32[] memory sellReserves, uint256[] memory sellRates ) = getReservesRates(token, amountWei); // map pair of buyRate and sellRate from the same Reserve uint256[] memory validReserves = new uint256[](buyReserves.length); uint256[] memory revertReserveIndex = new uint256[](buyReserves.length); uint256 validReserveSize = 0; for (uint256 i = 0; i < buyRates.length; i++) { for (uint256 j = 0; j < sellRates.length; j++) { if (sellReserves[j] == buyReserves[i]) { revertReserveIndex[i] = j; validReserves[validReserveSize] = i; validReserveSize++; break; } } } reserves = new bytes32[](validReserveSize); spreads = new int256[](validReserveSize); for (uint256 i = 0; i < validReserveSize; i++) { uint256 reserveIndex = validReserves[i]; reserves[i] = buyReserves[reserveIndex]; spreads[i] = calcSpreadInBps( buyRates[reserveIndex], sellRates[revertReserveIndex[reserveIndex]] ); } } function getSpreadInfoWithConfigReserves(IERC20 token, uint256 optionalAmountWei) public view returns (bytes32[] memory reserves, int256[] memory spreads) { uint256[] memory buyRates; uint256[] memory sellRates; uint256 amountWei = optionalAmountWei > 0 ? optionalAmountWei : DEFAULT_SPREAD_QUERY_AMOUNT_WEI; (reserves, buyRates, sellRates) = getReservesRatesWithConfigReserves(token, amountWei); spreads = new int256[](reserves.length); for (uint256 i = 0; i < buyRates.length; i++) { spreads[i] = calcSpreadInBps(buyRates[i], sellRates[i]); } } function getSlippageRateInfo( IERC20 token, uint256 optionalAmountWei, uint256 optionalSlippageAmount ) public view override returns ( bytes32[] memory buyReserves, int256[] memory buySlippageRateBps, bytes32[] memory sellReserves, int256[] memory sellSlippageRateBps ) { uint256 baseAmount = optionalAmountWei > 0 ? optionalAmountWei : DEFAULT_SLIPPAGE_QUERY_BASE_AMOUNT_WEI; uint256[] memory baseBuyRates; uint256[] memory baseSellRates; (buyReserves, baseBuyRates, sellReserves, baseSellRates) = getReservesRates( token, baseAmount ); uint256 slippageAmount = optionalSlippageAmount > 0 ? optionalSlippageAmount : DEFAULT_SLIPPAGE_QUERY_AMOUNT_WEI; uint256[] memory slippageBuyRates; uint256[] memory slippageSellRates; (, slippageBuyRates, , slippageSellRates) = getReservesRates(token, slippageAmount); // no rate exists for slippageAmount but rate exists for baseAmount if (slippageSellRates.length == 0 && baseSellRates.length != 0) { slippageSellRates = new uint256[](baseSellRates.length); } assert(slippageSellRates.length == baseSellRates.length); assert(slippageBuyRates.length == baseBuyRates.length); buySlippageRateBps = new int256[](buyReserves.length); for (uint256 i = 0; i < buyReserves.length; i++) { buySlippageRateBps[i] = calcSlippageRateInBps(baseBuyRates[i], slippageBuyRates[i], true); } sellSlippageRateBps = new int256[](sellReserves.length); for (uint256 i = 0; i < sellReserves.length; i++) { sellSlippageRateBps[i] = calcSlippageRateInBps(baseSellRates[i], slippageSellRates[i], false); } } function getSlippageRateInfoWithConfigReserves( IERC20 token, uint256 optionalAmountWei, uint256 optionalSlippageAmount ) public view returns ( bytes32[] memory reserves, int256[] memory buySlippageRateBps, int256[] memory sellSlippageRateBps ) { uint256 baseAmount = optionalAmountWei > 0 ? optionalAmountWei : DEFAULT_SLIPPAGE_QUERY_BASE_AMOUNT_WEI; uint256[] memory baseBuyRates; uint256[] memory baseSellRates; (reserves, baseBuyRates, baseSellRates) = getReservesRatesWithConfigReserves( token, baseAmount ); uint256 slippageAmount = optionalSlippageAmount > 0 ? optionalSlippageAmount : DEFAULT_SLIPPAGE_QUERY_AMOUNT_WEI; uint256[] memory slippageBuyRates; uint256[] memory slippageSellRates; (, slippageBuyRates, slippageSellRates) = getReservesRatesWithConfigReserves( token, slippageAmount ); assert(slippageSellRates.length == baseSellRates.length); assert(slippageBuyRates.length == baseBuyRates.length); buySlippageRateBps = new int256[](baseBuyRates.length); for (uint256 i = 0; i < baseBuyRates.length; i++) { buySlippageRateBps[i] = calcSlippageRateInBps(baseBuyRates[i], slippageBuyRates[i], true); } sellSlippageRateBps = new int256[](baseSellRates.length); for (uint256 i = 0; i < baseSellRates.length; i++) { sellSlippageRateBps[i] = calcSlippageRateInBps(baseSellRates[i], slippageSellRates[i], false); } } /// @dev if sellRate == 0 return 2 * BPS (max value of spread) /// @dev if buyRate ** sellRate >= 10 ** 36 (negative spread) return 0 /// @dev spread can be from -2 * BPS to 2 * BPS function calcSpreadInBps(uint256 buyRate, uint256 sellRate) internal pure returns (int256) { if (buyRate == 0) { return 2 * int256(BPS); } int256 reversedBuyRate = int256(PRECISION**2 / buyRate); int256 sellRateInt256 = int256(sellRate); return (2 * int256(BPS) * (reversedBuyRate - sellRateInt256)) / (reversedBuyRate + sellRateInt256); } /// @dev if baseRate == 0 return -1 /// @dev if slippageRate == 0 return BPS /// @dev if baseRate < slippageRate return 0 function calcSlippageRateInBps( uint256 baseRate, uint256 slippageRate, bool isBuy ) internal pure returns (int256) { if (baseRate == 0) { return -1; } if (slippageRate == 0) { return int256(BPS); } if (slippageRate > baseRate) { return 0; } if (isBuy) { uint256 reversedBaseRate = PRECISION**2 / baseRate; uint256 reversedSlippageRate = PRECISION**2 / slippageRate; return int256((BPS * (reversedSlippageRate - reversedBaseRate)) / reversedBaseRate); } else { return int256((BPS * (baseRate - slippageRate)) / baseRate); } } }
no rate exists for slippageAmount but rate exists for baseAmount
function getSlippageRateInfo( IERC20 token, uint256 optionalAmountWei, uint256 optionalSlippageAmount ) public view override returns ( bytes32[] memory buyReserves, int256[] memory buySlippageRateBps, bytes32[] memory sellReserves, int256[] memory sellSlippageRateBps ) { uint256 baseAmount = optionalAmountWei > 0 ? optionalAmountWei : DEFAULT_SLIPPAGE_QUERY_BASE_AMOUNT_WEI; uint256[] memory baseBuyRates; uint256[] memory baseSellRates; (buyReserves, baseBuyRates, sellReserves, baseSellRates) = getReservesRates( token, baseAmount ); uint256 slippageAmount = optionalSlippageAmount > 0 ? optionalSlippageAmount : DEFAULT_SLIPPAGE_QUERY_AMOUNT_WEI; uint256[] memory slippageBuyRates; uint256[] memory slippageSellRates; (, slippageBuyRates, , slippageSellRates) = getReservesRates(token, slippageAmount); if (slippageSellRates.length == 0 && baseSellRates.length != 0) { slippageSellRates = new uint256[](baseSellRates.length); } assert(slippageSellRates.length == baseSellRates.length); assert(slippageBuyRates.length == baseBuyRates.length); buySlippageRateBps = new int256[](buyReserves.length); for (uint256 i = 0; i < buyReserves.length; i++) { buySlippageRateBps[i] = calcSlippageRateInBps(baseBuyRates[i], slippageBuyRates[i], true); } sellSlippageRateBps = new int256[](sellReserves.length); for (uint256 i = 0; i < sellReserves.length; i++) { sellSlippageRateBps[i] = calcSlippageRateInBps(baseSellRates[i], slippageSellRates[i], false); } }
12,618,877
[ 1, 2135, 4993, 1704, 364, 272, 3169, 2433, 6275, 1496, 4993, 1704, 364, 1026, 6275, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1322, 3169, 2433, 4727, 966, 12, 203, 3639, 467, 654, 39, 3462, 1147, 16, 203, 3639, 2254, 5034, 3129, 6275, 3218, 77, 16, 203, 3639, 2254, 5034, 3129, 55, 3169, 2433, 6275, 203, 565, 262, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 3849, 203, 3639, 1135, 261, 203, 5411, 1731, 1578, 8526, 3778, 30143, 607, 264, 3324, 16, 203, 5411, 509, 5034, 8526, 3778, 30143, 55, 3169, 2433, 4727, 38, 1121, 16, 203, 5411, 1731, 1578, 8526, 3778, 357, 80, 607, 264, 3324, 16, 203, 5411, 509, 5034, 8526, 3778, 357, 80, 55, 3169, 2433, 4727, 38, 1121, 203, 3639, 262, 203, 565, 288, 203, 3639, 2254, 5034, 1026, 6275, 273, 3129, 6275, 3218, 77, 405, 374, 692, 3129, 6275, 3218, 77, 294, 3331, 67, 55, 2053, 6584, 2833, 67, 10753, 67, 8369, 67, 2192, 51, 5321, 67, 6950, 45, 31, 203, 3639, 2254, 5034, 8526, 3778, 1026, 38, 9835, 20836, 31, 203, 3639, 2254, 5034, 8526, 3778, 1026, 55, 1165, 20836, 31, 203, 3639, 261, 70, 9835, 607, 264, 3324, 16, 1026, 38, 9835, 20836, 16, 357, 80, 607, 264, 3324, 16, 1026, 55, 1165, 20836, 13, 273, 31792, 264, 3324, 20836, 12, 203, 5411, 1147, 16, 203, 5411, 1026, 6275, 203, 3639, 11272, 203, 3639, 2254, 5034, 272, 3169, 2433, 6275, 273, 3129, 55, 3169, 2433, 6275, 405, 374, 203, 5411, 692, 3129, 55, 3169, 2433, 6275, 203, 5411, 294, 3331, 67, 55, 2053, 6584, 2833, 67, 10753, 67, 2192, 51, 5321, 67, 6950, 45, 31, 203, 3639, 2254, 2 ]
pragma solidity >=0.5.0; import "./ContractManager.sol"; import "./Authentication.sol"; /// @title Business Owner contract BusinessOwner { struct businessOwner { bytes32 businessName; bytes32 location; bytes32 VATNumber; bytes32 CE; } ContractManager manager; address[] private registeredBusinessOwners; mapping(address => businessOwner) private businessOwners; /** * @dev Sets the correct instance of ContractManager so that the contract may be able to call functions from other * contracts * @param _manager The address of the instance of ContractManager */ constructor(ContractManager _manager) public { manager = _manager; } /** * @dev Checks if the given user is a registered business owner * @param _user The address of the user to check */ modifier onlyBusinessOwner(address _user) { require(!(businessOwners[_user].CE == 0x0), "Not a business owner!"); _; } /** * @dev Checks if the given user is not registered on the platform * @param _user The address of the user to check */ modifier onlyNotRegistered(address _user) { require(uint(Authentication(manager.getAuthenticationContract()).isRegistered(_user)) == 0, "Already registered"); _; } /** * @dev Registers the user who calls this function as a business owner * @param _businessName The name of the business to register * @param _location The location of the business to register * @param _VATNumber The VAT number of the business to register * @param _CE The certified e-mail of the business to register */ function registerBusinessOwner (bytes32 _businessName, bytes32 _location, bytes32 _VATNumber, bytes32 _CE) public onlyNotRegistered(msg.sender) { businessOwners[msg.sender].businessName = _businessName; businessOwners[msg.sender].location = _location; businessOwners[msg.sender].VATNumber = _VATNumber; businessOwners[msg.sender].CE = _CE; registeredBusinessOwners.push(msg.sender); } /** * @dev Returns the data of a specific user if it's a registered business owner * @param _user The address of the business owner whose data to return */ function login(address _user) public view returns(bytes32, bytes32, bytes32, bytes32) { return (businessOwners[_user].businessName, businessOwners[_user].location, businessOwners[_user].VATNumber, businessOwners[_user].CE); } /** * @dev Returns a dynamic array containing all registered business owners' addresses */ function getAllBusinessOwners() public view returns(address[] memory) { return registeredBusinessOwners; } }
* @dev Checks if the given user is a registered business owner @param _user The address of the user to check/
modifier onlyBusinessOwner(address _user) { require(!(businessOwners[_user].CE == 0x0), "Not a business owner!"); _; }
12,897,676
[ 1, 4081, 309, 326, 864, 729, 353, 279, 4104, 13160, 3410, 225, 389, 1355, 1021, 1758, 434, 326, 729, 358, 866, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 9606, 1338, 13423, 5541, 12, 2867, 389, 1355, 13, 288, 203, 3639, 2583, 12, 5, 12, 24510, 5460, 414, 63, 67, 1355, 8009, 1441, 422, 374, 92, 20, 3631, 315, 1248, 279, 13160, 3410, 4442, 1769, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./nTokenMintAction.sol"; import "../../internal/markets/Market.sol"; import "../../internal/markets/CashGroup.sol"; import "../../internal/markets/AssetRate.sol"; import "../../internal/balances/BalanceHandler.sol"; import "../../internal/portfolio/PortfolioHandler.sol"; import "../../internal/settlement/SettlePortfolioAssets.sol"; import "../../internal/settlement/SettleBitmapAssets.sol"; import "../../internal/nToken/nTokenHandler.sol"; import "../../math/SafeInt256.sol"; import "../../math/Bitmap.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; /// @notice Initialize markets is called once every quarter to setup the new markets. Only the nToken account /// can initialize markets, and this method will be called on behalf of that account. In this action /// the following will occur: /// - nToken Liquidity Tokens will be settled /// - Any ifCash assets will be settled /// - If nToken liquidity tokens are settled with negative net ifCash, enough cash will be withheld at the PV /// to purchase offsetting positions /// - fCash positions are written to storage /// - For each market, calculate the proportion of fCash to cash given: /// - previous oracle rates /// - rate anchor set by governance /// - percent of cash to deposit into the market set by governance /// - Set new markets and add liquidity tokens to portfolio library InitializeMarketsAction { using Bitmap for bytes32; using SafeMath for uint256; using SafeInt256 for int256; using PortfolioHandler for PortfolioState; using Market for MarketParameters; using BalanceHandler for BalanceState; using CashGroup for CashGroupParameters; using AssetRate for AssetRateParameters; using AccountContextHandler for AccountContext; using nTokenHandler for nTokenPortfolio; event MarketsInitialized(uint16 currencyId); event SweepCashIntoMarkets(uint16 currencyId, int256 cashIntoMarkets); struct GovernanceParameters { int256[] depositShares; int256[] leverageThresholds; int256[] annualizedAnchorRates; int256[] proportions; } function _getGovernanceParameters(uint256 currencyId, uint256 maxMarketIndex) private view returns (GovernanceParameters memory) { GovernanceParameters memory params; (params.depositShares, params.leverageThresholds) = nTokenHandler.getDepositParameters( currencyId, maxMarketIndex ); (params.annualizedAnchorRates, params.proportions) = nTokenHandler.getInitializationParameters( currencyId, maxMarketIndex ); return params; } function _settleNTokenPortfolio(nTokenPortfolio memory nToken, uint256 blockTime) private { // nToken never has idiosyncratic cash between 90 day intervals but since it also has a // bitmap fCash assets. We don't set the pointer to the settlement date of the liquidity // tokens (1 quarter away), instead we set it to the current block time. This is a bit // esoteric but will ensure that ifCash is never improperly settled. // If lastInitializedTime == reference time then this will fail, that is the correct // behavior since initialization begins at lastInitializedTime. That means that markets // cannot be re-initialized during a single block (this is the correct behavior). If // lastInitializedTime >= reference time then the markets have already been initialized // for the quarter. uint256 referenceTime = DateTime.getReferenceTime(blockTime); require(nToken.lastInitializedTime < referenceTime, "IM: invalid time"); { // Settles liquidity token balances and portfolio state now contains the net fCash amounts SettleAmount[] memory settleAmount = SettlePortfolioAssets.settlePortfolio(nToken.portfolioState, blockTime); nToken.cashBalance = nToken.cashBalance.add(settleAmount[0].netCashChange); } (int256 settledAssetCash, uint256 blockTimeUTC0) = SettleBitmapAssets.settleBitmappedCashGroup( nToken.tokenAddress, nToken.cashGroup.currencyId, nToken.lastInitializedTime, blockTime ); nToken.cashBalance = nToken.cashBalance.add(settledAssetCash); // The ifCashBitmap has been updated to reference this new settlement time require(blockTimeUTC0 <= type(uint40).max); nToken.lastInitializedTime = uint40(blockTimeUTC0); } /// @notice Special method to get previous markets, normal usage would not reference previous markets /// in this way function _getPreviousMarkets( uint256 currencyId, uint256 blockTime, nTokenPortfolio memory nToken, MarketParameters[] memory previousMarkets ) private view { uint256 rateOracleTimeWindow = nToken.cashGroup.getRateOracleTimeWindow(); // This will reference the previous settlement date to get the previous markets uint256 settlementDate = DateTime.getReferenceTime(blockTime); // Assume that assets are stored in order and include all assets of the previous market // set. This will account for the potential that markets.length is greater than the previous // markets when the maxMarketIndex is increased (increasing the overall number of markets). // We don't fetch the 3 month market (i = 0) because it has settled and will not be used for // the subsequent calculations. Since nTokens never allow liquidity to go to zero then we know // there is always a matching token for each market. for (uint256 i = 1; i < nToken.portfolioState.storedAssets.length; i++) { previousMarkets[i].loadMarketWithSettlementDate( currencyId, // These assets will reference the previous liquidity tokens nToken.portfolioState.storedAssets[i].maturity, blockTime, // No liquidity tokens required for this process false, rateOracleTimeWindow, settlementDate ); } } /// @notice Check the net fCash assets set by the portfolio and withhold cash to account for /// the PV of negative ifCash. Also sets the ifCash assets into the nToken mapping. function _withholdAndSetfCashAssets( nTokenPortfolio memory nToken, MarketParameters[] memory previousMarkets, uint256 currencyId, uint256 blockTime ) private returns (int256) { // Residual fcash must be put into the ifCash bitmap from the portfolio, skip the 3 month // liquidity token since there is no residual fCash for that maturity, it always settles to cash. for (uint256 i = 1; i < nToken.portfolioState.storedAssets.length; i++) { PortfolioAsset memory asset = nToken.portfolioState.storedAssets[i]; // Defensive check to ensure that everything is an fcash asset, all liquidity tokens after // the three month should have been settled to fCash at this point. require(asset.assetType == Constants.FCASH_ASSET_TYPE); BitmapAssetsHandler.addifCashAsset( nToken.tokenAddress, currencyId, asset.maturity, nToken.lastInitializedTime, asset.notional ); // Do not have fCash assets stored in the portfolio nToken.portfolioState.deleteAsset(i); } // Recalculate what the withholdings are if there are any ifCash assets remaining return _getNTokenNegativefCashWithholding(nToken, previousMarkets, blockTime); } /// @notice If a nToken incurs a negative fCash residual as a result of lending, this means /// that we are going to need to withhold some amount of cash so that market makers can purchase and /// clear the debts off the balance sheet. function _getNTokenNegativefCashWithholding( nTokenPortfolio memory nToken, MarketParameters[] memory previousMarkets, uint256 blockTime ) internal view returns (int256 totalCashWithholding) { bytes32 assetsBitmap = BitmapAssetsHandler.getAssetsBitmap(nToken.tokenAddress, nToken.cashGroup.currencyId); // This buffer is denominated in rate precision with 10 basis point increments. It is used to shift the // withholding rate to ensure that sufficient cash is withheld for negative fCash balances. uint256 oracleRateBuffer = uint256(uint8(nToken.parameters[Constants.CASH_WITHHOLDING_BUFFER])) * Constants.TEN_BASIS_POINTS; // If previousMarkets are supplied, then we are in initialize markets and we want to get the oracleRate // from the perspective of the previous tRef (represented by blockTime - QUARTER). The reason is that the // oracleRates for the current markets have not been set yet (we are in the process of calculating them // in this contract). In the other case, we are in sweepCashIntoMarkets and we can use the current block time. uint256 oracleRateBlockTime = previousMarkets.length == 0 ? blockTime : blockTime.sub(Constants.QUARTER); uint256 bitNum = assetsBitmap.getNextBitNum(); while (bitNum != 0) { // lastInitializedTime is now the reference point for all ifCash bitmap uint256 maturity = DateTime.getMaturityFromBitNum(nToken.lastInitializedTime, bitNum); bool isValidMarket = DateTime.isValidMarketMaturity( nToken.cashGroup.maxMarketIndex, maturity, blockTime ); // Only apply withholding for idiosyncratic fCash if (!isValidMarket) { int256 notional = BitmapAssetsHandler.getifCashNotional( nToken.tokenAddress, nToken.cashGroup.currencyId, maturity ); // Withholding only applies for negative cash balances if (notional < 0) { // Oracle rates are calculated from the perspective of the previousMarkets during initialize // markets here. It is possible that these oracle rates do not equal the oracle rates when we // exit this method, this can happen if the nToken is above its leverage threshold. In that case // this oracleRate will be higher than what we have when we exit, causing the nToken to withhold // less cash than required. The NTOKEN_CASH_WITHHOLDING_BUFFER must be sufficient to cover this // potential shortfall. uint256 oracleRate = nToken.cashGroup.calculateOracleRate(maturity, oracleRateBlockTime); if (oracleRateBuffer > oracleRate) { oracleRate = 0; } else { oracleRate = oracleRate.sub(oracleRateBuffer); } totalCashWithholding = totalCashWithholding.sub( AssetHandler.getPresentfCashValue(notional, maturity, blockTime, oracleRate) ); } } // Turn off the bit and look for the next one assetsBitmap = assetsBitmap.setBit(bitNum, false); bitNum = assetsBitmap.getNextBitNum(); } return nToken.cashGroup.assetRate.convertFromUnderlying(totalCashWithholding); } function _calculateNetAssetCashAvailable( nTokenPortfolio memory nToken, MarketParameters[] memory previousMarkets, uint256 blockTime, uint256 currencyId, bool isFirstInit ) private returns (int256) { int256 netAssetCashAvailable; int256 assetCashWithholding; if (isFirstInit) { nToken.lastInitializedTime = uint40(DateTime.getTimeUTC0(blockTime)); } else { _settleNTokenPortfolio(nToken, blockTime); _getPreviousMarkets(currencyId, blockTime, nToken, previousMarkets); assetCashWithholding = _withholdAndSetfCashAssets( nToken, previousMarkets, currencyId, blockTime ); } // Deduct the amount of withholding required from the cash balance (at this point includes all settled cash) netAssetCashAvailable = nToken.cashBalance.subNoNeg(assetCashWithholding); // This is the new balance to store nToken.cashBalance = assetCashWithholding; // We can't have less net asset cash than our percent basis or some markets will end up not // initialized require( netAssetCashAvailable > int256(Constants.DEPOSIT_PERCENT_BASIS), "IM: insufficient cash" ); return netAssetCashAvailable; } /// @notice The six month implied rate is zero if there have never been any markets initialized /// otherwise the market will be the interpolation between the old 6 month and 1 year markets /// which are now sitting at 3 month and 9 month time to maturity function _getSixMonthImpliedRate( MarketParameters[] memory previousMarkets, uint256 referenceTime ) private pure returns (uint256) { // Cannot interpolate six month rate without a 1 year market require(previousMarkets.length >= 3, "IM: six month error"); return CashGroup.interpolateOracleRate( previousMarkets[1].maturity, previousMarkets[2].maturity, previousMarkets[1].oracleRate, previousMarkets[2].oracleRate, // Maturity date == 6 months from reference time referenceTime + 2 * Constants.QUARTER ); } /// @notice Calculates a market proportion via the implied rate. The formula is: /// exchangeRate = e ^ (impliedRate * timeToMaturity) /// exchangeRate = (1 / rateScalar) * ln(proportion / (1 - proportion)) + rateAnchor /// proportion / (1 - proportion) = e^((exchangeRate - rateAnchor) * rateScalar) /// exp = e^((exchangeRate - rateAnchor) * rateScalar) /// proportion / (1 - proportion) = exp /// exp * (1 - proportion) = proportion /// exp - exp * proportion = proportion /// exp = proportion + exp * proportion /// exp = proportion * (1 + exp) /// proportion = exp / (1 + exp) function _getProportionFromOracleRate( uint256 oracleRate, uint256 timeToMaturity, int256 rateScalar, uint256 annualizedAnchorRate ) private pure returns (int256) { int256 rateAnchor = Market.getExchangeRateFromImpliedRate(annualizedAnchorRate, timeToMaturity); // Exchange rate value here will be floored at Constants.RATE_PRECISION when the oracleRate is zero int256 exchangeRate = Market.getExchangeRateFromImpliedRate(oracleRate, timeToMaturity); int128 expValue = ABDKMath64x64.fromInt( // (exchangeRate - rateAnchor) * rateScalar (exchangeRate.sub(rateAnchor)).mulInRatePrecision(rateScalar) ); // Scale this back to a decimal in abdk expValue = ABDKMath64x64.div(expValue, Constants.RATE_PRECISION_64x64); // Take the exponent expValue = ABDKMath64x64.exp(expValue); // proportion = exp / (1 + exp) // NOTE: 2**64 == 1 in ABDKMath64x64 int128 proportion = ABDKMath64x64.div(expValue, ABDKMath64x64.add(expValue, 2**64)); // Scale this back to 1e9 precision proportion = ABDKMath64x64.mul(proportion, Constants.RATE_PRECISION_64x64); return ABDKMath64x64.toInt(proportion); } /// @dev Returns the oracle rate given the market ratios of fCash to cash. The annualizedAnchorRate /// is used to calculate a rate anchor. Since a rate anchor varies with timeToMaturity and annualizedAnchorRate /// does not, this method will return consistent values regardless of the timeToMaturity of when initialize /// markets is called. This can be helpful if a currency needs to be initialized mid quarter when it is /// newly launched. function _calculateOracleRate( int256 fCashAmount, int256 underlyingCashToMarket, int256 rateScalar, uint256 annualizedAnchorRate, uint256 timeToMaturity ) internal pure returns (uint256) { int256 rateAnchor = Market.getExchangeRateFromImpliedRate(annualizedAnchorRate, timeToMaturity); uint256 oracleRate = Market.getImpliedRate( fCashAmount, underlyingCashToMarket, rateScalar, rateAnchor, timeToMaturity ); return oracleRate; } /// @notice Returns the linear interpolation between two market rates. The formula is /// slope = (longMarket.oracleRate - shortMarket.oracleRate) / (longMarket.maturity - shortMarket.maturity) /// interpolatedRate = slope * (assetMaturity - shortMarket.maturity) + shortMarket.oracleRate function _interpolateFutureRate( uint256 shortMaturity, uint256 shortRate, MarketParameters memory longMarket ) private pure returns (uint256) { uint256 longMaturity = longMarket.maturity; uint256 longRate = longMarket.oracleRate; // the next market maturity is always a quarter away uint256 newMaturity = longMarket.maturity + Constants.QUARTER; require(shortMaturity < longMaturity, "IM: interpolation error"); // It's possible that the rates are inverted where the short market rate > long market rate and // we will get an underflow here so we check for that if (longRate >= shortRate) { return (longRate - shortRate) .mul(newMaturity - shortMaturity) // No underflow here, checked above .div(longMaturity - shortMaturity) .add(shortRate); } else { // In this case the slope is negative so: // interpolatedRate = shortMarket.oracleRate - slope * (assetMaturity - shortMarket.maturity) uint256 diff = (shortRate - longRate) .mul(newMaturity - shortMaturity) // No underflow here, checked above .div(longMaturity - shortMaturity); // This interpolation may go below zero so we bottom out interpolated rates at (practically) // zero. Storing a zero for oracleRates means that the markets are not initialized so using // a minimum value here to handle that case return shortRate > diff ? shortRate - diff : 1; } } /// @dev This is here to clear the stack function _setLiquidityAmount( int256 netAssetCashAvailable, int256 depositShare, uint256 assetType, MarketParameters memory newMarket, nTokenPortfolio memory nToken ) private pure returns (int256) { // The portion of the cash available that will be deposited into the market int256 assetCashToMarket = netAssetCashAvailable.mul(depositShare).div(Constants.DEPOSIT_PERCENT_BASIS); newMarket.totalAssetCash = assetCashToMarket; newMarket.totalLiquidity = assetCashToMarket; // Add a new liquidity token, this will end up in the new asset array nToken.portfolioState.addAsset( nToken.cashGroup.currencyId, newMarket.maturity, assetType, // This is liquidity token asset type assetCashToMarket ); // fCashAmount is calculated using the underlying amount return nToken.cashGroup.assetRate.convertToUnderlying(assetCashToMarket); } /// @notice Calculates the fCash amount given the cash and proportion: // proportion = totalfCash / (totalfCash + totalCashUnderlying) // proportion * (totalfCash + totalCashUnderlying) = totalfCash // proportion * totalCashUnderlying + proportion * totalfCash = totalfCash // proportion * totalCashUnderlying = totalfCash * (1 - proportion) // totalfCash = proportion * totalCashUnderlying / (1 - proportion) function _calculatefCashAmountFromProportion( int256 underlyingCashToMarket, int256 proportion ) private pure returns (int256) { return underlyingCashToMarket .mul(proportion) .div(Constants.RATE_PRECISION.sub(proportion)); } /// @notice Sweeps nToken cash balance into markets after accounting for cash withholding. Can be /// done after fCash residuals are purchased to ensure that markets have maximum liquidity. /// @param currencyId currency of markets to initialize /// @dev emit:CashSweepIntoMarkets /// @dev auth:none function sweepCashIntoMarkets(uint16 currencyId) external { uint256 blockTime = block.timestamp; nTokenPortfolio memory nToken; nToken.loadNTokenPortfolioStateful(currencyId); require(nToken.portfolioState.storedAssets.length > 0, "No nToken assets"); // Can only sweep cash after markets have been initialized uint256 referenceTime = DateTime.getReferenceTime(blockTime); require(nToken.lastInitializedTime >= referenceTime, "Must initialize markets"); // Can only sweep cash after the residual purchase time has passed uint256 minSweepCashTime = nToken.lastInitializedTime.add( uint256(uint8(nToken.parameters[Constants.RESIDUAL_PURCHASE_TIME_BUFFER])) * 1 hours ); require(blockTime > minSweepCashTime, "Invalid sweep cash time"); int256 assetCashWithholding = _getNTokenNegativefCashWithholding( nToken, new MarketParameters[](0), // Parameter is unused when referencing current markets blockTime ); int256 cashIntoMarkets = nToken.cashBalance.subNoNeg(assetCashWithholding); BalanceHandler.setBalanceStorageForNToken( nToken.tokenAddress, nToken.cashGroup.currencyId, assetCashWithholding ); // This will deposit the cash balance into markets, but will not record a token supply change. nTokenMintAction.nTokenMint(currencyId, cashIntoMarkets); emit SweepCashIntoMarkets(currencyId, cashIntoMarkets); } /// @notice Initialize the market for a given currency id, done once a quarter /// @param currencyId currency of markets to initialize /// @param isFirstInit true if this is the first time the markets have been initialized /// @dev emit:MarketsInitialized /// @dev auth:none function initializeMarkets(uint16 currencyId, bool isFirstInit) external { uint256 blockTime = block.timestamp; nTokenPortfolio memory nToken; nToken.loadNTokenPortfolioStateful(currencyId); MarketParameters[] memory previousMarkets = new MarketParameters[](nToken.cashGroup.maxMarketIndex); // This should be sufficient to validate that the currency id is valid require(nToken.cashGroup.maxMarketIndex != 0, "IM: no markets to init"); // If the nToken has any assets then this is not the first initialization if (isFirstInit) { require(nToken.portfolioState.storedAssets.length == 0, "IM: not first init"); } int256 netAssetCashAvailable = _calculateNetAssetCashAvailable( nToken, previousMarkets, blockTime, currencyId, isFirstInit ); GovernanceParameters memory parameters = _getGovernanceParameters(currencyId, nToken.cashGroup.maxMarketIndex); MarketParameters memory newMarket; // Oracle rate is carried over between loops uint256 oracleRate; for (uint256 i = 0; i < nToken.cashGroup.maxMarketIndex; i++) { // Traded markets are 1-indexed newMarket.maturity = DateTime.getReferenceTime(blockTime).add( DateTime.getTradedMarket(i + 1) ); int256 underlyingCashToMarket = _setLiquidityAmount( netAssetCashAvailable, parameters.depositShares[i], Constants.MIN_LIQUIDITY_TOKEN_INDEX + i, // liquidity token asset type newMarket, nToken ); uint256 timeToMaturity = newMarket.maturity.sub(blockTime); int256 rateScalar = nToken.cashGroup.getRateScalar(i + 1, timeToMaturity); // Governance will prevent previousMarkets.length from being equal to 1, meaning that we will // either have 0 markets (on first init), exactly 2 markets, or 2+ markets. In the case that there // are exactly two markets then the 6 month market must be initialized via this method (there is no // 9 month market to interpolate a rate against). In the case of 2+ markets then we will only enter this // first branch when the number of markets is increased if ( isFirstInit || // This is the six month market when there are only 3 and 6 month markets (i == 1 && previousMarkets.length == 2) || // At this point, these are new markets and they must be initialized (i >= nToken.portfolioState.storedAssets.length) || // When extending from the 6 month to 1 year market we must initialize both 6 and 1 year as new (i == 1 && previousMarkets[2].oracleRate == 0) ) { // Any newly added markets cannot have their implied rates interpolated via the previous // markets. In this case we initialize the markets using the rate anchor and proportion. int256 fCashAmount = _calculatefCashAmountFromProportion(underlyingCashToMarket, parameters.proportions[i]); newMarket.totalfCash = fCashAmount; newMarket.oracleRate = _calculateOracleRate( fCashAmount, underlyingCashToMarket, rateScalar, uint256(parameters.annualizedAnchorRates[i]), // No overflow, uint32 when set timeToMaturity ); // If this fails it is because the rate anchor and proportion are not set properly by // governance. require(newMarket.oracleRate > 0, "IM: implied rate failed"); } else { // Two special cases for the 3 month and 6 month market when interpolating implied rates. The 3 month market // inherits the implied rate from the previous 6 month market (they are now at the same maturity). if (i == 0) { // We should never get an array out of bounds error here because of the inequality check in the first branch // of the outer if statement. oracleRate = previousMarkets[1].oracleRate; } else if (i == 1) { // The six month market is the interpolation between the 3 month and the 1 year market (now at 9 months). This // interpolation is different since the rate is between 3 and 9 months, for all the other interpolations we interpolate // forward in time (i.e. use a 3 and 6 month rate to interpolate a 1 year rate). The first branch of this if statement // will capture the case when the 1 year rate has not been set. oracleRate = _getSixMonthImpliedRate( previousMarkets, DateTime.getReferenceTime(blockTime) ); } else { // Any other market has the interpolation between the new implied rate from the newly initialized market previous // to this market interpolated with the previous version of this market. For example, the newly initialized 1 year // market will have its implied rate set to the interpolation between the newly initialized 6 month market (done in // previous iteration of this loop) and the previous 1 year market (which has now rolled down to 9 months). Similarly, // a 2 year market will be interpolated from the newly initialized 1 year and the previous 2 year market. // This is the previous market maturity, traded markets are 1-indexed uint256 shortMarketMaturity = DateTime.getReferenceTime(blockTime).add(DateTime.getTradedMarket(i)); oracleRate = _interpolateFutureRate( shortMarketMaturity, // This is the oracle rate from the previous iteration in the loop, // refers to the new oracle rate set on the newly initialized market // that is adjacent to the market currently being initialized. oracleRate, // This is the previous version of the current market previousMarkets[i] ); } // When initializing new markets we need to ensure that the new implied oracle rates align // with the current yield curve or valuations for ifCash will spike. This should reference the // previously calculated implied rate and the current market. int256 proportion = _getProportionFromOracleRate( oracleRate, timeToMaturity, rateScalar, uint256(parameters.annualizedAnchorRates[i]) // No overflow, uint32 when set ); // If the calculated proportion is greater than the leverage threshold then we cannot // provide liquidity without risk of liquidation. In this case, set the leverage threshold // as the new proportion and calculate the oracle rate from it. This will result in fCash valuations // changing on chain, however, adding liquidity via nTokens would also end up with this // result as well. if (proportion > parameters.leverageThresholds[i]) { proportion = parameters.leverageThresholds[i]; newMarket.totalfCash = _calculatefCashAmountFromProportion(underlyingCashToMarket, proportion); oracleRate = _calculateOracleRate( newMarket.totalfCash, underlyingCashToMarket, rateScalar, uint256(parameters.annualizedAnchorRates[i]), // No overflow, uint32 when set timeToMaturity ); require(oracleRate != 0, "Oracle rate overflow"); } else { newMarket.totalfCash = _calculatefCashAmountFromProportion(underlyingCashToMarket, proportion); } // It's possible that totalfCash is zero from rounding errors above, we want to set this to a minimum value // so that we don't have divide by zero errors. if (newMarket.totalfCash < 1) newMarket.totalfCash = 1; newMarket.oracleRate = oracleRate; // The oracle rate has been changed so we set the previous trade time to current newMarket.previousTradeTime = blockTime; } // Implied rate will always be set to oracle rate newMarket.lastImpliedRate = newMarket.oracleRate; finalizeMarket(newMarket, currencyId, nToken); } // prettier-ignore ( /* hasDebt */, /* activeCurrencies */, uint8 assetArrayLength, /* nextSettleTime */ ) = nToken.portfolioState.storeAssets(nToken.tokenAddress); BalanceHandler.setBalanceStorageForNToken( nToken.tokenAddress, currencyId, nToken.cashBalance ); nTokenHandler.setArrayLengthAndInitializedTime( nToken.tokenAddress, assetArrayLength, nToken.lastInitializedTime ); emit MarketsInitialized(uint16(currencyId)); } function finalizeMarket( MarketParameters memory market, uint256 currencyId, nTokenPortfolio memory nToken ) internal { // Always reference the current settlement date uint256 settlementDate = DateTime.getReferenceTime(block.timestamp) + Constants.QUARTER; market.setMarketStorageForInitialize(currencyId, settlementDate); BitmapAssetsHandler.addifCashAsset( nToken.tokenAddress, currencyId, market.maturity, nToken.lastInitializedTime, market.totalfCash.neg() ); } /// @notice Get a list of deployed library addresses (sorted by library name) function getLibInfo() external view returns (address) { return address(nTokenMintAction); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../../global/Constants.sol"; import "../../internal/nToken/nTokenHandler.sol"; import "../../internal/nToken/nTokenCalculations.sol"; import "../../internal/markets/Market.sol"; import "../../internal/markets/CashGroup.sol"; import "../../internal/markets/AssetRate.sol"; import "../../internal/balances/BalanceHandler.sol"; import "../../internal/portfolio/PortfolioHandler.sol"; import "../../math/SafeInt256.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library nTokenMintAction { using SafeInt256 for int256; using BalanceHandler for BalanceState; using CashGroup for CashGroupParameters; using Market for MarketParameters; using nTokenHandler for nTokenPortfolio; using PortfolioHandler for PortfolioState; using AssetRate for AssetRateParameters; using SafeMath for uint256; using nTokenHandler for nTokenPortfolio; /// @notice Converts the given amount of cash to nTokens in the same currency. /// @param currencyId the currency associated the nToken /// @param amountToDepositInternal the amount of asset tokens to deposit denominated in internal decimals /// @return nTokens minted by this action function nTokenMint(uint16 currencyId, int256 amountToDepositInternal) external returns (int256) { uint256 blockTime = block.timestamp; nTokenPortfolio memory nToken; nToken.loadNTokenPortfolioStateful(currencyId); int256 tokensToMint = calculateTokensToMint(nToken, amountToDepositInternal, blockTime); require(tokensToMint >= 0, "Invalid token amount"); if (nToken.portfolioState.storedAssets.length == 0) { // If the token does not have any assets, then the markets must be initialized first. nToken.cashBalance = nToken.cashBalance.add(amountToDepositInternal); BalanceHandler.setBalanceStorageForNToken( nToken.tokenAddress, currencyId, nToken.cashBalance ); } else { _depositIntoPortfolio(nToken, amountToDepositInternal, blockTime); } // NOTE: token supply does not change here, it will change after incentives have been claimed // during BalanceHandler.finalize return tokensToMint; } /// @notice Calculates the tokens to mint to the account as a ratio of the nToken /// present value denominated in asset cash terms. /// @return the amount of tokens to mint, the ifCash bitmap function calculateTokensToMint( nTokenPortfolio memory nToken, int256 amountToDepositInternal, uint256 blockTime ) internal view returns (int256) { require(amountToDepositInternal >= 0); // dev: deposit amount negative if (amountToDepositInternal == 0) return 0; if (nToken.lastInitializedTime != 0) { // For the sake of simplicity, nTokens cannot be minted if they have assets // that need to be settled. This is only done during market initialization. uint256 nextSettleTime = nToken.getNextSettleTime(); // If next settle time <= blockTime then the token can be settled require(nextSettleTime > blockTime, "Requires settlement"); } int256 assetCashPV = nTokenCalculations.getNTokenAssetPV(nToken, blockTime); // Defensive check to ensure PV remains positive require(assetCashPV >= 0); // Allow for the first deposit if (nToken.totalSupply == 0) { return amountToDepositInternal; } else { // assetCashPVPost = assetCashPV + amountToDeposit // (tokenSupply + tokensToMint) / tokenSupply == (assetCashPV + amountToDeposit) / assetCashPV // (tokenSupply + tokensToMint) == (assetCashPV + amountToDeposit) * tokenSupply / assetCashPV // (tokenSupply + tokensToMint) == tokenSupply + (amountToDeposit * tokenSupply) / assetCashPV // tokensToMint == (amountToDeposit * tokenSupply) / assetCashPV return amountToDepositInternal.mul(nToken.totalSupply).div(assetCashPV); } } /// @notice Portions out assetCashDeposit into amounts to deposit into individual markets. When /// entering this method we know that assetCashDeposit is positive and the nToken has been /// initialized to have liquidity tokens. function _depositIntoPortfolio( nTokenPortfolio memory nToken, int256 assetCashDeposit, uint256 blockTime ) private { (int256[] memory depositShares, int256[] memory leverageThresholds) = nTokenHandler.getDepositParameters( nToken.cashGroup.currencyId, nToken.cashGroup.maxMarketIndex ); // Loop backwards from the last market to the first market, the reasoning is a little complicated: // If we have to deleverage the markets (i.e. lend instead of provide liquidity) it's quite gas inefficient // to calculate the cash amount to lend. We do know that longer term maturities will have more // slippage and therefore the residual from the perMarketDeposit will be lower as the maturities get // closer to the current block time. Any residual cash from lending will be rolled into shorter // markets as this loop progresses. int256 residualCash; MarketParameters memory market; for (uint256 marketIndex = nToken.cashGroup.maxMarketIndex; marketIndex > 0; marketIndex--) { int256 fCashAmount; // Loads values into the market memory slot nToken.cashGroup.loadMarket( market, marketIndex, true, // Needs liquidity to true blockTime ); // If market has not been initialized, continue. This can occur when cash groups extend maxMarketIndex // before initializing if (market.totalLiquidity == 0) continue; // Checked that assetCashDeposit must be positive before entering int256 perMarketDeposit = assetCashDeposit .mul(depositShares[marketIndex - 1]) .div(Constants.DEPOSIT_PERCENT_BASIS) .add(residualCash); (fCashAmount, residualCash) = _lendOrAddLiquidity( nToken, market, perMarketDeposit, leverageThresholds[marketIndex - 1], marketIndex, blockTime ); if (fCashAmount != 0) { BitmapAssetsHandler.addifCashAsset( nToken.tokenAddress, nToken.cashGroup.currencyId, market.maturity, nToken.lastInitializedTime, fCashAmount ); } } // nToken is allowed to store assets directly without updating account context. nToken.portfolioState.storeAssets(nToken.tokenAddress); // Defensive check to ensure that we do not somehow accrue negative residual cash. require(residualCash >= 0, "Negative residual cash"); // This will occur if the three month market is over levered and we cannot lend into it if (residualCash > 0) { // Any remaining residual cash will be put into the nToken balance and added as liquidity on the // next market initialization nToken.cashBalance = nToken.cashBalance.add(residualCash); BalanceHandler.setBalanceStorageForNToken( nToken.tokenAddress, nToken.cashGroup.currencyId, nToken.cashBalance ); } } /// @notice For a given amount of cash to deposit, decides how much to lend or provide /// given the market conditions. function _lendOrAddLiquidity( nTokenPortfolio memory nToken, MarketParameters memory market, int256 perMarketDeposit, int256 leverageThreshold, uint256 marketIndex, uint256 blockTime ) private returns (int256 fCashAmount, int256 residualCash) { // We start off with the entire per market deposit as residuals residualCash = perMarketDeposit; // If the market is over leveraged then we will lend to it instead of providing liquidity if (_isMarketOverLeveraged(nToken.cashGroup, market, leverageThreshold)) { (residualCash, fCashAmount) = _deleverageMarket( nToken.cashGroup, market, perMarketDeposit, blockTime, marketIndex ); // Recalculate this after lending into the market, if it is still over leveraged then // we will not add liquidity and just exit. if (_isMarketOverLeveraged(nToken.cashGroup, market, leverageThreshold)) { // Returns the residual cash amount return (fCashAmount, residualCash); } } // Add liquidity to the market only if we have successfully delevered. // (marketIndex - 1) is the index of the nToken portfolio array where the asset is stored // If deleveraged, residualCash is what remains // If not deleveraged, residual cash is per market deposit fCashAmount = fCashAmount.add( _addLiquidityToMarket(nToken, market, marketIndex - 1, residualCash) ); // No residual cash if we're adding liquidity return (fCashAmount, 0); } /// @notice Markets are over levered when their proportion is greater than a governance set /// threshold. At this point, providing liquidity will incur too much negative fCash on the nToken /// account for the given amount of cash deposited, putting the nToken account at risk of liquidation. /// If the market is over leveraged, we call `deleverageMarket` to lend to the market instead. function _isMarketOverLeveraged( CashGroupParameters memory cashGroup, MarketParameters memory market, int256 leverageThreshold ) private pure returns (bool) { int256 totalCashUnderlying = cashGroup.assetRate.convertToUnderlying(market.totalAssetCash); // Comparison we want to do: // (totalfCash) / (totalfCash + totalCashUnderlying) > leverageThreshold // However, the division will introduce rounding errors so we change this to: // totalfCash * RATE_PRECISION > leverageThreshold * (totalfCash + totalCashUnderlying) // Leverage threshold is denominated in rate precision. return ( market.totalfCash.mul(Constants.RATE_PRECISION) > leverageThreshold.mul(market.totalfCash.add(totalCashUnderlying)) ); } function _addLiquidityToMarket( nTokenPortfolio memory nToken, MarketParameters memory market, uint256 index, int256 perMarketDeposit ) private returns (int256) { // Add liquidity to the market PortfolioAsset memory asset = nToken.portfolioState.storedAssets[index]; // We expect that all the liquidity tokens are in the portfolio in order. require( asset.maturity == market.maturity && // Ensures that the asset type references the proper liquidity token asset.assetType == index + Constants.MIN_LIQUIDITY_TOKEN_INDEX && // Ensures that the storage state will not be overwritten asset.storageState == AssetStorageState.NoChange, "PT: invalid liquidity token" ); // This will update the market state as well, fCashAmount returned here is negative (int256 liquidityTokens, int256 fCashAmount) = market.addLiquidity(perMarketDeposit); asset.notional = asset.notional.add(liquidityTokens); asset.storageState = AssetStorageState.Update; return fCashAmount; } /// @notice Lends into the market to reduce the leverage that the nToken will add liquidity at. May fail due /// to slippage or result in some amount of residual cash. function _deleverageMarket( CashGroupParameters memory cashGroup, MarketParameters memory market, int256 perMarketDeposit, uint256 blockTime, uint256 marketIndex ) private returns (int256, int256) { uint256 timeToMaturity = market.maturity.sub(blockTime); // Shift the last implied rate by some buffer and calculate the exchange rate to fCash. Hope that this // is sufficient to cover all potential slippage. We don't use the `getfCashGivenCashAmount` method here // because it is very gas inefficient. int256 assumedExchangeRate; if (market.lastImpliedRate < Constants.DELEVERAGE_BUFFER) { // Floor the exchange rate at zero interest rate assumedExchangeRate = Constants.RATE_PRECISION; } else { assumedExchangeRate = Market.getExchangeRateFromImpliedRate( market.lastImpliedRate.sub(Constants.DELEVERAGE_BUFFER), timeToMaturity ); } int256 fCashAmount; { int256 perMarketDepositUnderlying = cashGroup.assetRate.convertToUnderlying(perMarketDeposit); // NOTE: cash * exchangeRate = fCash fCashAmount = perMarketDepositUnderlying.mulInRatePrecision(assumedExchangeRate); } int256 netAssetCash = market.executeTrade(cashGroup, fCashAmount, timeToMaturity, marketIndex); // This means that the trade failed if (netAssetCash == 0) { return (perMarketDeposit, 0); } else { // Ensure that net the per market deposit figure does not drop below zero, this should not be possible // given how we've calculated the exchange rate but extra caution here int256 residual = perMarketDeposit.add(netAssetCash); require(residual >= 0); // dev: insufficient cash return (residual, fCashAmount); } } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./AssetRate.sol"; import "./CashGroup.sol"; import "./DateTime.sol"; import "../balances/BalanceHandler.sol"; import "../../global/LibStorage.sol"; import "../../global/Types.sol"; import "../../global/Constants.sol"; import "../../math/SafeInt256.sol"; import "../../math/ABDKMath64x64.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library Market { using SafeMath for uint256; using SafeInt256 for int256; using CashGroup for CashGroupParameters; using AssetRate for AssetRateParameters; // Max positive value for a ABDK64x64 integer int256 private constant MAX64 = 0x7FFFFFFFFFFFFFFF; /// @notice Add liquidity to a market, assuming that it is initialized. If not then /// this method will revert and the market must be initialized first. /// Return liquidityTokens and negative fCash to the portfolio function addLiquidity(MarketParameters memory market, int256 assetCash) internal returns (int256 liquidityTokens, int256 fCash) { require(market.totalLiquidity > 0, "M: zero liquidity"); if (assetCash == 0) return (0, 0); require(assetCash > 0); // dev: negative asset cash liquidityTokens = market.totalLiquidity.mul(assetCash).div(market.totalAssetCash); // No need to convert this to underlying, assetCash / totalAssetCash is a unitless proportion. fCash = market.totalfCash.mul(assetCash).div(market.totalAssetCash); market.totalLiquidity = market.totalLiquidity.add(liquidityTokens); market.totalfCash = market.totalfCash.add(fCash); market.totalAssetCash = market.totalAssetCash.add(assetCash); _setMarketStorageForLiquidity(market); // Flip the sign to represent the LP's net position fCash = fCash.neg(); } /// @notice Remove liquidity from a market, assuming that it is initialized. /// Return assetCash and positive fCash to the portfolio function removeLiquidity(MarketParameters memory market, int256 tokensToRemove) internal returns (int256 assetCash, int256 fCash) { if (tokensToRemove == 0) return (0, 0); require(tokensToRemove > 0); // dev: negative tokens to remove assetCash = market.totalAssetCash.mul(tokensToRemove).div(market.totalLiquidity); fCash = market.totalfCash.mul(tokensToRemove).div(market.totalLiquidity); market.totalLiquidity = market.totalLiquidity.subNoNeg(tokensToRemove); market.totalfCash = market.totalfCash.subNoNeg(fCash); market.totalAssetCash = market.totalAssetCash.subNoNeg(assetCash); _setMarketStorageForLiquidity(market); } function executeTrade( MarketParameters memory market, CashGroupParameters memory cashGroup, int256 fCashToAccount, uint256 timeToMaturity, uint256 marketIndex ) internal returns (int256 netAssetCash) { int256 netAssetCashToReserve; (netAssetCash, netAssetCashToReserve) = calculateTrade( market, cashGroup, fCashToAccount, timeToMaturity, marketIndex ); MarketStorage storage marketStorage = _getMarketStoragePointer(market); _setMarketStorage( marketStorage, market.totalfCash, market.totalAssetCash, market.lastImpliedRate, market.oracleRate, market.previousTradeTime ); BalanceHandler.incrementFeeToReserve(cashGroup.currencyId, netAssetCashToReserve); } /// @notice Calculates the asset cash amount the results from trading fCashToAccount with the market. A positive /// fCashToAccount is equivalent of lending, a negative is borrowing. Updates the market state in memory. /// @param market the current market state /// @param cashGroup cash group configuration parameters /// @param fCashToAccount the fCash amount that will be deposited into the user's portfolio. The net change /// to the market is in the opposite direction. /// @param timeToMaturity number of seconds until maturity /// @return netAssetCash, netAssetCashToReserve function calculateTrade( MarketParameters memory market, CashGroupParameters memory cashGroup, int256 fCashToAccount, uint256 timeToMaturity, uint256 marketIndex ) internal view returns (int256, int256) { // We return false if there is not enough fCash to support this trade. // if fCashToAccount > 0 and totalfCash - fCashToAccount <= 0 then the trade will fail // if fCashToAccount < 0 and totalfCash > 0 then this will always pass if (market.totalfCash <= fCashToAccount) return (0, 0); // Calculates initial rate factors for the trade (int256 rateScalar, int256 totalCashUnderlying, int256 rateAnchor) = getExchangeRateFactors(market, cashGroup, timeToMaturity, marketIndex); // Calculates the exchange rate from cash to fCash before any liquidity fees // are applied int256 preFeeExchangeRate; { bool success; (preFeeExchangeRate, success) = _getExchangeRate( market.totalfCash, totalCashUnderlying, rateScalar, rateAnchor, fCashToAccount ); if (!success) return (0, 0); } // Given the exchange rate, returns the net cash amounts to apply to each of the // three relevant balances. (int256 netCashToAccount, int256 netCashToMarket, int256 netCashToReserve) = _getNetCashAmountsUnderlying( cashGroup, preFeeExchangeRate, fCashToAccount, timeToMaturity ); // Signifies a failed net cash amount calculation if (netCashToAccount == 0) return (0, 0); { // Set the new implied interest rate after the trade has taken effect, this // will be used to calculate the next trader's interest rate. market.totalfCash = market.totalfCash.subNoNeg(fCashToAccount); market.lastImpliedRate = getImpliedRate( market.totalfCash, totalCashUnderlying.add(netCashToMarket), rateScalar, rateAnchor, timeToMaturity ); // It's technically possible that the implied rate is actually exactly zero (or // more accurately the natural log rounds down to zero) but we will still fail // in this case. If this does happen we may assume that markets are not initialized. if (market.lastImpliedRate == 0) return (0, 0); } return _setNewMarketState( market, cashGroup.assetRate, netCashToAccount, netCashToMarket, netCashToReserve ); } /// @notice Returns factors for calculating exchange rates /// @return /// rateScalar: a scalar value in rate precision that defines the slope of the line /// totalCashUnderlying: the converted asset cash to underlying cash for calculating /// the exchange rates for the trade /// rateAnchor: an offset from the x axis to maintain interest rate continuity over time function getExchangeRateFactors( MarketParameters memory market, CashGroupParameters memory cashGroup, uint256 timeToMaturity, uint256 marketIndex ) internal pure returns ( int256, int256, int256 ) { int256 rateScalar = cashGroup.getRateScalar(marketIndex, timeToMaturity); int256 totalCashUnderlying = cashGroup.assetRate.convertToUnderlying(market.totalAssetCash); // This would result in a divide by zero if (market.totalfCash == 0 || totalCashUnderlying == 0) return (0, 0, 0); // Get the rate anchor given the market state, this will establish the baseline for where // the exchange rate is set. int256 rateAnchor; { bool success; (rateAnchor, success) = _getRateAnchor( market.totalfCash, market.lastImpliedRate, totalCashUnderlying, rateScalar, timeToMaturity ); if (!success) return (0, 0, 0); } return (rateScalar, totalCashUnderlying, rateAnchor); } /// @dev Returns net asset cash amounts to the account, the market and the reserve /// @return /// netCashToAccount: this is a positive or negative amount of cash change to the account /// netCashToMarket: this is a positive or negative amount of cash change in the market // netCashToReserve: this is always a positive amount of cash accrued to the reserve function _getNetCashAmountsUnderlying( CashGroupParameters memory cashGroup, int256 preFeeExchangeRate, int256 fCashToAccount, uint256 timeToMaturity ) private pure returns ( int256, int256, int256 ) { // Fees are specified in basis points which is an rate precision denomination. We convert this to // an exchange rate denomination for the given time to maturity. (i.e. get e^(fee * t) and multiply // or divide depending on the side of the trade). // tradeExchangeRate = exp((tradeInterestRateNoFee +/- fee) * timeToMaturity) // tradeExchangeRate = tradeExchangeRateNoFee (* or /) exp(fee * timeToMaturity) // cash = fCash / exchangeRate, exchangeRate > 1 int256 preFeeCashToAccount = fCashToAccount.divInRatePrecision(preFeeExchangeRate).neg(); int256 fee = getExchangeRateFromImpliedRate(cashGroup.getTotalFee(), timeToMaturity); if (fCashToAccount > 0) { // Lending // Dividing reduces exchange rate, lending should receive less fCash for cash int256 postFeeExchangeRate = preFeeExchangeRate.divInRatePrecision(fee); // It's possible that the fee pushes exchange rates into negative territory. This is not possible // when borrowing. If this happens then the trade has failed. if (postFeeExchangeRate < Constants.RATE_PRECISION) return (0, 0, 0); // cashToAccount = -(fCashToAccount / exchangeRate) // postFeeExchangeRate = preFeeExchangeRate / feeExchangeRate // preFeeCashToAccount = -(fCashToAccount / preFeeExchangeRate) // postFeeCashToAccount = -(fCashToAccount / postFeeExchangeRate) // netFee = preFeeCashToAccount - postFeeCashToAccount // netFee = (fCashToAccount / postFeeExchangeRate) - (fCashToAccount / preFeeExchangeRate) // netFee = ((fCashToAccount * feeExchangeRate) / preFeeExchangeRate) - (fCashToAccount / preFeeExchangeRate) // netFee = (fCashToAccount / preFeeExchangeRate) * (feeExchangeRate - 1) // netFee = -(preFeeCashToAccount) * (feeExchangeRate - 1) // netFee = preFeeCashToAccount * (1 - feeExchangeRate) // RATE_PRECISION - fee will be negative here, preFeeCashToAccount < 0, fee > 0 fee = preFeeCashToAccount.mulInRatePrecision(Constants.RATE_PRECISION.sub(fee)); } else { // Borrowing // cashToAccount = -(fCashToAccount / exchangeRate) // postFeeExchangeRate = preFeeExchangeRate * feeExchangeRate // netFee = preFeeCashToAccount - postFeeCashToAccount // netFee = (fCashToAccount / postFeeExchangeRate) - (fCashToAccount / preFeeExchangeRate) // netFee = ((fCashToAccount / (feeExchangeRate * preFeeExchangeRate)) - (fCashToAccount / preFeeExchangeRate) // netFee = (fCashToAccount / preFeeExchangeRate) * (1 / feeExchangeRate - 1) // netFee = preFeeCashToAccount * ((1 - feeExchangeRate) / feeExchangeRate) // NOTE: preFeeCashToAccount is negative in this branch so we negate it to ensure that fee is a positive number // preFee * (1 - fee) / fee will be negative, use neg() to flip to positive // RATE_PRECISION - fee will be negative fee = preFeeCashToAccount.mul(Constants.RATE_PRECISION.sub(fee)).div(fee).neg(); } int256 cashToReserve = fee.mul(cashGroup.getReserveFeeShare()).div(Constants.PERCENTAGE_DECIMALS); return ( // postFeeCashToAccount = preFeeCashToAccount - fee preFeeCashToAccount.sub(fee), // netCashToMarket = -(preFeeCashToAccount - fee + cashToReserve) (preFeeCashToAccount.sub(fee).add(cashToReserve)).neg(), cashToReserve ); } /// @notice Sets the new market state /// @return /// netAssetCashToAccount: the positive or negative change in asset cash to the account /// assetCashToReserve: the positive amount of cash that accrues to the reserve function _setNewMarketState( MarketParameters memory market, AssetRateParameters memory assetRate, int256 netCashToAccount, int256 netCashToMarket, int256 netCashToReserve ) private view returns (int256, int256) { int256 netAssetCashToMarket = assetRate.convertFromUnderlying(netCashToMarket); // Set storage checks that total asset cash is above zero market.totalAssetCash = market.totalAssetCash.add(netAssetCashToMarket); // Sets the trade time for the next oracle update market.previousTradeTime = block.timestamp; int256 assetCashToReserve = assetRate.convertFromUnderlying(netCashToReserve); int256 netAssetCashToAccount = assetRate.convertFromUnderlying(netCashToAccount); return (netAssetCashToAccount, assetCashToReserve); } /// @notice Rate anchors update as the market gets closer to maturity. Rate anchors are not comparable /// across time or markets but implied rates are. The goal here is to ensure that the implied rate /// before and after the rate anchor update is the same. Therefore, the market will trade at the same implied /// rate that it last traded at. If these anchors do not update then it opens up the opportunity for arbitrage /// which will hurt the liquidity providers. /// /// The rate anchor will update as the market rolls down to maturity. The calculation is: /// newExchangeRate = e^(lastImpliedRate * timeToMaturity / Constants.IMPLIED_RATE_TIME) /// newAnchor = newExchangeRate - ln((proportion / (1 - proportion)) / rateScalar /// /// where: /// lastImpliedRate = ln(exchangeRate') * (Constants.IMPLIED_RATE_TIME / timeToMaturity') /// (calculated when the last trade in the market was made) /// @return the new rate anchor and a boolean that signifies success function _getRateAnchor( int256 totalfCash, uint256 lastImpliedRate, int256 totalCashUnderlying, int256 rateScalar, uint256 timeToMaturity ) internal pure returns (int256, bool) { // This is the exchange rate at the new time to maturity int256 newExchangeRate = getExchangeRateFromImpliedRate(lastImpliedRate, timeToMaturity); if (newExchangeRate < Constants.RATE_PRECISION) return (0, false); int256 rateAnchor; { // totalfCash / (totalfCash + totalCashUnderlying) int256 proportion = totalfCash.divInRatePrecision(totalfCash.add(totalCashUnderlying)); (int256 lnProportion, bool success) = _logProportion(proportion); if (!success) return (0, false); // newExchangeRate - ln(proportion / (1 - proportion)) / rateScalar rateAnchor = newExchangeRate.sub(lnProportion.divInRatePrecision(rateScalar)); } return (rateAnchor, true); } /// @notice Calculates the current market implied rate. /// @return the implied rate and a bool that is true on success function getImpliedRate( int256 totalfCash, int256 totalCashUnderlying, int256 rateScalar, int256 rateAnchor, uint256 timeToMaturity ) internal pure returns (uint256) { // This will check for exchange rates < Constants.RATE_PRECISION (int256 exchangeRate, bool success) = _getExchangeRate(totalfCash, totalCashUnderlying, rateScalar, rateAnchor, 0); if (!success) return 0; // Uses continuous compounding to calculate the implied rate: // ln(exchangeRate) * Constants.IMPLIED_RATE_TIME / timeToMaturity int128 rate = ABDKMath64x64.fromInt(exchangeRate); // Scales down to a floating point for LN int128 rateScaled = ABDKMath64x64.div(rate, Constants.RATE_PRECISION_64x64); // We will not have a negative log here because we check that exchangeRate > Constants.RATE_PRECISION // inside getExchangeRate int128 lnRateScaled = ABDKMath64x64.ln(rateScaled); // Scales up to a fixed point uint256 lnRate = ABDKMath64x64.toUInt(ABDKMath64x64.mul(lnRateScaled, Constants.RATE_PRECISION_64x64)); // lnRate * IMPLIED_RATE_TIME / ttm uint256 impliedRate = lnRate.mul(Constants.IMPLIED_RATE_TIME).div(timeToMaturity); // Implied rates over 429% will overflow, this seems like a safe assumption if (impliedRate > type(uint32).max) return 0; return impliedRate; } /// @notice Converts an implied rate to an exchange rate given a time to maturity. The /// formula is E = e^rt function getExchangeRateFromImpliedRate(uint256 impliedRate, uint256 timeToMaturity) internal pure returns (int256) { int128 expValue = ABDKMath64x64.fromUInt( impliedRate.mul(timeToMaturity).div(Constants.IMPLIED_RATE_TIME) ); int128 expValueScaled = ABDKMath64x64.div(expValue, Constants.RATE_PRECISION_64x64); int128 expResult = ABDKMath64x64.exp(expValueScaled); int128 expResultScaled = ABDKMath64x64.mul(expResult, Constants.RATE_PRECISION_64x64); return ABDKMath64x64.toInt(expResultScaled); } /// @notice Returns the exchange rate between fCash and cash for the given market /// Calculates the following exchange rate: /// (1 / rateScalar) * ln(proportion / (1 - proportion)) + rateAnchor /// where: /// proportion = totalfCash / (totalfCash + totalUnderlyingCash) /// @dev has an underscore to denote as private but is marked internal for the mock function _getExchangeRate( int256 totalfCash, int256 totalCashUnderlying, int256 rateScalar, int256 rateAnchor, int256 fCashToAccount ) internal pure returns (int256, bool) { int256 numerator = totalfCash.subNoNeg(fCashToAccount); // This is the proportion scaled by Constants.RATE_PRECISION // (totalfCash + fCash) / (totalfCash + totalCashUnderlying) int256 proportion = numerator.divInRatePrecision(totalfCash.add(totalCashUnderlying)); // This limit is here to prevent the market from reaching extremely high interest rates via an // excessively large proportion (high amounts of fCash relative to cash). // Market proportion can only increase via borrowing (fCash is added to the market and cash is // removed). Over time, the returns from asset cash will slightly decrease the proportion (the // value of cash underlying in the market must be monotonically increasing). Therefore it is not // possible for the proportion to go over max market proportion unless borrowing occurs. if (proportion > Constants.MAX_MARKET_PROPORTION) return (0, false); (int256 lnProportion, bool success) = _logProportion(proportion); if (!success) return (0, false); // lnProportion / rateScalar + rateAnchor int256 rate = lnProportion.divInRatePrecision(rateScalar).add(rateAnchor); // Do not succeed if interest rates fall below 1 if (rate < Constants.RATE_PRECISION) { return (0, false); } else { return (rate, true); } } /// @dev This method calculates the log of the proportion inside the logit function which is /// defined as ln(proportion / (1 - proportion)). Special handling here is required to deal with /// fixed point precision and the ABDK library. function _logProportion(int256 proportion) internal pure returns (int256, bool) { // This will result in divide by zero, short circuit if (proportion == Constants.RATE_PRECISION) return (0, false); // Convert proportion to what is used inside the logit function (p / (1-p)) int256 logitP = proportion.divInRatePrecision(Constants.RATE_PRECISION.sub(proportion)); // ABDK does not handle log of numbers that are less than 1, in order to get the right value // scaled by RATE_PRECISION we use the log identity: // (ln(logitP / RATE_PRECISION)) * RATE_PRECISION = (ln(logitP) - ln(RATE_PRECISION)) * RATE_PRECISION int128 abdkProportion = ABDKMath64x64.fromInt(logitP); // Here, abdk will revert due to negative log so abort if (abdkProportion <= 0) return (0, false); int256 result = ABDKMath64x64.toInt( ABDKMath64x64.mul( ABDKMath64x64.sub( ABDKMath64x64.ln(abdkProportion), Constants.LOG_RATE_PRECISION_64x64 ), Constants.RATE_PRECISION_64x64 ) ); return (result, true); } /// @notice Oracle rate protects against short term price manipulation. Time window will be set to a value /// on the order of minutes to hours. This is to protect fCash valuations from market manipulation. For example, /// a trader could use a flash loan to dump a large amount of cash into the market and depress interest rates. /// Since we value fCash in portfolios based on these rates, portfolio values will decrease and they may then /// be liquidated. /// /// Oracle rates are calculated when the market is loaded from storage. /// /// The oracle rate is a lagged weighted average over a short term price window. If we are past /// the short term window then we just set the rate to the lastImpliedRate, otherwise we take the /// weighted average: /// lastImpliedRatePreTrade * (currentTs - previousTs) / timeWindow + /// oracleRatePrevious * (1 - (currentTs - previousTs) / timeWindow) function _updateRateOracle( uint256 previousTradeTime, uint256 lastImpliedRate, uint256 oracleRate, uint256 rateOracleTimeWindow, uint256 blockTime ) private pure returns (uint256) { require(rateOracleTimeWindow > 0); // dev: update rate oracle, time window zero // This can occur when using a view function get to a market state in the past if (previousTradeTime > blockTime) return lastImpliedRate; uint256 timeDiff = blockTime.sub(previousTradeTime); if (timeDiff > rateOracleTimeWindow) { // If past the time window just return the lastImpliedRate return lastImpliedRate; } // (currentTs - previousTs) / timeWindow uint256 lastTradeWeight = timeDiff.mul(uint256(Constants.RATE_PRECISION)).div(rateOracleTimeWindow); // 1 - (currentTs - previousTs) / timeWindow uint256 oracleWeight = uint256(Constants.RATE_PRECISION).sub(lastTradeWeight); uint256 newOracleRate = (lastImpliedRate.mul(lastTradeWeight).add(oracleRate.mul(oracleWeight))).div( uint256(Constants.RATE_PRECISION) ); return newOracleRate; } function getOracleRate( uint256 currencyId, uint256 maturity, uint256 rateOracleTimeWindow, uint256 blockTime ) internal view returns (uint256) { mapping(uint256 => mapping(uint256 => mapping(uint256 => MarketStorage))) storage store = LibStorage.getMarketStorage(); uint256 settlementDate = DateTime.getReferenceTime(blockTime) + Constants.QUARTER; MarketStorage storage marketStorage = store[currencyId][maturity][settlementDate]; uint256 lastImpliedRate = marketStorage.lastImpliedRate; uint256 oracleRate = marketStorage.oracleRate; uint256 previousTradeTime = marketStorage.previousTradeTime; // If the oracle rate is set to zero this can only be because the markets have past their settlement // date but the new set of markets has not yet been initialized. This means that accounts cannot be liquidated // during this time, but market initialization can be called by anyone so the actual time that this condition // exists for should be quite short. require(oracleRate > 0, "Market not initialized"); return _updateRateOracle( previousTradeTime, lastImpliedRate, oracleRate, rateOracleTimeWindow, blockTime ); } /// @notice Reads a market object directly from storage. `loadMarket` should be called instead of this method /// which ensures that the rate oracle is set properly. function _loadMarketStorage( MarketParameters memory market, uint256 currencyId, uint256 maturity, bool needsLiquidity, uint256 settlementDate ) private view { // Market object always uses the most current reference time as the settlement date mapping(uint256 => mapping(uint256 => mapping(uint256 => MarketStorage))) storage store = LibStorage.getMarketStorage(); MarketStorage storage marketStorage = store[currencyId][maturity][settlementDate]; bytes32 slot; assembly { slot := marketStorage.slot } market.storageSlot = slot; market.maturity = maturity; market.totalfCash = marketStorage.totalfCash; market.totalAssetCash = marketStorage.totalAssetCash; market.lastImpliedRate = marketStorage.lastImpliedRate; market.oracleRate = marketStorage.oracleRate; market.previousTradeTime = marketStorage.previousTradeTime; if (needsLiquidity) { market.totalLiquidity = marketStorage.totalLiquidity; } else { market.totalLiquidity = 0; } } function _getMarketStoragePointer( MarketParameters memory market ) private pure returns (MarketStorage storage marketStorage) { bytes32 slot = market.storageSlot; assembly { marketStorage.slot := slot } } function _setMarketStorageForLiquidity(MarketParameters memory market) internal { MarketStorage storage marketStorage = _getMarketStoragePointer(market); // Oracle rate does not change on liquidity uint32 storedOracleRate = marketStorage.oracleRate; _setMarketStorage( marketStorage, market.totalfCash, market.totalAssetCash, market.lastImpliedRate, storedOracleRate, market.previousTradeTime ); _setTotalLiquidity(marketStorage, market.totalLiquidity); } function setMarketStorageForInitialize( MarketParameters memory market, uint256 currencyId, uint256 settlementDate ) internal { // On initialization we have not yet calculated the storage slot so we get it here. mapping(uint256 => mapping(uint256 => mapping(uint256 => MarketStorage))) storage store = LibStorage.getMarketStorage(); MarketStorage storage marketStorage = store[currencyId][market.maturity][settlementDate]; _setMarketStorage( marketStorage, market.totalfCash, market.totalAssetCash, market.lastImpliedRate, market.oracleRate, market.previousTradeTime ); _setTotalLiquidity(marketStorage, market.totalLiquidity); } function _setTotalLiquidity( MarketStorage storage marketStorage, int256 totalLiquidity ) internal { require(totalLiquidity >= 0 && totalLiquidity <= type(uint80).max); // dev: market storage totalLiquidity overflow marketStorage.totalLiquidity = uint80(totalLiquidity); } function _setMarketStorage( MarketStorage storage marketStorage, int256 totalfCash, int256 totalAssetCash, uint256 lastImpliedRate, uint256 oracleRate, uint256 previousTradeTime ) private { require(totalfCash >= 0 && totalfCash <= type(uint80).max); // dev: storage totalfCash overflow require(totalAssetCash >= 0 && totalAssetCash <= type(uint80).max); // dev: storage totalAssetCash overflow require(0 < lastImpliedRate && lastImpliedRate <= type(uint32).max); // dev: storage lastImpliedRate overflow require(0 < oracleRate && oracleRate <= type(uint32).max); // dev: storage oracleRate overflow require(0 <= previousTradeTime && previousTradeTime <= type(uint32).max); // dev: storage previous trade time overflow marketStorage.totalfCash = uint80(totalfCash); marketStorage.totalAssetCash = uint80(totalAssetCash); marketStorage.lastImpliedRate = uint32(lastImpliedRate); marketStorage.oracleRate = uint32(oracleRate); marketStorage.previousTradeTime = uint32(previousTradeTime); } /// @notice Creates a market object and ensures that the rate oracle time window is updated appropriately. function loadMarket( MarketParameters memory market, uint256 currencyId, uint256 maturity, uint256 blockTime, bool needsLiquidity, uint256 rateOracleTimeWindow ) internal view { // Always reference the current settlement date uint256 settlementDate = DateTime.getReferenceTime(blockTime) + Constants.QUARTER; loadMarketWithSettlementDate( market, currencyId, maturity, blockTime, needsLiquidity, rateOracleTimeWindow, settlementDate ); } /// @notice Creates a market object and ensures that the rate oracle time window is updated appropriately, this /// is mainly used in the InitializeMarketAction contract. function loadMarketWithSettlementDate( MarketParameters memory market, uint256 currencyId, uint256 maturity, uint256 blockTime, bool needsLiquidity, uint256 rateOracleTimeWindow, uint256 settlementDate ) internal view { _loadMarketStorage(market, currencyId, maturity, needsLiquidity, settlementDate); market.oracleRate = _updateRateOracle( market.previousTradeTime, market.lastImpliedRate, market.oracleRate, rateOracleTimeWindow, blockTime ); } function loadSettlementMarket( MarketParameters memory market, uint256 currencyId, uint256 maturity, uint256 settlementDate ) internal view { _loadMarketStorage(market, currencyId, maturity, true, settlementDate); } /// Uses Newton's method to converge on an fCash amount given the amount of /// cash. The relation between cash and fcash is: /// cashAmount * exchangeRate * fee + fCash = 0 /// where exchangeRate(fCash) = (rateScalar ^ -1) * ln(p / (1 - p)) + rateAnchor /// p = (totalfCash - fCash) / (totalfCash + totalCash) /// if cashAmount < 0: fee = feeRate ^ -1 /// if cashAmount > 0: fee = feeRate /// /// Newton's method is: /// fCash_(n+1) = fCash_n - f(fCash) / f'(fCash) /// /// f(fCash) = cashAmount * exchangeRate(fCash) * fee + fCash /// /// (totalfCash + totalCash) /// exchangeRate'(fCash) = - ------------------------------------------ /// (totalfCash - fCash) * (totalCash + fCash) /// /// https://www.wolframalpha.com/input/?i=ln%28%28%28a-x%29%2F%28a%2Bb%29%29%2F%281-%28a-x%29%2F%28a%2Bb%29%29%29 /// /// (cashAmount * fee) * (totalfCash + totalCash) /// f'(fCash) = 1 - ------------------------------------------------------ /// rateScalar * (totalfCash - fCash) * (totalCash + fCash) /// /// NOTE: each iteration costs about 11.3k so this is only done via a view function. function getfCashGivenCashAmount( int256 totalfCash, int256 netCashToAccount, int256 totalCashUnderlying, int256 rateScalar, int256 rateAnchor, int256 feeRate, int256 maxDelta ) internal pure returns (int256) { require(maxDelta >= 0); int256 fCashChangeToAccountGuess = netCashToAccount.mulInRatePrecision(rateAnchor).neg(); for (uint8 i = 0; i < 250; i++) { (int256 exchangeRate, bool success) = _getExchangeRate( totalfCash, totalCashUnderlying, rateScalar, rateAnchor, fCashChangeToAccountGuess ); require(success); // dev: invalid exchange rate int256 delta = _calculateDelta( netCashToAccount, totalfCash, totalCashUnderlying, rateScalar, fCashChangeToAccountGuess, exchangeRate, feeRate ); if (delta.abs() <= maxDelta) return fCashChangeToAccountGuess; fCashChangeToAccountGuess = fCashChangeToAccountGuess.sub(delta); } revert("No convergence"); } /// @dev Calculates: f(fCash) / f'(fCash) /// f(fCash) = cashAmount * exchangeRate * fee + fCash /// (cashAmount * fee) * (totalfCash + totalCash) /// f'(fCash) = 1 - ------------------------------------------------------ /// rateScalar * (totalfCash - fCash) * (totalCash + fCash) function _calculateDelta( int256 cashAmount, int256 totalfCash, int256 totalCashUnderlying, int256 rateScalar, int256 fCashGuess, int256 exchangeRate, int256 feeRate ) private pure returns (int256) { int256 derivative; // rateScalar * (totalfCash - fCash) * (totalCash + fCash) // Precision: TOKEN_PRECISION ^ 2 int256 denominator = rateScalar.mulInRatePrecision( (totalfCash.sub(fCashGuess)).mul(totalCashUnderlying.add(fCashGuess)) ); if (fCashGuess > 0) { // Lending exchangeRate = exchangeRate.divInRatePrecision(feeRate); require(exchangeRate >= Constants.RATE_PRECISION); // dev: rate underflow // (cashAmount / fee) * (totalfCash + totalCash) // Precision: TOKEN_PRECISION ^ 2 derivative = cashAmount .mul(totalfCash.add(totalCashUnderlying)) .divInRatePrecision(feeRate); } else { // Borrowing exchangeRate = exchangeRate.mulInRatePrecision(feeRate); require(exchangeRate >= Constants.RATE_PRECISION); // dev: rate underflow // (cashAmount * fee) * (totalfCash + totalCash) // Precision: TOKEN_PRECISION ^ 2 derivative = cashAmount.mulInRatePrecision( feeRate.mul(totalfCash.add(totalCashUnderlying)) ); } // 1 - numerator / denominator // Precision: TOKEN_PRECISION derivative = Constants.INTERNAL_TOKEN_PRECISION.sub(derivative.div(denominator)); // f(fCash) = cashAmount * exchangeRate * fee + fCash // NOTE: exchangeRate at this point already has the fee taken into account int256 numerator = cashAmount.mulInRatePrecision(exchangeRate); numerator = numerator.add(fCashGuess); // f(fCash) / f'(fCash), note that they are both denominated as cashAmount so use TOKEN_PRECISION // here instead of RATE_PRECISION return numerator.mul(Constants.INTERNAL_TOKEN_PRECISION).div(derivative); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./Market.sol"; import "./AssetRate.sol"; import "./DateTime.sol"; import "../../global/LibStorage.sol"; import "../../global/Types.sol"; import "../../global/Constants.sol"; import "../../math/SafeInt256.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library CashGroup { using SafeMath for uint256; using SafeInt256 for int256; using AssetRate for AssetRateParameters; using Market for MarketParameters; // Bit number references for each parameter in the 32 byte word (0-indexed) uint256 private constant MARKET_INDEX_BIT = 31; uint256 private constant RATE_ORACLE_TIME_WINDOW_BIT = 30; uint256 private constant TOTAL_FEE_BIT = 29; uint256 private constant RESERVE_FEE_SHARE_BIT = 28; uint256 private constant DEBT_BUFFER_BIT = 27; uint256 private constant FCASH_HAIRCUT_BIT = 26; uint256 private constant SETTLEMENT_PENALTY_BIT = 25; uint256 private constant LIQUIDATION_FCASH_HAIRCUT_BIT = 24; uint256 private constant LIQUIDATION_DEBT_BUFFER_BIT = 23; // 7 bytes allocated, one byte per market for the liquidity token haircut uint256 private constant LIQUIDITY_TOKEN_HAIRCUT_FIRST_BIT = 22; // 7 bytes allocated, one byte per market for the rate scalar uint256 private constant RATE_SCALAR_FIRST_BIT = 15; // Offsets for the bytes of the different parameters uint256 private constant MARKET_INDEX = (31 - MARKET_INDEX_BIT) * 8; uint256 private constant RATE_ORACLE_TIME_WINDOW = (31 - RATE_ORACLE_TIME_WINDOW_BIT) * 8; uint256 private constant TOTAL_FEE = (31 - TOTAL_FEE_BIT) * 8; uint256 private constant RESERVE_FEE_SHARE = (31 - RESERVE_FEE_SHARE_BIT) * 8; uint256 private constant DEBT_BUFFER = (31 - DEBT_BUFFER_BIT) * 8; uint256 private constant FCASH_HAIRCUT = (31 - FCASH_HAIRCUT_BIT) * 8; uint256 private constant SETTLEMENT_PENALTY = (31 - SETTLEMENT_PENALTY_BIT) * 8; uint256 private constant LIQUIDATION_FCASH_HAIRCUT = (31 - LIQUIDATION_FCASH_HAIRCUT_BIT) * 8; uint256 private constant LIQUIDATION_DEBT_BUFFER = (31 - LIQUIDATION_DEBT_BUFFER_BIT) * 8; uint256 private constant LIQUIDITY_TOKEN_HAIRCUT = (31 - LIQUIDITY_TOKEN_HAIRCUT_FIRST_BIT) * 8; uint256 private constant RATE_SCALAR = (31 - RATE_SCALAR_FIRST_BIT) * 8; /// @notice Returns the rate scalar scaled by time to maturity. The rate scalar multiplies /// the ln() portion of the liquidity curve as an inverse so it increases with time to /// maturity. The effect of the rate scalar on slippage must decrease with time to maturity. function getRateScalar( CashGroupParameters memory cashGroup, uint256 marketIndex, uint256 timeToMaturity ) internal pure returns (int256) { require(1 <= marketIndex && marketIndex <= cashGroup.maxMarketIndex); // dev: invalid market index uint256 offset = RATE_SCALAR + 8 * (marketIndex - 1); int256 scalar = int256(uint8(uint256(cashGroup.data >> offset))) * Constants.RATE_PRECISION; int256 rateScalar = scalar.mul(int256(Constants.IMPLIED_RATE_TIME)).div(SafeInt256.toInt(timeToMaturity)); // Rate scalar is denominated in RATE_PRECISION, it is unlikely to underflow in the // division above. require(rateScalar > 0); // dev: rate scalar underflow return rateScalar; } /// @notice Haircut on liquidity tokens to account for the risk associated with changes in the /// proportion of cash to fCash within the pool. This is set as a percentage less than or equal to 100. function getLiquidityHaircut(CashGroupParameters memory cashGroup, uint256 assetType) internal pure returns (uint8) { require( Constants.MIN_LIQUIDITY_TOKEN_INDEX <= assetType && assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX ); // dev: liquidity haircut invalid asset type uint256 offset = LIQUIDITY_TOKEN_HAIRCUT + 8 * (assetType - Constants.MIN_LIQUIDITY_TOKEN_INDEX); return uint8(uint256(cashGroup.data >> offset)); } /// @notice Total trading fee denominated in RATE_PRECISION with basis point increments function getTotalFee(CashGroupParameters memory cashGroup) internal pure returns (uint256) { return uint256(uint8(uint256(cashGroup.data >> TOTAL_FEE))) * Constants.BASIS_POINT; } /// @notice Percentage of the total trading fee that goes to the reserve function getReserveFeeShare(CashGroupParameters memory cashGroup) internal pure returns (int256) { return uint8(uint256(cashGroup.data >> RESERVE_FEE_SHARE)); } /// @notice fCash haircut for valuation denominated in rate precision with five basis point increments function getfCashHaircut(CashGroupParameters memory cashGroup) internal pure returns (uint256) { return uint256(uint8(uint256(cashGroup.data >> FCASH_HAIRCUT))) * Constants.FIVE_BASIS_POINTS; } /// @notice fCash debt buffer for valuation denominated in rate precision with five basis point increments function getDebtBuffer(CashGroupParameters memory cashGroup) internal pure returns (uint256) { return uint256(uint8(uint256(cashGroup.data >> DEBT_BUFFER))) * Constants.FIVE_BASIS_POINTS; } /// @notice Time window factor for the rate oracle denominated in seconds with five minute increments. function getRateOracleTimeWindow(CashGroupParameters memory cashGroup) internal pure returns (uint256) { // This is denominated in 5 minute increments in storage return uint256(uint8(uint256(cashGroup.data >> RATE_ORACLE_TIME_WINDOW))) * Constants.FIVE_MINUTES; } /// @notice Penalty rate for settling cash debts denominated in basis points function getSettlementPenalty(CashGroupParameters memory cashGroup) internal pure returns (uint256) { return uint256(uint8(uint256(cashGroup.data >> SETTLEMENT_PENALTY))) * Constants.FIVE_BASIS_POINTS; } /// @notice Haircut for positive fCash during liquidation denominated rate precision /// with five basis point increments function getLiquidationfCashHaircut(CashGroupParameters memory cashGroup) internal pure returns (uint256) { return uint256(uint8(uint256(cashGroup.data >> LIQUIDATION_FCASH_HAIRCUT))) * Constants.FIVE_BASIS_POINTS; } /// @notice Haircut for negative fCash during liquidation denominated rate precision /// with five basis point increments function getLiquidationDebtBuffer(CashGroupParameters memory cashGroup) internal pure returns (uint256) { return uint256(uint8(uint256(cashGroup.data >> LIQUIDATION_DEBT_BUFFER))) * Constants.FIVE_BASIS_POINTS; } function loadMarket( CashGroupParameters memory cashGroup, MarketParameters memory market, uint256 marketIndex, bool needsLiquidity, uint256 blockTime ) internal view { require(1 <= marketIndex && marketIndex <= cashGroup.maxMarketIndex, "Invalid market"); uint256 maturity = DateTime.getReferenceTime(blockTime).add(DateTime.getTradedMarket(marketIndex)); market.loadMarket( cashGroup.currencyId, maturity, blockTime, needsLiquidity, getRateOracleTimeWindow(cashGroup) ); } /// @notice Returns the linear interpolation between two market rates. The formula is /// slope = (longMarket.oracleRate - shortMarket.oracleRate) / (longMarket.maturity - shortMarket.maturity) /// interpolatedRate = slope * (assetMaturity - shortMarket.maturity) + shortMarket.oracleRate function interpolateOracleRate( uint256 shortMaturity, uint256 longMaturity, uint256 shortRate, uint256 longRate, uint256 assetMaturity ) internal pure returns (uint256) { require(shortMaturity < assetMaturity); // dev: cash group interpolation error, short maturity require(assetMaturity < longMaturity); // dev: cash group interpolation error, long maturity // It's possible that the rates are inverted where the short market rate > long market rate and // we will get an underflow here so we check for that if (longRate >= shortRate) { return (longRate - shortRate) .mul(assetMaturity - shortMaturity) // No underflow here, checked above .div(longMaturity - shortMaturity) .add(shortRate); } else { // In this case the slope is negative so: // interpolatedRate = shortMarket.oracleRate - slope * (assetMaturity - shortMarket.maturity) // NOTE: this subtraction should never overflow, the linear interpolation between two points above zero // cannot go below zero return shortRate.sub( // This is reversed to keep it it positive (shortRate - longRate) .mul(assetMaturity - shortMaturity) // No underflow here, checked above .div(longMaturity - shortMaturity) ); } } /// @dev Gets an oracle rate given any valid maturity. function calculateOracleRate( CashGroupParameters memory cashGroup, uint256 maturity, uint256 blockTime ) internal view returns (uint256) { (uint256 marketIndex, bool idiosyncratic) = DateTime.getMarketIndex(cashGroup.maxMarketIndex, maturity, blockTime); uint256 timeWindow = getRateOracleTimeWindow(cashGroup); if (!idiosyncratic) { return Market.getOracleRate(cashGroup.currencyId, maturity, timeWindow, blockTime); } else { uint256 referenceTime = DateTime.getReferenceTime(blockTime); // DateTime.getMarketIndex returns the market that is past the maturity if idiosyncratic uint256 longMaturity = referenceTime.add(DateTime.getTradedMarket(marketIndex)); uint256 longRate = Market.getOracleRate(cashGroup.currencyId, longMaturity, timeWindow, blockTime); uint256 shortMaturity; uint256 shortRate; if (marketIndex == 1) { // In this case the short market is the annualized asset supply rate shortMaturity = blockTime; shortRate = cashGroup.assetRate.getSupplyRate(); } else { // Minimum value for marketIndex here is 2 shortMaturity = referenceTime.add(DateTime.getTradedMarket(marketIndex - 1)); shortRate = Market.getOracleRate( cashGroup.currencyId, shortMaturity, timeWindow, blockTime ); } return interpolateOracleRate(shortMaturity, longMaturity, shortRate, longRate, maturity); } } function _getCashGroupStorageBytes(uint256 currencyId) private view returns (bytes32 data) { mapping(uint256 => bytes32) storage store = LibStorage.getCashGroupStorage(); return store[currencyId]; } /// @dev Helper method for validating maturities in ERC1155Action function getMaxMarketIndex(uint256 currencyId) internal view returns (uint8) { bytes32 data = _getCashGroupStorageBytes(currencyId); return uint8(data[MARKET_INDEX_BIT]); } /// @notice Checks all cash group settings for invalid values and sets them into storage function setCashGroupStorage(uint256 currencyId, CashGroupSettings calldata cashGroup) internal { // Due to the requirements of the yield curve we do not allow a cash group to have solely a 3 month market. // The reason is that borrowers will not have a further maturity to roll from their 3 month fixed to a 6 month // fixed. It also complicates the logic in the nToken initialization method. Additionally, we cannot have cash // groups with 0 market index, it has no effect. require(2 <= cashGroup.maxMarketIndex && cashGroup.maxMarketIndex <= Constants.MAX_TRADED_MARKET_INDEX, "CG: invalid market index" ); require( cashGroup.reserveFeeShare <= Constants.PERCENTAGE_DECIMALS, "CG: invalid reserve share" ); require(cashGroup.liquidityTokenHaircuts.length == cashGroup.maxMarketIndex); require(cashGroup.rateScalars.length == cashGroup.maxMarketIndex); // This is required so that fCash liquidation can proceed correctly require(cashGroup.liquidationfCashHaircut5BPS < cashGroup.fCashHaircut5BPS); require(cashGroup.liquidationDebtBuffer5BPS < cashGroup.debtBuffer5BPS); // Market indexes cannot decrease or they will leave fCash assets stranded in the future with no valuation curve uint8 previousMaxMarketIndex = getMaxMarketIndex(currencyId); require( previousMaxMarketIndex <= cashGroup.maxMarketIndex, "CG: market index cannot decrease" ); // Per cash group settings bytes32 data = (bytes32(uint256(cashGroup.maxMarketIndex)) | (bytes32(uint256(cashGroup.rateOracleTimeWindow5Min)) << RATE_ORACLE_TIME_WINDOW) | (bytes32(uint256(cashGroup.totalFeeBPS)) << TOTAL_FEE) | (bytes32(uint256(cashGroup.reserveFeeShare)) << RESERVE_FEE_SHARE) | (bytes32(uint256(cashGroup.debtBuffer5BPS)) << DEBT_BUFFER) | (bytes32(uint256(cashGroup.fCashHaircut5BPS)) << FCASH_HAIRCUT) | (bytes32(uint256(cashGroup.settlementPenaltyRate5BPS)) << SETTLEMENT_PENALTY) | (bytes32(uint256(cashGroup.liquidationfCashHaircut5BPS)) << LIQUIDATION_FCASH_HAIRCUT) | (bytes32(uint256(cashGroup.liquidationDebtBuffer5BPS)) << LIQUIDATION_DEBT_BUFFER)); // Per market group settings for (uint256 i = 0; i < cashGroup.liquidityTokenHaircuts.length; i++) { require( cashGroup.liquidityTokenHaircuts[i] <= Constants.PERCENTAGE_DECIMALS, "CG: invalid token haircut" ); data = data | (bytes32(uint256(cashGroup.liquidityTokenHaircuts[i])) << (LIQUIDITY_TOKEN_HAIRCUT + i * 8)); } for (uint256 i = 0; i < cashGroup.rateScalars.length; i++) { // Causes a divide by zero error require(cashGroup.rateScalars[i] != 0, "CG: invalid rate scalar"); data = data | (bytes32(uint256(cashGroup.rateScalars[i])) << (RATE_SCALAR + i * 8)); } mapping(uint256 => bytes32) storage store = LibStorage.getCashGroupStorage(); store[currencyId] = data; } /// @notice Deserialize the cash group storage bytes into a user friendly object function deserializeCashGroupStorage(uint256 currencyId) internal view returns (CashGroupSettings memory) { bytes32 data = _getCashGroupStorageBytes(currencyId); uint8 maxMarketIndex = uint8(data[MARKET_INDEX_BIT]); uint8[] memory tokenHaircuts = new uint8[](uint256(maxMarketIndex)); uint8[] memory rateScalars = new uint8[](uint256(maxMarketIndex)); for (uint8 i = 0; i < maxMarketIndex; i++) { tokenHaircuts[i] = uint8(data[LIQUIDITY_TOKEN_HAIRCUT_FIRST_BIT - i]); rateScalars[i] = uint8(data[RATE_SCALAR_FIRST_BIT - i]); } return CashGroupSettings({ maxMarketIndex: maxMarketIndex, rateOracleTimeWindow5Min: uint8(data[RATE_ORACLE_TIME_WINDOW_BIT]), totalFeeBPS: uint8(data[TOTAL_FEE_BIT]), reserveFeeShare: uint8(data[RESERVE_FEE_SHARE_BIT]), debtBuffer5BPS: uint8(data[DEBT_BUFFER_BIT]), fCashHaircut5BPS: uint8(data[FCASH_HAIRCUT_BIT]), settlementPenaltyRate5BPS: uint8(data[SETTLEMENT_PENALTY_BIT]), liquidationfCashHaircut5BPS: uint8(data[LIQUIDATION_FCASH_HAIRCUT_BIT]), liquidationDebtBuffer5BPS: uint8(data[LIQUIDATION_DEBT_BUFFER_BIT]), liquidityTokenHaircuts: tokenHaircuts, rateScalars: rateScalars }); } function _buildCashGroup(uint16 currencyId, AssetRateParameters memory assetRate) private view returns (CashGroupParameters memory) { bytes32 data = _getCashGroupStorageBytes(currencyId); uint256 maxMarketIndex = uint8(data[MARKET_INDEX_BIT]); return CashGroupParameters({ currencyId: currencyId, maxMarketIndex: maxMarketIndex, assetRate: assetRate, data: data }); } /// @notice Builds a cash group using a view version of the asset rate function buildCashGroupView(uint16 currencyId) internal view returns (CashGroupParameters memory) { AssetRateParameters memory assetRate = AssetRate.buildAssetRateView(currencyId); return _buildCashGroup(currencyId, assetRate); } /// @notice Builds a cash group using a stateful version of the asset rate function buildCashGroupStateful(uint16 currencyId) internal returns (CashGroupParameters memory) { AssetRateParameters memory assetRate = AssetRate.buildAssetRateStateful(currencyId); return _buildCashGroup(currencyId, assetRate); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../../global/Types.sol"; import "../../global/LibStorage.sol"; import "../../global/Constants.sol"; import "../../math/SafeInt256.sol"; import "../../../interfaces/notional/AssetRateAdapter.sol"; library AssetRate { using SafeInt256 for int256; event SetSettlementRate(uint256 indexed currencyId, uint256 indexed maturity, uint128 rate); // Asset rates are in 1e18 decimals (cToken exchange rates), internal balances // are in 1e8 decimals. Therefore we leave this as 1e18 / 1e8 = 1e10 int256 private constant ASSET_RATE_DECIMAL_DIFFERENCE = 1e10; /// @notice Converts an internal asset cash value to its underlying token value. /// @param ar exchange rate object between asset and underlying /// @param assetBalance amount to convert to underlying function convertToUnderlying(AssetRateParameters memory ar, int256 assetBalance) internal pure returns (int256) { // Calculation here represents: // rate * balance * internalPrecision / rateDecimals * underlyingPrecision int256 underlyingBalance = ar.rate .mul(assetBalance) .div(ASSET_RATE_DECIMAL_DIFFERENCE) .div(ar.underlyingDecimals); return underlyingBalance; } /// @notice Converts an internal underlying cash value to its asset cash value /// @param ar exchange rate object between asset and underlying /// @param underlyingBalance amount to convert to asset cash, denominated in internal token precision function convertFromUnderlying(AssetRateParameters memory ar, int256 underlyingBalance) internal pure returns (int256) { // Calculation here represents: // rateDecimals * balance * underlyingPrecision / rate * internalPrecision int256 assetBalance = underlyingBalance .mul(ASSET_RATE_DECIMAL_DIFFERENCE) .mul(ar.underlyingDecimals) .div(ar.rate); return assetBalance; } /// @notice Returns the current per block supply rate, is used when calculating oracle rates /// for idiosyncratic fCash with a shorter duration than the 3 month maturity. function getSupplyRate(AssetRateParameters memory ar) internal view returns (uint256) { // If the rate oracle is not set, the asset is not interest bearing and has an oracle rate of zero. if (address(ar.rateOracle) == address(0)) return 0; uint256 rate = ar.rateOracle.getAnnualizedSupplyRate(); // Zero supply rate is valid since this is an interest rate, we do not divide by // the supply rate so we do not get div by zero errors. require(rate >= 0); // dev: invalid supply rate return rate; } function _getAssetRateStorage(uint256 currencyId) private view returns (AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) { mapping(uint256 => AssetRateStorage) storage store = LibStorage.getAssetRateStorage(); AssetRateStorage storage ar = store[currencyId]; rateOracle = AssetRateAdapter(ar.rateOracle); underlyingDecimalPlaces = ar.underlyingDecimalPlaces; } /// @notice Gets an asset rate using a view function, does not accrue interest so the /// exchange rate will not be up to date. Should only be used for non-stateful methods function _getAssetRateView(uint256 currencyId) private view returns ( int256, AssetRateAdapter, uint8 ) { (AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) = _getAssetRateStorage(currencyId); int256 rate; if (address(rateOracle) == address(0)) { // If no rate oracle is set, then set this to the identity rate = ASSET_RATE_DECIMAL_DIFFERENCE; // This will get raised to 10^x and return 1, will not end up with div by zero underlyingDecimalPlaces = 0; } else { rate = rateOracle.getExchangeRateView(); require(rate > 0); // dev: invalid exchange rate } return (rate, rateOracle, underlyingDecimalPlaces); } /// @notice Gets an asset rate using a stateful function, accrues interest so the /// exchange rate will be up to date for the current block. function _getAssetRateStateful(uint256 currencyId) private returns ( int256, AssetRateAdapter, uint8 ) { (AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) = _getAssetRateStorage(currencyId); int256 rate; if (address(rateOracle) == address(0)) { // If no rate oracle is set, then set this to the identity rate = ASSET_RATE_DECIMAL_DIFFERENCE; // This will get raised to 10^x and return 1, will not end up with div by zero underlyingDecimalPlaces = 0; } else { rate = rateOracle.getExchangeRateStateful(); require(rate > 0); // dev: invalid exchange rate } return (rate, rateOracle, underlyingDecimalPlaces); } /// @notice Returns an asset rate object using the view method function buildAssetRateView(uint256 currencyId) internal view returns (AssetRateParameters memory) { (int256 rate, AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) = _getAssetRateView(currencyId); return AssetRateParameters({ rateOracle: rateOracle, rate: rate, // No overflow, restricted on storage underlyingDecimals: int256(10**underlyingDecimalPlaces) }); } /// @notice Returns an asset rate object using the stateful method function buildAssetRateStateful(uint256 currencyId) internal returns (AssetRateParameters memory) { (int256 rate, AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) = _getAssetRateStateful(currencyId); return AssetRateParameters({ rateOracle: rateOracle, rate: rate, // No overflow, restricted on storage underlyingDecimals: int256(10**underlyingDecimalPlaces) }); } /// @dev Gets a settlement rate object function _getSettlementRateStorage(uint256 currencyId, uint256 maturity) private view returns ( int256 settlementRate, uint8 underlyingDecimalPlaces ) { mapping(uint256 => mapping(uint256 => SettlementRateStorage)) storage store = LibStorage.getSettlementRateStorage(); SettlementRateStorage storage rateStorage = store[currencyId][maturity]; settlementRate = rateStorage.settlementRate; underlyingDecimalPlaces = rateStorage.underlyingDecimalPlaces; } /// @notice Returns a settlement rate object using the view method function buildSettlementRateView(uint256 currencyId, uint256 maturity) internal view returns (AssetRateParameters memory) { // prettier-ignore ( int256 settlementRate, uint8 underlyingDecimalPlaces ) = _getSettlementRateStorage(currencyId, maturity); // Asset exchange rates cannot be zero if (settlementRate == 0) { // If settlement rate has not been set then we need to fetch it // prettier-ignore ( settlementRate, /* address */, underlyingDecimalPlaces ) = _getAssetRateView(currencyId); } return AssetRateParameters( AssetRateAdapter(address(0)), settlementRate, // No overflow, restricted on storage int256(10**underlyingDecimalPlaces) ); } /// @notice Returns a settlement rate object and sets the rate if it has not been set yet function buildSettlementRateStateful( uint256 currencyId, uint256 maturity, uint256 blockTime ) internal returns (AssetRateParameters memory) { (int256 settlementRate, uint8 underlyingDecimalPlaces) = _getSettlementRateStorage(currencyId, maturity); if (settlementRate == 0) { // Settlement rate has not yet been set, set it in this branch AssetRateAdapter rateOracle; // If rate oracle == 0 then this will return the identity settlement rate // prettier-ignore ( settlementRate, rateOracle, underlyingDecimalPlaces ) = _getAssetRateStateful(currencyId); if (address(rateOracle) != address(0)) { mapping(uint256 => mapping(uint256 => SettlementRateStorage)) storage store = LibStorage.getSettlementRateStorage(); // Only need to set settlement rates when the rate oracle is set (meaning the asset token has // a conversion rate to an underlying). If not set then the asset cash always settles to underlying at a 1-1 // rate since they are the same. require(0 < blockTime && maturity <= blockTime && blockTime <= type(uint40).max); // dev: settlement rate timestamp overflow require(0 < settlementRate && settlementRate <= type(uint128).max); // dev: settlement rate overflow SettlementRateStorage storage rateStorage = store[currencyId][maturity]; rateStorage.blockTime = uint40(blockTime); rateStorage.settlementRate = uint128(settlementRate); rateStorage.underlyingDecimalPlaces = underlyingDecimalPlaces; emit SetSettlementRate(currencyId, maturity, uint128(settlementRate)); } } return AssetRateParameters( AssetRateAdapter(address(0)), settlementRate, // No overflow, restricted on storage int256(10**underlyingDecimalPlaces) ); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./Incentives.sol"; import "./TokenHandler.sol"; import "../AccountContextHandler.sol"; import "../../global/Types.sol"; import "../../global/Constants.sol"; import "../../math/SafeInt256.sol"; import "../../math/FloatingPoint56.sol"; library BalanceHandler { using SafeInt256 for int256; using TokenHandler for Token; using AssetRate for AssetRateParameters; using AccountContextHandler for AccountContext; /// @notice Emitted when a cash balance changes event CashBalanceChange(address indexed account, uint16 indexed currencyId, int256 netCashChange); /// @notice Emitted when nToken supply changes (not the same as transfers) event nTokenSupplyChange(address indexed account, uint16 indexed currencyId, int256 tokenSupplyChange); /// @notice Emitted when reserve fees are accrued event ReserveFeeAccrued(uint16 indexed currencyId, int256 fee); /// @notice Emitted when reserve balance is updated event ReserveBalanceUpdated(uint16 indexed currencyId, int256 newBalance); /// @notice Emitted when reserve balance is harvested event ExcessReserveBalanceHarvested(uint16 indexed currencyId, int256 harvestAmount); /// @notice Deposits asset tokens into an account /// @dev Handles two special cases when depositing tokens into an account. /// - If a token has transfer fees then the amount specified does not equal the amount that the contract /// will receive. Complete the deposit here rather than in finalize so that the contract has the correct /// balance to work with. /// - Force a transfer before finalize to allow a different account to deposit into an account /// @return assetAmountInternal which is the converted asset amount accounting for transfer fees function depositAssetToken( BalanceState memory balanceState, address account, int256 assetAmountExternal, bool forceTransfer ) internal returns (int256 assetAmountInternal) { if (assetAmountExternal == 0) return 0; require(assetAmountExternal > 0); // dev: deposit asset token amount negative Token memory token = TokenHandler.getAssetToken(balanceState.currencyId); if (token.tokenType == TokenType.aToken) { // Handles special accounting requirements for aTokens assetAmountExternal = AaveHandler.convertToScaledBalanceExternal( balanceState.currencyId, assetAmountExternal ); } // Force transfer is used to complete the transfer before going to finalize if (token.hasTransferFee || forceTransfer) { // If the token has a transfer fee the deposit amount may not equal the actual amount // that the contract will receive. We handle the deposit here and then update the netCashChange // accordingly which is denominated in internal precision. int256 assetAmountExternalPrecisionFinal = token.transfer(account, balanceState.currencyId, assetAmountExternal); // Convert the external precision to internal, it's possible that we lose dust amounts here but // this is unavoidable because we do not know how transfer fees are calculated. assetAmountInternal = token.convertToInternal(assetAmountExternalPrecisionFinal); // Transfer has been called balanceState.netCashChange = balanceState.netCashChange.add(assetAmountInternal); return assetAmountInternal; } else { assetAmountInternal = token.convertToInternal(assetAmountExternal); // Otherwise add the asset amount here. It may be net off later and we want to only do // a single transfer during the finalize method. Use internal precision to ensure that internal accounting // and external account remain in sync. // Transfer will be deferred balanceState.netAssetTransferInternalPrecision = balanceState .netAssetTransferInternalPrecision .add(assetAmountInternal); // Returns the converted assetAmountExternal to the internal amount return assetAmountInternal; } } /// @notice Handle deposits of the underlying token /// @dev In this case we must wrap the underlying token into an asset token, ensuring that we do not end up /// with any underlying tokens left as dust on the contract. function depositUnderlyingToken( BalanceState memory balanceState, address account, int256 underlyingAmountExternal ) internal returns (int256) { if (underlyingAmountExternal == 0) return 0; require(underlyingAmountExternal > 0); // dev: deposit underlying token negative Token memory underlyingToken = TokenHandler.getUnderlyingToken(balanceState.currencyId); // This is the exact amount of underlying tokens the account has in external precision. if (underlyingToken.tokenType == TokenType.Ether) { // Underflow checked above require(uint256(underlyingAmountExternal) == msg.value, "ETH Balance"); } else { underlyingAmountExternal = underlyingToken.transfer(account, balanceState.currencyId, underlyingAmountExternal); } Token memory assetToken = TokenHandler.getAssetToken(balanceState.currencyId); int256 assetTokensReceivedExternalPrecision = assetToken.mint(balanceState.currencyId, SafeInt256.toUint(underlyingAmountExternal)); // cTokens match INTERNAL_TOKEN_PRECISION so this will short circuit but we leave this here in case a different // type of asset token is listed in the future. It's possible if those tokens have a different precision dust may // accrue but that is not relevant now. int256 assetTokensReceivedInternal = assetToken.convertToInternal(assetTokensReceivedExternalPrecision); // Transfer / mint has taken effect balanceState.netCashChange = balanceState.netCashChange.add(assetTokensReceivedInternal); return assetTokensReceivedInternal; } /// @notice Finalizes an account's balances, handling any transfer logic required /// @dev This method SHOULD NOT be used for nToken accounts, for that use setBalanceStorageForNToken /// as the nToken is limited in what types of balances it can hold. function finalize( BalanceState memory balanceState, address account, AccountContext memory accountContext, bool redeemToUnderlying ) internal returns (int256 transferAmountExternal) { bool mustUpdate; if (balanceState.netNTokenTransfer < 0) { require( balanceState.storedNTokenBalance .add(balanceState.netNTokenSupplyChange) .add(balanceState.netNTokenTransfer) >= 0, "Neg nToken" ); } if (balanceState.netAssetTransferInternalPrecision < 0) { require( balanceState.storedCashBalance .add(balanceState.netCashChange) .add(balanceState.netAssetTransferInternalPrecision) >= 0, "Neg Cash" ); } // Transfer amount is checked inside finalize transfers in case when converting to external we // round down to zero. This returns the actual net transfer in internal precision as well. ( transferAmountExternal, balanceState.netAssetTransferInternalPrecision ) = _finalizeTransfers(balanceState, account, redeemToUnderlying); // No changes to total cash after this point int256 totalCashChange = balanceState.netCashChange.add(balanceState.netAssetTransferInternalPrecision); if (totalCashChange != 0) { balanceState.storedCashBalance = balanceState.storedCashBalance.add(totalCashChange); mustUpdate = true; emit CashBalanceChange( account, uint16(balanceState.currencyId), totalCashChange ); } if (balanceState.netNTokenTransfer != 0 || balanceState.netNTokenSupplyChange != 0) { // Final nToken balance is used to calculate the account incentive debt int256 finalNTokenBalance = balanceState.storedNTokenBalance .add(balanceState.netNTokenTransfer) .add(balanceState.netNTokenSupplyChange); // The toUint() call here will ensure that nToken balances never become negative Incentives.claimIncentives(balanceState, account, finalNTokenBalance.toUint()); balanceState.storedNTokenBalance = finalNTokenBalance; if (balanceState.netNTokenSupplyChange != 0) { emit nTokenSupplyChange( account, uint16(balanceState.currencyId), balanceState.netNTokenSupplyChange ); } mustUpdate = true; } if (mustUpdate) { _setBalanceStorage( account, balanceState.currencyId, balanceState.storedCashBalance, balanceState.storedNTokenBalance, balanceState.lastClaimTime, balanceState.accountIncentiveDebt ); } accountContext.setActiveCurrency( balanceState.currencyId, // Set active currency to true if either balance is non-zero balanceState.storedCashBalance != 0 || balanceState.storedNTokenBalance != 0, Constants.ACTIVE_IN_BALANCES ); if (balanceState.storedCashBalance < 0) { // NOTE: HAS_CASH_DEBT cannot be extinguished except by a free collateral check where all balances // are examined accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_CASH_DEBT; } } /// @dev Returns the amount transferred in underlying or asset terms depending on how redeem to underlying /// is specified. function _finalizeTransfers( BalanceState memory balanceState, address account, bool redeemToUnderlying ) private returns (int256 actualTransferAmountExternal, int256 assetTransferAmountInternal) { Token memory assetToken = TokenHandler.getAssetToken(balanceState.currencyId); // Dust accrual to the protocol is possible if the token decimals is less than internal token precision. // See the comments in TokenHandler.convertToExternal and TokenHandler.convertToInternal int256 assetTransferAmountExternal = assetToken.convertToExternal(balanceState.netAssetTransferInternalPrecision); if (assetTransferAmountExternal == 0) { return (0, 0); } else if (redeemToUnderlying && assetTransferAmountExternal < 0) { // We only do the redeem to underlying if the asset transfer amount is less than zero. If it is greater than // zero then we will do a normal transfer instead. // We use the internal amount here and then scale it to the external amount so that there is // no loss of precision between our internal accounting and the external account. In this case // there will be no dust accrual in underlying tokens since we will transfer the exact amount // of underlying that was received. actualTransferAmountExternal = assetToken.redeem( balanceState.currencyId, account, // No overflow, checked above uint256(assetTransferAmountExternal.neg()) ); // In this case we're transferring underlying tokens, we want to convert the internal // asset transfer amount to store in cash balances assetTransferAmountInternal = assetToken.convertToInternal(assetTransferAmountExternal); } else { // NOTE: in the case of aTokens assetTransferAmountExternal is the scaledBalanceOf in external precision, it // will be converted to balanceOf denomination inside transfer actualTransferAmountExternal = assetToken.transfer(account, balanceState.currencyId, assetTransferAmountExternal); // Convert the actual transferred amount assetTransferAmountInternal = assetToken.convertToInternal(actualTransferAmountExternal); } } /// @notice Special method for settling negative current cash debts. This occurs when an account /// has a negative fCash balance settle to cash. A settler may come and force the account to borrow /// at the prevailing 3 month rate /// @dev Use this method to avoid any nToken and transfer logic in finalize which is unnecessary. function setBalanceStorageForSettleCashDebt( address account, CashGroupParameters memory cashGroup, int256 amountToSettleAsset, AccountContext memory accountContext ) internal returns (int256) { require(amountToSettleAsset >= 0); // dev: amount to settle negative (int256 cashBalance, int256 nTokenBalance, uint256 lastClaimTime, uint256 accountIncentiveDebt) = getBalanceStorage(account, cashGroup.currencyId); // Prevents settlement of positive balances require(cashBalance < 0, "Invalid settle balance"); if (amountToSettleAsset == 0) { // Symbolizes that the entire debt should be settled amountToSettleAsset = cashBalance.neg(); cashBalance = 0; } else { // A partial settlement of the debt require(amountToSettleAsset <= cashBalance.neg(), "Invalid amount to settle"); cashBalance = cashBalance.add(amountToSettleAsset); } // NOTE: we do not update HAS_CASH_DEBT here because it is possible that the other balances // also have cash debts if (cashBalance == 0 && nTokenBalance == 0) { accountContext.setActiveCurrency( cashGroup.currencyId, false, Constants.ACTIVE_IN_BALANCES ); } _setBalanceStorage( account, cashGroup.currencyId, cashBalance, nTokenBalance, lastClaimTime, accountIncentiveDebt ); // Emit the event here, we do not call finalize emit CashBalanceChange(account, cashGroup.currencyId, amountToSettleAsset); return amountToSettleAsset; } /** * @notice A special balance storage method for fCash liquidation to reduce the bytecode size. */ function setBalanceStorageForfCashLiquidation( address account, AccountContext memory accountContext, uint16 currencyId, int256 netCashChange ) internal { (int256 cashBalance, int256 nTokenBalance, uint256 lastClaimTime, uint256 accountIncentiveDebt) = getBalanceStorage(account, currencyId); int256 newCashBalance = cashBalance.add(netCashChange); // If a cash balance is negative already we cannot put an account further into debt. In this case // the netCashChange must be positive so that it is coming out of debt. if (newCashBalance < 0) { require(netCashChange > 0, "Neg Cash"); // NOTE: HAS_CASH_DEBT cannot be extinguished except by a free collateral check // where all balances are examined. In this case the has cash debt flag should // already be set (cash balances cannot get more negative) but we do it again // here just to be safe. accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_CASH_DEBT; } bool isActive = newCashBalance != 0 || nTokenBalance != 0; accountContext.setActiveCurrency(currencyId, isActive, Constants.ACTIVE_IN_BALANCES); // Emit the event here, we do not call finalize emit CashBalanceChange(account, currencyId, netCashChange); _setBalanceStorage( account, currencyId, newCashBalance, nTokenBalance, lastClaimTime, accountIncentiveDebt ); } /// @notice Helper method for settling the output of the SettleAssets method function finalizeSettleAmounts( address account, AccountContext memory accountContext, SettleAmount[] memory settleAmounts ) internal { for (uint256 i = 0; i < settleAmounts.length; i++) { SettleAmount memory amt = settleAmounts[i]; if (amt.netCashChange == 0) continue; ( int256 cashBalance, int256 nTokenBalance, uint256 lastClaimTime, uint256 accountIncentiveDebt ) = getBalanceStorage(account, amt.currencyId); cashBalance = cashBalance.add(amt.netCashChange); accountContext.setActiveCurrency( amt.currencyId, cashBalance != 0 || nTokenBalance != 0, Constants.ACTIVE_IN_BALANCES ); if (cashBalance < 0) { accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_CASH_DEBT; } emit CashBalanceChange( account, uint16(amt.currencyId), amt.netCashChange ); _setBalanceStorage( account, amt.currencyId, cashBalance, nTokenBalance, lastClaimTime, accountIncentiveDebt ); } } /// @notice Special method for setting balance storage for nToken function setBalanceStorageForNToken( address nTokenAddress, uint256 currencyId, int256 cashBalance ) internal { require(cashBalance >= 0); // dev: invalid nToken cash balance _setBalanceStorage(nTokenAddress, currencyId, cashBalance, 0, 0, 0); } /// @notice increments fees to the reserve function incrementFeeToReserve(uint256 currencyId, int256 fee) internal { require(fee >= 0); // dev: invalid fee // prettier-ignore (int256 totalReserve, /* */, /* */, /* */) = getBalanceStorage(Constants.RESERVE, currencyId); totalReserve = totalReserve.add(fee); _setBalanceStorage(Constants.RESERVE, currencyId, totalReserve, 0, 0, 0); emit ReserveFeeAccrued(uint16(currencyId), fee); } /// @notice harvests excess reserve balance function harvestExcessReserveBalance(uint16 currencyId, int256 reserve, int256 assetInternalRedeemAmount) internal { // parameters are validated by the caller reserve = reserve.subNoNeg(assetInternalRedeemAmount); _setBalanceStorage(Constants.RESERVE, currencyId, reserve, 0, 0, 0); emit ExcessReserveBalanceHarvested(currencyId, assetInternalRedeemAmount); } /// @notice sets the reserve balance, see TreasuryAction.setReserveCashBalance function setReserveCashBalance(uint16 currencyId, int256 newBalance) internal { require(newBalance >= 0); // dev: invalid balance _setBalanceStorage(Constants.RESERVE, currencyId, newBalance, 0, 0, 0); emit ReserveBalanceUpdated(currencyId, newBalance); } /// @notice Sets internal balance storage. function _setBalanceStorage( address account, uint256 currencyId, int256 cashBalance, int256 nTokenBalance, uint256 lastClaimTime, uint256 accountIncentiveDebt ) private { mapping(address => mapping(uint256 => BalanceStorage)) storage store = LibStorage.getBalanceStorage(); BalanceStorage storage balanceStorage = store[account][currencyId]; require(cashBalance >= type(int88).min && cashBalance <= type(int88).max); // dev: stored cash balance overflow // Allows for 12 quadrillion nToken balance in 1e8 decimals before overflow require(nTokenBalance >= 0 && nTokenBalance <= type(uint80).max); // dev: stored nToken balance overflow if (lastClaimTime == 0) { // In this case the account has migrated and we set the accountIncentiveDebt // The maximum NOTE supply is 100_000_000e8 (1e16) which is less than 2^56 (7.2e16) so we should never // encounter an overflow for accountIncentiveDebt require(accountIncentiveDebt <= type(uint56).max); // dev: account incentive debt overflow balanceStorage.accountIncentiveDebt = uint56(accountIncentiveDebt); } else { // In this case the last claim time has not changed and we do not update the last integral supply // (stored in the accountIncentiveDebt position) require(lastClaimTime == balanceStorage.lastClaimTime); } balanceStorage.lastClaimTime = uint32(lastClaimTime); balanceStorage.nTokenBalance = uint80(nTokenBalance); balanceStorage.cashBalance = int88(cashBalance); } /// @notice Gets internal balance storage, nTokens are stored alongside cash balances function getBalanceStorage(address account, uint256 currencyId) internal view returns ( int256 cashBalance, int256 nTokenBalance, uint256 lastClaimTime, uint256 accountIncentiveDebt ) { mapping(address => mapping(uint256 => BalanceStorage)) storage store = LibStorage.getBalanceStorage(); BalanceStorage storage balanceStorage = store[account][currencyId]; nTokenBalance = balanceStorage.nTokenBalance; lastClaimTime = balanceStorage.lastClaimTime; if (lastClaimTime > 0) { // NOTE: this is only necessary to support the deprecated integral supply values, which are stored // in the accountIncentiveDebt slot accountIncentiveDebt = FloatingPoint56.unpackFrom56Bits(balanceStorage.accountIncentiveDebt); } else { accountIncentiveDebt = balanceStorage.accountIncentiveDebt; } cashBalance = balanceStorage.cashBalance; } /// @notice Loads a balance state memory object /// @dev Balance state objects occupy a lot of memory slots, so this method allows /// us to reuse them if possible function loadBalanceState( BalanceState memory balanceState, address account, uint16 currencyId, AccountContext memory accountContext ) internal view { require(0 < currencyId && currencyId <= Constants.MAX_CURRENCIES); // dev: invalid currency id balanceState.currencyId = currencyId; if (accountContext.isActiveInBalances(currencyId)) { ( balanceState.storedCashBalance, balanceState.storedNTokenBalance, balanceState.lastClaimTime, balanceState.accountIncentiveDebt ) = getBalanceStorage(account, currencyId); } else { balanceState.storedCashBalance = 0; balanceState.storedNTokenBalance = 0; balanceState.lastClaimTime = 0; balanceState.accountIncentiveDebt = 0; } balanceState.netCashChange = 0; balanceState.netAssetTransferInternalPrecision = 0; balanceState.netNTokenTransfer = 0; balanceState.netNTokenSupplyChange = 0; } /// @notice Used when manually claiming incentives in nTokenAction. Also sets the balance state /// to storage to update the accountIncentiveDebt. lastClaimTime will be set to zero as accounts /// are migrated to the new incentive calculation function claimIncentivesManual(BalanceState memory balanceState, address account) internal returns (uint256 incentivesClaimed) { incentivesClaimed = Incentives.claimIncentives( balanceState, account, balanceState.storedNTokenBalance.toUint() ); _setBalanceStorage( account, balanceState.currencyId, balanceState.storedCashBalance, balanceState.storedNTokenBalance, balanceState.lastClaimTime, balanceState.accountIncentiveDebt ); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./TransferAssets.sol"; import "../valuation/AssetHandler.sol"; import "../../math/SafeInt256.sol"; import "../../global/LibStorage.sol"; /// @notice Handles the management of an array of assets including reading from storage, inserting /// updating, deleting and writing back to storage. library PortfolioHandler { using SafeInt256 for int256; using AssetHandler for PortfolioAsset; // Mirror of LibStorage.MAX_PORTFOLIO_ASSETS uint256 private constant MAX_PORTFOLIO_ASSETS = 16; /// @notice Primarily used by the TransferAssets library function addMultipleAssets(PortfolioState memory portfolioState, PortfolioAsset[] memory assets) internal pure { for (uint256 i = 0; i < assets.length; i++) { PortfolioAsset memory asset = assets[i]; if (asset.notional == 0) continue; addAsset( portfolioState, asset.currencyId, asset.maturity, asset.assetType, asset.notional ); } } function _mergeAssetIntoArray( PortfolioAsset[] memory assetArray, uint256 currencyId, uint256 maturity, uint256 assetType, int256 notional ) private pure returns (bool) { for (uint256 i = 0; i < assetArray.length; i++) { PortfolioAsset memory asset = assetArray[i]; if ( asset.assetType != assetType || asset.currencyId != currencyId || asset.maturity != maturity ) continue; // Either of these storage states mean that some error in logic has occurred, we cannot // store this portfolio require( asset.storageState != AssetStorageState.Delete && asset.storageState != AssetStorageState.RevertIfStored ); // dev: portfolio handler deleted storage int256 newNotional = asset.notional.add(notional); // Liquidity tokens cannot be reduced below zero. if (AssetHandler.isLiquidityToken(assetType)) { require(newNotional >= 0); // dev: portfolio handler negative liquidity token balance } require(newNotional >= type(int88).min && newNotional <= type(int88).max); // dev: portfolio handler notional overflow asset.notional = newNotional; asset.storageState = AssetStorageState.Update; return true; } return false; } /// @notice Adds an asset to a portfolio state in memory (does not write to storage) /// @dev Ensures that only one version of an asset exists in a portfolio (i.e. does not allow two fCash assets of the same maturity /// to exist in a single portfolio). Also ensures that liquidity tokens do not have a negative notional. function addAsset( PortfolioState memory portfolioState, uint256 currencyId, uint256 maturity, uint256 assetType, int256 notional ) internal pure { if ( // Will return true if merged _mergeAssetIntoArray( portfolioState.storedAssets, currencyId, maturity, assetType, notional ) ) return; if (portfolioState.lastNewAssetIndex > 0) { bool merged = _mergeAssetIntoArray( portfolioState.newAssets, currencyId, maturity, assetType, notional ); if (merged) return; } // At this point if we have not merged the asset then append to the array // Cannot remove liquidity that the portfolio does not have if (AssetHandler.isLiquidityToken(assetType)) { require(notional >= 0); // dev: portfolio handler negative liquidity token balance } require(notional >= type(int88).min && notional <= type(int88).max); // dev: portfolio handler notional overflow // Need to provision a new array at this point if (portfolioState.lastNewAssetIndex == portfolioState.newAssets.length) { portfolioState.newAssets = _extendNewAssetArray(portfolioState.newAssets); } // Otherwise add to the new assets array. It should not be possible to add matching assets in a single transaction, we will // check this again when we write to storage. Assigning to memory directly here, do not allocate new memory via struct. PortfolioAsset memory newAsset = portfolioState.newAssets[portfolioState.lastNewAssetIndex]; newAsset.currencyId = currencyId; newAsset.maturity = maturity; newAsset.assetType = assetType; newAsset.notional = notional; newAsset.storageState = AssetStorageState.NoChange; portfolioState.lastNewAssetIndex += 1; } /// @dev Extends the new asset array if it is not large enough, this is likely to get a bit expensive if we do /// it too much function _extendNewAssetArray(PortfolioAsset[] memory newAssets) private pure returns (PortfolioAsset[] memory) { // Double the size of the new asset array every time we have to extend to reduce the number of times // that we have to extend it. This will go: 0, 1, 2, 4, 8 (probably stops there). uint256 newLength = newAssets.length == 0 ? 1 : newAssets.length * 2; PortfolioAsset[] memory extendedArray = new PortfolioAsset[](newLength); for (uint256 i = 0; i < newAssets.length; i++) { extendedArray[i] = newAssets[i]; } return extendedArray; } /// @notice Takes a portfolio state and writes it to storage. /// @dev This method should only be called directly by the nToken. Account updates to portfolios should happen via /// the storeAssetsAndUpdateContext call in the AccountContextHandler.sol library. /// @return updated variables to update the account context with /// hasDebt: whether or not the portfolio has negative fCash assets /// portfolioActiveCurrencies: a byte32 word with all the currencies in the portfolio /// uint8: the length of the storage array /// uint40: the new nextSettleTime for the portfolio function storeAssets(PortfolioState memory portfolioState, address account) internal returns ( bool, bytes32, uint8, uint40 ) { bool hasDebt; // NOTE: cannot have more than 16 assets or this byte object will overflow. Max assets is // set to 7 and the worst case during liquidation would be 7 liquidity tokens that generate // 7 additional fCash assets for a total of 14 assets. Although even in this case all assets // would be of the same currency so it would not change the end result of the active currency // calculation. bytes32 portfolioActiveCurrencies; uint256 nextSettleTime; for (uint256 i = 0; i < portfolioState.storedAssets.length; i++) { PortfolioAsset memory asset = portfolioState.storedAssets[i]; // NOTE: this is to prevent the storage of assets that have been modified in the AssetHandler // during valuation. require(asset.storageState != AssetStorageState.RevertIfStored); // Mark any zero notional assets as deleted if (asset.storageState != AssetStorageState.Delete && asset.notional == 0) { deleteAsset(portfolioState, i); } } // First delete assets from asset storage to maintain asset storage indexes for (uint256 i = 0; i < portfolioState.storedAssets.length; i++) { PortfolioAsset memory asset = portfolioState.storedAssets[i]; if (asset.storageState == AssetStorageState.Delete) { // Delete asset from storage uint256 currentSlot = asset.storageSlot; assembly { sstore(currentSlot, 0x00) } } else { if (asset.storageState == AssetStorageState.Update) { PortfolioAssetStorage storage assetStorage; uint256 currentSlot = asset.storageSlot; assembly { assetStorage.slot := currentSlot } _storeAsset(asset, assetStorage); } // Update portfolio context for every asset that is in storage, whether it is // updated in storage or not. (hasDebt, portfolioActiveCurrencies, nextSettleTime) = _updatePortfolioContext( asset, hasDebt, portfolioActiveCurrencies, nextSettleTime ); } } // Add new assets uint256 assetStorageLength = portfolioState.storedAssetLength; mapping(address => PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS]) storage store = LibStorage.getPortfolioArrayStorage(); PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS] storage storageArray = store[account]; for (uint256 i = 0; i < portfolioState.newAssets.length; i++) { PortfolioAsset memory asset = portfolioState.newAssets[i]; if (asset.notional == 0) continue; require( asset.storageState != AssetStorageState.Delete && asset.storageState != AssetStorageState.RevertIfStored ); // dev: store assets deleted storage (hasDebt, portfolioActiveCurrencies, nextSettleTime) = _updatePortfolioContext( asset, hasDebt, portfolioActiveCurrencies, nextSettleTime ); _storeAsset(asset, storageArray[assetStorageLength]); assetStorageLength += 1; } // 16 is the maximum number of assets or portfolio active currencies will overflow at 32 bytes with // 2 bytes per currency require(assetStorageLength <= 16 && nextSettleTime <= type(uint40).max); // dev: portfolio return value overflow return ( hasDebt, portfolioActiveCurrencies, uint8(assetStorageLength), uint40(nextSettleTime) ); } /// @notice Updates context information during the store assets method function _updatePortfolioContext( PortfolioAsset memory asset, bool hasDebt, bytes32 portfolioActiveCurrencies, uint256 nextSettleTime ) private pure returns ( bool, bytes32, uint256 ) { uint256 settlementDate = asset.getSettlementDate(); // Tis will set it to the minimum settlement date if (nextSettleTime == 0 || nextSettleTime > settlementDate) { nextSettleTime = settlementDate; } hasDebt = hasDebt || asset.notional < 0; require(uint16(uint256(portfolioActiveCurrencies)) == 0); // dev: portfolio active currencies overflow portfolioActiveCurrencies = (portfolioActiveCurrencies >> 16) | (bytes32(asset.currencyId) << 240); return (hasDebt, portfolioActiveCurrencies, nextSettleTime); } /// @dev Encodes assets for storage function _storeAsset( PortfolioAsset memory asset, PortfolioAssetStorage storage assetStorage ) internal { require(0 < asset.currencyId && asset.currencyId <= Constants.MAX_CURRENCIES); // dev: encode asset currency id overflow require(0 < asset.maturity && asset.maturity <= type(uint40).max); // dev: encode asset maturity overflow require(0 < asset.assetType && asset.assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX); // dev: encode asset type invalid require(type(int88).min <= asset.notional && asset.notional <= type(int88).max); // dev: encode asset notional overflow assetStorage.currencyId = uint16(asset.currencyId); assetStorage.maturity = uint40(asset.maturity); assetStorage.assetType = uint8(asset.assetType); assetStorage.notional = int88(asset.notional); } /// @notice Deletes an asset from a portfolio /// @dev This method should only be called during settlement, assets can only be removed from a portfolio before settlement /// by adding the offsetting negative position function deleteAsset(PortfolioState memory portfolioState, uint256 index) internal pure { require(index < portfolioState.storedAssets.length); // dev: stored assets bounds require(portfolioState.storedAssetLength > 0); // dev: stored assets length is zero PortfolioAsset memory assetToDelete = portfolioState.storedAssets[index]; require( assetToDelete.storageState != AssetStorageState.Delete && assetToDelete.storageState != AssetStorageState.RevertIfStored ); // dev: cannot delete asset portfolioState.storedAssetLength -= 1; uint256 maxActiveSlotIndex; uint256 maxActiveSlot; // The max active slot is the last storage slot where an asset exists, it's not clear where this will be in the // array so we search for it here. for (uint256 i; i < portfolioState.storedAssets.length; i++) { PortfolioAsset memory a = portfolioState.storedAssets[i]; if (a.storageSlot > maxActiveSlot && a.storageState != AssetStorageState.Delete) { maxActiveSlot = a.storageSlot; maxActiveSlotIndex = i; } } if (index == maxActiveSlotIndex) { // In this case we are deleting the asset with the max storage slot so no swap is necessary. assetToDelete.storageState = AssetStorageState.Delete; return; } // Swap the storage slots of the deleted asset with the last non-deleted asset in the array. Mark them accordingly // so that when we call store assets they will be updated appropriately PortfolioAsset memory assetToSwap = portfolioState.storedAssets[maxActiveSlotIndex]; ( assetToSwap.storageSlot, assetToDelete.storageSlot ) = ( assetToDelete.storageSlot, assetToSwap.storageSlot ); assetToSwap.storageState = AssetStorageState.Update; assetToDelete.storageState = AssetStorageState.Delete; } /// @notice Returns a portfolio array, will be sorted function getSortedPortfolio(address account, uint8 assetArrayLength) internal view returns (PortfolioAsset[] memory) { PortfolioAsset[] memory assets = _loadAssetArray(account, assetArrayLength); // No sorting required for length of 1 if (assets.length <= 1) return assets; _sortInPlace(assets); return assets; } /// @notice Builds a portfolio array from storage. The new assets hint parameter will /// be used to provision a new array for the new assets. This will increase gas efficiency /// so that we don't have to make copies when we extend the array. function buildPortfolioState( address account, uint8 assetArrayLength, uint256 newAssetsHint ) internal view returns (PortfolioState memory) { PortfolioState memory state; if (assetArrayLength == 0) return state; state.storedAssets = getSortedPortfolio(account, assetArrayLength); state.storedAssetLength = assetArrayLength; state.newAssets = new PortfolioAsset[](newAssetsHint); return state; } function _sortInPlace(PortfolioAsset[] memory assets) private pure { uint256 length = assets.length; uint256[] memory ids = new uint256[](length); for (uint256 k; k < length; k++) { PortfolioAsset memory asset = assets[k]; // Prepopulate the ids to calculate just once ids[k] = TransferAssets.encodeAssetId(asset.currencyId, asset.maturity, asset.assetType); } // Uses insertion sort uint256 i = 1; while (i < length) { uint256 j = i; while (j > 0 && ids[j - 1] > ids[j]) { // Swap j - 1 and j (ids[j - 1], ids[j]) = (ids[j], ids[j - 1]); (assets[j - 1], assets[j]) = (assets[j], assets[j - 1]); j--; } i++; } } function _loadAssetArray(address account, uint8 length) private view returns (PortfolioAsset[] memory) { // This will overflow the storage pointer require(length <= MAX_PORTFOLIO_ASSETS); mapping(address => PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS]) storage store = LibStorage.getPortfolioArrayStorage(); PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS] storage storageArray = store[account]; PortfolioAsset[] memory assets = new PortfolioAsset[](length); for (uint256 i = 0; i < length; i++) { PortfolioAssetStorage storage assetStorage = storageArray[i]; PortfolioAsset memory asset = assets[i]; uint256 slot; assembly { slot := assetStorage.slot } asset.currencyId = assetStorage.currencyId; asset.maturity = assetStorage.maturity; asset.assetType = assetStorage.assetType; asset.notional = assetStorage.notional; asset.storageSlot = slot; } return assets; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../valuation/AssetHandler.sol"; import "../markets/Market.sol"; import "../markets/AssetRate.sol"; import "../portfolio/PortfolioHandler.sol"; import "../../math/SafeInt256.sol"; import "../../global/Constants.sol"; import "../../global/Types.sol"; library SettlePortfolioAssets { using SafeInt256 for int256; using AssetRate for AssetRateParameters; using Market for MarketParameters; using PortfolioHandler for PortfolioState; using AssetHandler for PortfolioAsset; /// @dev Returns a SettleAmount array for the assets that will be settled function _getSettleAmountArray(PortfolioState memory portfolioState, uint256 blockTime) private pure returns (SettleAmount[] memory) { uint256 currenciesSettled; uint256 lastCurrencyId = 0; if (portfolioState.storedAssets.length == 0) return new SettleAmount[](0); // Loop backwards so "lastCurrencyId" will be set to the first currency in the portfolio // NOTE: if this contract is ever upgraded to Solidity 0.8+ then this i-- will underflow and cause // a revert, must wrap in an unchecked. for (uint256 i = portfolioState.storedAssets.length; (i--) > 0;) { PortfolioAsset memory asset = portfolioState.storedAssets[i]; // Assets settle on exactly blockTime if (asset.getSettlementDate() > blockTime) continue; // Assume that this is sorted by cash group and maturity, currencyId = 0 is unused so this // will work for the first asset if (lastCurrencyId != asset.currencyId) { lastCurrencyId = asset.currencyId; currenciesSettled++; } } // Actual currency ids will be set as we loop through the portfolio and settle assets SettleAmount[] memory settleAmounts = new SettleAmount[](currenciesSettled); if (currenciesSettled > 0) settleAmounts[0].currencyId = lastCurrencyId; return settleAmounts; } /// @notice Settles a portfolio array function settlePortfolio(PortfolioState memory portfolioState, uint256 blockTime) internal returns (SettleAmount[] memory) { AssetRateParameters memory settlementRate; SettleAmount[] memory settleAmounts = _getSettleAmountArray(portfolioState, blockTime); MarketParameters memory market; if (settleAmounts.length == 0) return settleAmounts; uint256 settleAmountIndex; for (uint256 i; i < portfolioState.storedAssets.length; i++) { PortfolioAsset memory asset = portfolioState.storedAssets[i]; uint256 settleDate = asset.getSettlementDate(); // Settlement date is on block time exactly if (settleDate > blockTime) continue; // On the first loop the lastCurrencyId is already set. if (settleAmounts[settleAmountIndex].currencyId != asset.currencyId) { // New currency in the portfolio settleAmountIndex += 1; settleAmounts[settleAmountIndex].currencyId = asset.currencyId; } int256 assetCash; if (asset.assetType == Constants.FCASH_ASSET_TYPE) { // Gets or sets the settlement rate, only do this before settling fCash settlementRate = AssetRate.buildSettlementRateStateful( asset.currencyId, asset.maturity, blockTime ); assetCash = settlementRate.convertFromUnderlying(asset.notional); portfolioState.deleteAsset(i); } else if (AssetHandler.isLiquidityToken(asset.assetType)) { Market.loadSettlementMarket(market, asset.currencyId, asset.maturity, settleDate); int256 fCash; (assetCash, fCash) = market.removeLiquidity(asset.notional); // Assets mature exactly on block time if (asset.maturity > blockTime) { // If fCash has not yet matured then add it to the portfolio _settleLiquidityTokenTofCash(portfolioState, i, fCash); } else { // Gets or sets the settlement rate, only do this before settling fCash settlementRate = AssetRate.buildSettlementRateStateful( asset.currencyId, asset.maturity, blockTime ); // If asset has matured then settle fCash to asset cash assetCash = assetCash.add(settlementRate.convertFromUnderlying(fCash)); portfolioState.deleteAsset(i); } } settleAmounts[settleAmountIndex].netCashChange = settleAmounts[settleAmountIndex] .netCashChange .add(assetCash); } return settleAmounts; } /// @notice Settles a liquidity token to idiosyncratic fCash, this occurs when the maturity is still in the future function _settleLiquidityTokenTofCash( PortfolioState memory portfolioState, uint256 index, int256 fCash ) private pure { PortfolioAsset memory liquidityToken = portfolioState.storedAssets[index]; // If the liquidity token's maturity is still in the future then we change the entry to be // an idiosyncratic fCash entry with the net fCash amount. if (index != 0) { // Check to see if the previous index is the matching fCash asset, this will be the case when the // portfolio is sorted PortfolioAsset memory fCashAsset = portfolioState.storedAssets[index - 1]; if ( fCashAsset.currencyId == liquidityToken.currencyId && fCashAsset.maturity == liquidityToken.maturity && fCashAsset.assetType == Constants.FCASH_ASSET_TYPE ) { // This fCash asset has not matured if we are settling to fCash fCashAsset.notional = fCashAsset.notional.add(fCash); fCashAsset.storageState = AssetStorageState.Update; portfolioState.deleteAsset(index); } } // We are going to delete this asset anyway, convert to an fCash position liquidityToken.assetType = Constants.FCASH_ASSET_TYPE; liquidityToken.notional = fCash; liquidityToken.storageState = AssetStorageState.Update; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../markets/AssetRate.sol"; import "../../global/LibStorage.sol"; import "../portfolio/BitmapAssetsHandler.sol"; import "../../math/SafeInt256.sol"; import "../../math/Bitmap.sol"; import "../../global/Constants.sol"; import "../../global/Types.sol"; /** * Settles a bitmap portfolio by checking for all matured fCash assets and turning them into cash * at the prevailing settlement rate. It will also update the asset bitmap to ensure that it continues * to correctly reference all actual maturities. fCash asset notional values are stored in *absolute* * time terms and bitmap bits are *relative* time terms based on the bitNumber and the stored oldSettleTime. * Remapping bits requires converting the old relative bit numbers to new relative bit numbers based on * newSettleTime and the absolute times (maturities) that the previous bitmap references. */ library SettleBitmapAssets { using SafeInt256 for int256; using AssetRate for AssetRateParameters; using Bitmap for bytes32; /// @notice Given a bitmap for a cash group and timestamps, will settle all assets /// that have matured and remap the bitmap to correspond to the current time. function settleBitmappedCashGroup( address account, uint256 currencyId, uint256 oldSettleTime, uint256 blockTime ) internal returns (int256 totalAssetCash, uint256 newSettleTime) { bytes32 bitmap = BitmapAssetsHandler.getAssetsBitmap(account, currencyId); // This newSettleTime will be set to the new `oldSettleTime`. The bits between 1 and // `lastSettleBit` (inclusive) will be shifted out of the bitmap and settled. The reason // that lastSettleBit is inclusive is that it refers to newSettleTime which always less // than the current block time. newSettleTime = DateTime.getTimeUTC0(blockTime); // If newSettleTime == oldSettleTime lastSettleBit will be zero require(newSettleTime >= oldSettleTime); // dev: new settle time before previous // Do not need to worry about validity, if newSettleTime is not on an exact bit we will settle up until // the closest maturity that is less than newSettleTime. (uint256 lastSettleBit, /* isValid */) = DateTime.getBitNumFromMaturity(oldSettleTime, newSettleTime); if (lastSettleBit == 0) return (totalAssetCash, newSettleTime); // Returns the next bit that is set in the bitmap uint256 nextBitNum = bitmap.getNextBitNum(); while (nextBitNum != 0 && nextBitNum <= lastSettleBit) { uint256 maturity = DateTime.getMaturityFromBitNum(oldSettleTime, nextBitNum); totalAssetCash = totalAssetCash.add( _settlefCashAsset(account, currencyId, maturity, blockTime) ); // Turn the bit off now that it is settled bitmap = bitmap.setBit(nextBitNum, false); nextBitNum = bitmap.getNextBitNum(); } bytes32 newBitmap; while (nextBitNum != 0) { uint256 maturity = DateTime.getMaturityFromBitNum(oldSettleTime, nextBitNum); (uint256 newBitNum, bool isValid) = DateTime.getBitNumFromMaturity(newSettleTime, maturity); require(isValid); // dev: invalid new bit num newBitmap = newBitmap.setBit(newBitNum, true); // Turn the bit off now that it is remapped bitmap = bitmap.setBit(nextBitNum, false); nextBitNum = bitmap.getNextBitNum(); } BitmapAssetsHandler.setAssetsBitmap(account, currencyId, newBitmap); } /// @dev Stateful settlement function to settle a bitmapped asset. Deletes the /// asset from storage after calculating it. function _settlefCashAsset( address account, uint256 currencyId, uint256 maturity, uint256 blockTime ) private returns (int256 assetCash) { mapping(address => mapping(uint256 => mapping(uint256 => ifCashStorage))) storage store = LibStorage.getifCashBitmapStorage(); int256 notional = store[account][currencyId][maturity].notional; // Gets the current settlement rate or will store a new settlement rate if it does not // yet exist. AssetRateParameters memory rate = AssetRate.buildSettlementRateStateful(currencyId, maturity, blockTime); assetCash = rate.convertFromUnderlying(notional); delete store[account][currencyId][maturity]; return assetCash; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./nTokenSupply.sol"; import "../markets/CashGroup.sol"; import "../markets/AssetRate.sol"; import "../portfolio/PortfolioHandler.sol"; import "../balances/BalanceHandler.sol"; import "../../global/LibStorage.sol"; import "../../math/SafeInt256.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library nTokenHandler { using SafeInt256 for int256; /// @dev Mirror of the value in LibStorage, solidity compiler does not allow assigning /// two constants to each other. uint256 private constant NUM_NTOKEN_MARKET_FACTORS = 14; /// @notice Returns an account context object that is specific to nTokens. function getNTokenContext(address tokenAddress) internal view returns ( uint16 currencyId, uint256 incentiveAnnualEmissionRate, uint256 lastInitializedTime, uint8 assetArrayLength, bytes5 parameters ) { mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage(); nTokenContext storage context = store[tokenAddress]; currencyId = context.currencyId; incentiveAnnualEmissionRate = context.incentiveAnnualEmissionRate; lastInitializedTime = context.lastInitializedTime; assetArrayLength = context.assetArrayLength; parameters = context.nTokenParameters; } /// @notice Returns the nToken token address for a given currency function nTokenAddress(uint256 currencyId) internal view returns (address tokenAddress) { mapping(uint256 => address) storage store = LibStorage.getNTokenAddressStorage(); return store[currencyId]; } /// @notice Called by governance to set the nToken token address and its reverse lookup. Cannot be /// reset once this is set. function setNTokenAddress(uint16 currencyId, address tokenAddress) internal { mapping(uint256 => address) storage addressStore = LibStorage.getNTokenAddressStorage(); require(addressStore[currencyId] == address(0), "PT: token address exists"); mapping(address => nTokenContext) storage contextStore = LibStorage.getNTokenContextStorage(); nTokenContext storage context = contextStore[tokenAddress]; require(context.currencyId == 0, "PT: currency exists"); // This will initialize all other context slots to zero context.currencyId = currencyId; addressStore[currencyId] = tokenAddress; } /// @notice Set nToken token collateral parameters function setNTokenCollateralParameters( address tokenAddress, uint8 residualPurchaseIncentive10BPS, uint8 pvHaircutPercentage, uint8 residualPurchaseTimeBufferHours, uint8 cashWithholdingBuffer10BPS, uint8 liquidationHaircutPercentage ) internal { mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage(); nTokenContext storage context = store[tokenAddress]; require(liquidationHaircutPercentage <= Constants.PERCENTAGE_DECIMALS, "Invalid haircut"); // The pv haircut percentage must be less than the liquidation percentage or else liquidators will not // get profit for liquidating nToken. require(pvHaircutPercentage < liquidationHaircutPercentage, "Invalid pv haircut"); // Ensure that the cash withholding buffer is greater than the residual purchase incentive or // the nToken may not have enough cash to pay accounts to buy its negative ifCash require(residualPurchaseIncentive10BPS <= cashWithholdingBuffer10BPS, "Invalid discounts"); bytes5 parameters = (bytes5(uint40(residualPurchaseIncentive10BPS)) | (bytes5(uint40(pvHaircutPercentage)) << 8) | (bytes5(uint40(residualPurchaseTimeBufferHours)) << 16) | (bytes5(uint40(cashWithholdingBuffer10BPS)) << 24) | (bytes5(uint40(liquidationHaircutPercentage)) << 32)); // Set the parameters context.nTokenParameters = parameters; } /// @notice Sets a secondary rewarder contract on an nToken so that incentives can come from a different /// contract, aside from the native NOTE token incentives. function setSecondaryRewarder( uint16 currencyId, IRewarder rewarder ) internal { address tokenAddress = nTokenAddress(currencyId); // nToken must exist for a secondary rewarder require(tokenAddress != address(0)); mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage(); nTokenContext storage context = store[tokenAddress]; // Setting the rewarder to address(0) will disable it. We use a context setting here so that // we can save a storage read before getting the rewarder context.hasSecondaryRewarder = (address(rewarder) != address(0)); LibStorage.getSecondaryIncentiveRewarder()[tokenAddress] = rewarder; } /// @notice Returns the secondary rewarder if it is set function getSecondaryRewarder(address tokenAddress) internal view returns (IRewarder) { mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage(); nTokenContext storage context = store[tokenAddress]; if (context.hasSecondaryRewarder) { return LibStorage.getSecondaryIncentiveRewarder()[tokenAddress]; } else { return IRewarder(address(0)); } } function setArrayLengthAndInitializedTime( address tokenAddress, uint8 arrayLength, uint256 lastInitializedTime ) internal { require(lastInitializedTime >= 0 && uint256(lastInitializedTime) < type(uint32).max); // dev: next settle time overflow mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage(); nTokenContext storage context = store[tokenAddress]; context.lastInitializedTime = uint32(lastInitializedTime); context.assetArrayLength = arrayLength; } /// @notice Returns the array of deposit shares and leverage thresholds for nTokens function getDepositParameters(uint256 currencyId, uint256 maxMarketIndex) internal view returns (int256[] memory depositShares, int256[] memory leverageThresholds) { mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store = LibStorage.getNTokenDepositStorage(); uint32[NUM_NTOKEN_MARKET_FACTORS] storage depositParameters = store[currencyId]; (depositShares, leverageThresholds) = _getParameters(depositParameters, maxMarketIndex, false); } /// @notice Sets the deposit parameters /// @dev We pack the values in alternating between the two parameters into either one or two // storage slots depending on the number of markets. This is to save storage reads when we use the parameters. function setDepositParameters( uint256 currencyId, uint32[] calldata depositShares, uint32[] calldata leverageThresholds ) internal { require( depositShares.length <= Constants.MAX_TRADED_MARKET_INDEX, "PT: deposit share length" ); require(depositShares.length == leverageThresholds.length, "PT: leverage share length"); uint256 shareSum; for (uint256 i; i < depositShares.length; i++) { // This cannot overflow in uint 256 with 9 max slots shareSum = shareSum + depositShares[i]; require( leverageThresholds[i] > 0 && leverageThresholds[i] < Constants.RATE_PRECISION, "PT: leverage threshold" ); } // Total deposit share must add up to 100% require(shareSum == uint256(Constants.DEPOSIT_PERCENT_BASIS), "PT: deposit shares sum"); mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store = LibStorage.getNTokenDepositStorage(); uint32[NUM_NTOKEN_MARKET_FACTORS] storage depositParameters = store[currencyId]; _setParameters(depositParameters, depositShares, leverageThresholds); } /// @notice Sets the initialization parameters for the markets, these are read only when markets /// are initialized function setInitializationParameters( uint256 currencyId, uint32[] calldata annualizedAnchorRates, uint32[] calldata proportions ) internal { require(annualizedAnchorRates.length <= Constants.MAX_TRADED_MARKET_INDEX, "PT: annualized anchor rates length"); require(proportions.length == annualizedAnchorRates.length, "PT: proportions length"); for (uint256 i; i < proportions.length; i++) { // Proportions must be between zero and the rate precision require(annualizedAnchorRates[i] > 0, "NT: anchor rate zero"); require( proportions[i] > 0 && proportions[i] < Constants.RATE_PRECISION, "PT: invalid proportion" ); } mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store = LibStorage.getNTokenInitStorage(); uint32[NUM_NTOKEN_MARKET_FACTORS] storage initParameters = store[currencyId]; _setParameters(initParameters, annualizedAnchorRates, proportions); } /// @notice Returns the array of initialization parameters for a given currency. function getInitializationParameters(uint256 currencyId, uint256 maxMarketIndex) internal view returns (int256[] memory annualizedAnchorRates, int256[] memory proportions) { mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store = LibStorage.getNTokenInitStorage(); uint32[NUM_NTOKEN_MARKET_FACTORS] storage initParameters = store[currencyId]; (annualizedAnchorRates, proportions) = _getParameters(initParameters, maxMarketIndex, true); } function _getParameters( uint32[NUM_NTOKEN_MARKET_FACTORS] storage slot, uint256 maxMarketIndex, bool noUnset ) private view returns (int256[] memory, int256[] memory) { uint256 index = 0; int256[] memory array1 = new int256[](maxMarketIndex); int256[] memory array2 = new int256[](maxMarketIndex); for (uint256 i; i < maxMarketIndex; i++) { array1[i] = slot[index]; index++; array2[i] = slot[index]; index++; if (noUnset) { require(array1[i] > 0 && array2[i] > 0, "PT: init value zero"); } } return (array1, array2); } function _setParameters( uint32[NUM_NTOKEN_MARKET_FACTORS] storage slot, uint32[] calldata array1, uint32[] calldata array2 ) private { uint256 index = 0; for (uint256 i = 0; i < array1.length; i++) { slot[index] = array1[i]; index++; slot[index] = array2[i]; index++; } } function loadNTokenPortfolioNoCashGroup(nTokenPortfolio memory nToken, uint16 currencyId) internal view { nToken.tokenAddress = nTokenAddress(currencyId); // prettier-ignore ( /* currencyId */, /* incentiveRate */, uint256 lastInitializedTime, uint8 assetArrayLength, bytes5 parameters ) = getNTokenContext(nToken.tokenAddress); // prettier-ignore ( uint256 totalSupply, /* accumulatedNOTEPerNToken */, /* lastAccumulatedTime */ ) = nTokenSupply.getStoredNTokenSupplyFactors(nToken.tokenAddress); nToken.lastInitializedTime = lastInitializedTime; nToken.totalSupply = int256(totalSupply); nToken.parameters = parameters; nToken.portfolioState = PortfolioHandler.buildPortfolioState( nToken.tokenAddress, assetArrayLength, 0 ); // prettier-ignore ( nToken.cashBalance, /* nTokenBalance */, /* lastClaimTime */, /* accountIncentiveDebt */ ) = BalanceHandler.getBalanceStorage(nToken.tokenAddress, currencyId); } /// @notice Uses buildCashGroupStateful function loadNTokenPortfolioStateful(nTokenPortfolio memory nToken, uint16 currencyId) internal { loadNTokenPortfolioNoCashGroup(nToken, currencyId); nToken.cashGroup = CashGroup.buildCashGroupStateful(currencyId); } /// @notice Uses buildCashGroupView function loadNTokenPortfolioView(nTokenPortfolio memory nToken, uint16 currencyId) internal view { loadNTokenPortfolioNoCashGroup(nToken, currencyId); nToken.cashGroup = CashGroup.buildCashGroupView(currencyId); } /// @notice Returns the next settle time for the nToken which is 1 quarter away function getNextSettleTime(nTokenPortfolio memory nToken) internal pure returns (uint256) { if (nToken.lastInitializedTime == 0) return 0; return DateTime.getReferenceTime(nToken.lastInitializedTime) + Constants.QUARTER; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; import "../global/Constants.sol"; library SafeInt256 { int256 private constant _INT256_MIN = type(int256).min; /// @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 c) { c = a * b; if (a == -1) require (b == 0 || c / b == a); else require (a == 0 || c / a == b); } /// @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 c) { require(!(b == -1 && a == _INT256_MIN)); // dev: int256 div overflow // NOTE: solidity will automatically revert on divide by zero c = a / b; } function sub(int256 x, int256 y) internal pure returns (int256 z) { // taken from uniswap v3 require((z = x - y) <= x == (y >= 0)); } function add(int256 x, int256 y) internal pure returns (int256 z) { require((z = x + y) >= x == (y >= 0)); } function neg(int256 x) internal pure returns (int256 y) { return mul(-1, x); } function abs(int256 x) internal pure returns (int256) { if (x < 0) return neg(x); else return x; } function subNoNeg(int256 x, int256 y) internal pure returns (int256 z) { z = sub(x, y); require(z >= 0); // dev: int256 sub to negative return z; } /// @dev Calculates x * RATE_PRECISION / y while checking overflows function divInRatePrecision(int256 x, int256 y) internal pure returns (int256) { return div(mul(x, Constants.RATE_PRECISION), y); } /// @dev Calculates x * y / RATE_PRECISION while checking overflows function mulInRatePrecision(int256 x, int256 y) internal pure returns (int256) { return div(mul(x, y), Constants.RATE_PRECISION); } function toUint(int256 x) internal pure returns (uint256) { require(x >= 0); return uint256(x); } function toInt(uint256 x) internal pure returns (int256) { require (x <= uint256(type(int256).max)); // dev: toInt overflow return int256(x); } function max(int256 x, int256 y) internal pure returns (int256) { return x > y ? x : y; } function min(int256 x, int256 y) internal pure returns (int256) { return x < y ? x : y; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../global/Types.sol"; import "../global/Constants.sol"; /// @notice Helper methods for bitmaps, they are big-endian and 1-indexed. library Bitmap { /// @notice Set a bit on or off in a bitmap, index is 1-indexed function setBit( bytes32 bitmap, uint256 index, bool setOn ) internal pure returns (bytes32) { require(index >= 1 && index <= 256); // dev: set bit index bounds if (setOn) { return bitmap | (Constants.MSB >> (index - 1)); } else { return bitmap & ~(Constants.MSB >> (index - 1)); } } /// @notice Check if a bit is set function isBitSet(bytes32 bitmap, uint256 index) internal pure returns (bool) { require(index >= 1 && index <= 256); // dev: set bit index bounds return ((bitmap << (index - 1)) & Constants.MSB) == Constants.MSB; } /// @notice Count the total bits set function totalBitsSet(bytes32 bitmap) internal pure returns (uint256) { uint256 x = uint256(bitmap); x = (x & 0x5555555555555555555555555555555555555555555555555555555555555555) + (x >> 1 & 0x5555555555555555555555555555555555555555555555555555555555555555); x = (x & 0x3333333333333333333333333333333333333333333333333333333333333333) + (x >> 2 & 0x3333333333333333333333333333333333333333333333333333333333333333); x = (x & 0x0707070707070707070707070707070707070707070707070707070707070707) + (x >> 4); x = (x & 0x000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F) + (x >> 8 & 0x000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F); x = x + (x >> 16); x = x + (x >> 32); x = x + (x >> 64); return (x & 0xFF) + (x >> 128 & 0xFF); } // Does a binary search over x to get the position of the most significant bit function getMSB(uint256 x) internal pure returns (uint256 msb) { // If x == 0 then there is no MSB and this method will return zero. That would // be the same as the return value when x == 1 (MSB is zero indexed), so instead // we have this require here to ensure that the values don't get mixed up. require(x != 0); // dev: get msb zero value if (x >= 0x100000000000000000000000000000000) { x >>= 128; msb += 128; } if (x >= 0x10000000000000000) { x >>= 64; msb += 64; } if (x >= 0x100000000) { x >>= 32; msb += 32; } if (x >= 0x10000) { x >>= 16; msb += 16; } if (x >= 0x100) { x >>= 8; msb += 8; } if (x >= 0x10) { x >>= 4; msb += 4; } if (x >= 0x4) { x >>= 2; msb += 2; } if (x >= 0x2) msb += 1; // No need to shift xc anymore } /// @dev getMSB returns a zero indexed bit number where zero is the first bit counting /// from the right (little endian). Asset Bitmaps are counted from the left (big endian) /// and one indexed. function getNextBitNum(bytes32 bitmap) internal pure returns (uint256 bitNum) { // Short circuit the search if bitmap is all zeros if (bitmap == 0x00) return 0; return 255 - getMSB(uint256(bitmap)) + 1; } } // 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: GPL-3.0-only pragma solidity ^0.7.0; /// @title All shared constants for the Notional system should be declared here. library Constants { uint8 internal constant CETH_DECIMAL_PLACES = 8; // Token precision used for all internal balances, TokenHandler library ensures that we // limit the dust amount caused by precision mismatches int256 internal constant INTERNAL_TOKEN_PRECISION = 1e8; uint256 internal constant INCENTIVE_ACCUMULATION_PRECISION = 1e18; // ETH will be initialized as the first currency uint256 internal constant ETH_CURRENCY_ID = 1; uint8 internal constant ETH_DECIMAL_PLACES = 18; int256 internal constant ETH_DECIMALS = 1e18; // Used to prevent overflow when converting decimal places to decimal precision values via // 10**decimalPlaces. This is a safe value for int256 and uint256 variables. We apply this // constraint when storing decimal places in governance. uint256 internal constant MAX_DECIMAL_PLACES = 36; // Address of the reserve account address internal constant RESERVE = address(0); // Most significant bit bytes32 internal constant MSB = 0x8000000000000000000000000000000000000000000000000000000000000000; // Each bit set in this mask marks where an active market should be in the bitmap // if the first bit refers to the reference time. Used to detect idiosyncratic // fcash in the nToken accounts bytes32 internal constant ACTIVE_MARKETS_MASK = ( MSB >> ( 90 - 1) | // 3 month MSB >> (105 - 1) | // 6 month MSB >> (135 - 1) | // 1 year MSB >> (147 - 1) | // 2 year MSB >> (183 - 1) | // 5 year MSB >> (211 - 1) | // 10 year MSB >> (251 - 1) // 20 year ); // Basis for percentages int256 internal constant PERCENTAGE_DECIMALS = 100; // Max number of traded markets, also used as the maximum number of assets in a portfolio array uint256 internal constant MAX_TRADED_MARKET_INDEX = 7; // Max number of fCash assets in a bitmap, this is based on the gas costs of calculating free collateral // for a bitmap portfolio uint256 internal constant MAX_BITMAP_ASSETS = 20; uint256 internal constant FIVE_MINUTES = 300; // Internal date representations, note we use a 6/30/360 week/month/year convention here uint256 internal constant DAY = 86400; // We use six day weeks to ensure that all time references divide evenly uint256 internal constant WEEK = DAY * 6; uint256 internal constant MONTH = WEEK * 5; uint256 internal constant QUARTER = MONTH * 3; uint256 internal constant YEAR = QUARTER * 4; // These constants are used in DateTime.sol uint256 internal constant DAYS_IN_WEEK = 6; uint256 internal constant DAYS_IN_MONTH = 30; uint256 internal constant DAYS_IN_QUARTER = 90; // Offsets for each time chunk denominated in days uint256 internal constant MAX_DAY_OFFSET = 90; uint256 internal constant MAX_WEEK_OFFSET = 360; uint256 internal constant MAX_MONTH_OFFSET = 2160; uint256 internal constant MAX_QUARTER_OFFSET = 7650; // Offsets for each time chunk denominated in bits uint256 internal constant WEEK_BIT_OFFSET = 90; uint256 internal constant MONTH_BIT_OFFSET = 135; uint256 internal constant QUARTER_BIT_OFFSET = 195; // This is a constant that represents the time period that all rates are normalized by, 360 days uint256 internal constant IMPLIED_RATE_TIME = 360 * DAY; // Number of decimal places that rates are stored in, equals 100% int256 internal constant RATE_PRECISION = 1e9; // One basis point in RATE_PRECISION terms uint256 internal constant BASIS_POINT = uint256(RATE_PRECISION / 10000); // Used to when calculating the amount to deleverage of a market when minting nTokens uint256 internal constant DELEVERAGE_BUFFER = 300 * BASIS_POINT; // Used for scaling cash group factors uint256 internal constant FIVE_BASIS_POINTS = 5 * BASIS_POINT; // Used for residual purchase incentive and cash withholding buffer uint256 internal constant TEN_BASIS_POINTS = 10 * BASIS_POINT; // This is the ABDK64x64 representation of RATE_PRECISION // RATE_PRECISION_64x64 = ABDKMath64x64.fromUint(RATE_PRECISION) int128 internal constant RATE_PRECISION_64x64 = 0x3b9aca000000000000000000; int128 internal constant LOG_RATE_PRECISION_64x64 = 382276781265598821176; // Limit the market proportion so that borrowing cannot hit extremely high interest rates int256 internal constant MAX_MARKET_PROPORTION = RATE_PRECISION * 99 / 100; uint8 internal constant FCASH_ASSET_TYPE = 1; // Liquidity token asset types are 1 + marketIndex (where marketIndex is 1-indexed) uint8 internal constant MIN_LIQUIDITY_TOKEN_INDEX = 2; uint8 internal constant MAX_LIQUIDITY_TOKEN_INDEX = 8; // Used for converting bool to bytes1, solidity does not have a native conversion // method for this bytes1 internal constant BOOL_FALSE = 0x00; bytes1 internal constant BOOL_TRUE = 0x01; // Account context flags bytes1 internal constant HAS_ASSET_DEBT = 0x01; bytes1 internal constant HAS_CASH_DEBT = 0x02; bytes2 internal constant ACTIVE_IN_PORTFOLIO = 0x8000; bytes2 internal constant ACTIVE_IN_BALANCES = 0x4000; bytes2 internal constant UNMASK_FLAGS = 0x3FFF; uint16 internal constant MAX_CURRENCIES = uint16(UNMASK_FLAGS); // Equal to 100% of all deposit amounts for nToken liquidity across fCash markets. int256 internal constant DEPOSIT_PERCENT_BASIS = 1e8; // nToken Parameters: there are offsets in the nTokenParameters bytes6 variable returned // in nTokenHandler. Each constant represents a position in the byte array. uint8 internal constant LIQUIDATION_HAIRCUT_PERCENTAGE = 0; uint8 internal constant CASH_WITHHOLDING_BUFFER = 1; uint8 internal constant RESIDUAL_PURCHASE_TIME_BUFFER = 2; uint8 internal constant PV_HAIRCUT_PERCENTAGE = 3; uint8 internal constant RESIDUAL_PURCHASE_INCENTIVE = 4; // Liquidation parameters // Default percentage of collateral that a liquidator is allowed to liquidate, will be higher if the account // requires more collateral to be liquidated int256 internal constant DEFAULT_LIQUIDATION_PORTION = 40; // Percentage of local liquidity token cash claim delivered to the liquidator for liquidating liquidity tokens int256 internal constant TOKEN_REPO_INCENTIVE_PERCENT = 30; // Pause Router liquidation enabled states bytes1 internal constant LOCAL_CURRENCY_ENABLED = 0x01; bytes1 internal constant COLLATERAL_CURRENCY_ENABLED = 0x02; bytes1 internal constant LOCAL_FCASH_ENABLED = 0x04; bytes1 internal constant CROSS_CURRENCY_FCASH_ENABLED = 0x08; } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./nTokenHandler.sol"; import "../portfolio/BitmapAssetsHandler.sol"; import "../../math/SafeInt256.sol"; import "../../math/Bitmap.sol"; library nTokenCalculations { using Bitmap for bytes32; using SafeInt256 for int256; using AssetRate for AssetRateParameters; using CashGroup for CashGroupParameters; /// @notice Returns the nToken present value denominated in asset terms. function getNTokenAssetPV(nTokenPortfolio memory nToken, uint256 blockTime) internal view returns (int256) { int256 totalAssetPV; int256 totalUnderlyingPV; { uint256 nextSettleTime = nTokenHandler.getNextSettleTime(nToken); // If the first asset maturity has passed (the 3 month), this means that all the LTs must // be settled except the 6 month (which is now the 3 month). We don't settle LTs except in // initialize markets so we calculate the cash value of the portfolio here. if (nextSettleTime <= blockTime) { // NOTE: this condition should only be present for a very short amount of time, which is the window between // when the markets are no longer tradable at quarter end and when the new markets have been initialized. // We time travel back to one second before maturity to value the liquidity tokens. Although this value is // not strictly correct the different should be quite slight. We do this to ensure that free collateral checks // for withdraws and liquidations can still be processed. If this condition persists for a long period of time then // the entire protocol will have serious problems as markets will not be tradable. blockTime = nextSettleTime - 1; } } // This is the total value in liquid assets (int256 totalAssetValueInMarkets, /* int256[] memory netfCash */) = getNTokenMarketValue(nToken, blockTime); // Then get the total value in any idiosyncratic fCash residuals (if they exist) bytes32 ifCashBits = getNTokenifCashBits( nToken.tokenAddress, nToken.cashGroup.currencyId, nToken.lastInitializedTime, blockTime, nToken.cashGroup.maxMarketIndex ); int256 ifCashResidualUnderlyingPV = 0; if (ifCashBits != 0) { // Non idiosyncratic residuals have already been accounted for (ifCashResidualUnderlyingPV, /* hasDebt */) = BitmapAssetsHandler.getNetPresentValueFromBitmap( nToken.tokenAddress, nToken.cashGroup.currencyId, nToken.lastInitializedTime, blockTime, nToken.cashGroup, false, // nToken present value calculation does not use risk adjusted values ifCashBits ); } // Return the total present value denominated in asset terms return totalAssetValueInMarkets .add(nToken.cashGroup.assetRate.convertFromUnderlying(ifCashResidualUnderlyingPV)) .add(nToken.cashBalance); } /** * @notice Handles the case when liquidity tokens should be withdrawn in proportion to their amounts * in the market. This will be the case when there is no idiosyncratic fCash residuals in the nToken * portfolio. * @param nToken portfolio object for nToken * @param nTokensToRedeem amount of nTokens to redeem * @param tokensToWithdraw array of liquidity tokens to withdraw from each market, proportional to * the account's share of the total supply * @param netfCash an empty array to hold net fCash values calculated later when the tokens are actually * withdrawn from markets */ function _getProportionalLiquidityTokens( nTokenPortfolio memory nToken, int256 nTokensToRedeem ) private pure returns (int256[] memory tokensToWithdraw, int256[] memory netfCash) { uint256 numMarkets = nToken.portfolioState.storedAssets.length; tokensToWithdraw = new int256[](numMarkets); netfCash = new int256[](numMarkets); for (uint256 i = 0; i < numMarkets; i++) { int256 totalTokens = nToken.portfolioState.storedAssets[i].notional; tokensToWithdraw[i] = totalTokens.mul(nTokensToRedeem).div(nToken.totalSupply); } } /** * @notice Returns the number of liquidity tokens to withdraw from each market if the nToken * has idiosyncratic residuals during nToken redeem. In this case the redeemer will take * their cash from the rest of the fCash markets, redeeming around the nToken. * @param nToken portfolio object for nToken * @param nTokensToRedeem amount of nTokens to redeem * @param blockTime block time * @param ifCashBits the bits in the bitmap that represent ifCash assets * @return tokensToWithdraw array of tokens to withdraw from each corresponding market * @return netfCash array of netfCash amounts to go back to the account */ function getLiquidityTokenWithdraw( nTokenPortfolio memory nToken, int256 nTokensToRedeem, uint256 blockTime, bytes32 ifCashBits ) internal view returns (int256[] memory, int256[] memory) { // If there are no ifCash bits set then this will just return the proportion of all liquidity tokens if (ifCashBits == 0) return _getProportionalLiquidityTokens(nToken, nTokensToRedeem); ( int256 totalAssetValueInMarkets, int256[] memory netfCash ) = getNTokenMarketValue(nToken, blockTime); int256[] memory tokensToWithdraw = new int256[](netfCash.length); // NOTE: this total portfolio asset value does not include any cash balance the nToken may hold. // The redeemer will always get a proportional share of this cash balance and therefore we don't // need to account for it here when we calculate the share of liquidity tokens to withdraw. We are // only concerned with the nToken's portfolio assets in this method. int256 totalPortfolioAssetValue; { // Returns the risk adjusted net present value for the idiosyncratic residuals (int256 underlyingPV, /* hasDebt */) = BitmapAssetsHandler.getNetPresentValueFromBitmap( nToken.tokenAddress, nToken.cashGroup.currencyId, nToken.lastInitializedTime, blockTime, nToken.cashGroup, true, // use risk adjusted here to assess a penalty for withdrawing around the residual ifCashBits ); // NOTE: we do not include cash balance here because the account will always take their share // of the cash balance regardless of the residuals totalPortfolioAssetValue = totalAssetValueInMarkets.add( nToken.cashGroup.assetRate.convertFromUnderlying(underlyingPV) ); } // Loops through each liquidity token and calculates how much the redeemer can withdraw to get // the requisite amount of present value after adjusting for the ifCash residual value that is // not accessible via redemption. for (uint256 i = 0; i < tokensToWithdraw.length; i++) { int256 totalTokens = nToken.portfolioState.storedAssets[i].notional; // Redeemer's baseline share of the liquidity tokens based on total supply: // redeemerShare = totalTokens * nTokensToRedeem / totalSupply // Scalar factor to account for residual value (need to inflate the tokens to withdraw // proportional to the value locked up in ifCash residuals): // scaleFactor = totalPortfolioAssetValue / totalAssetValueInMarkets // Final math equals: // tokensToWithdraw = redeemerShare * scalarFactor // tokensToWithdraw = (totalTokens * nTokensToRedeem * totalPortfolioAssetValue) // / (totalAssetValueInMarkets * totalSupply) tokensToWithdraw[i] = totalTokens .mul(nTokensToRedeem) .mul(totalPortfolioAssetValue); tokensToWithdraw[i] = tokensToWithdraw[i] .div(totalAssetValueInMarkets) .div(nToken.totalSupply); // This is the share of net fcash that will be credited back to the account netfCash[i] = netfCash[i].mul(tokensToWithdraw[i]).div(totalTokens); } return (tokensToWithdraw, netfCash); } /// @notice Returns the value of all the liquid assets in an nToken portfolio which are defined by /// the liquidity tokens held in each market and their corresponding fCash positions. The formula /// can be described as: /// totalAssetValue = sum_per_liquidity_token(cashClaim + presentValue(netfCash)) /// where netfCash = fCashClaim + fCash /// and fCash refers the the fCash position at the corresponding maturity function getNTokenMarketValue(nTokenPortfolio memory nToken, uint256 blockTime) internal view returns (int256 totalAssetValue, int256[] memory netfCash) { uint256 numMarkets = nToken.portfolioState.storedAssets.length; netfCash = new int256[](numMarkets); MarketParameters memory market; for (uint256 i = 0; i < numMarkets; i++) { // Load the corresponding market into memory nToken.cashGroup.loadMarket(market, i + 1, true, blockTime); PortfolioAsset memory liquidityToken = nToken.portfolioState.storedAssets[i]; uint256 maturity = liquidityToken.maturity; // Get the fCash claims and fCash assets. We do not use haircut versions here because // nTokenRedeem does not require it and getNTokenPV does not use it (a haircut is applied // at the end of the calculation to the entire PV instead). (int256 assetCashClaim, int256 fCashClaim) = AssetHandler.getCashClaims(liquidityToken, market); // fCash is denominated in underlying netfCash[i] = fCashClaim.add( BitmapAssetsHandler.getifCashNotional( nToken.tokenAddress, nToken.cashGroup.currencyId, maturity ) ); // This calculates for a single liquidity token: // assetCashClaim + convertToAssetCash(pv(netfCash)) int256 netAssetValueInMarket = assetCashClaim.add( nToken.cashGroup.assetRate.convertFromUnderlying( AssetHandler.getPresentfCashValue( netfCash[i], maturity, blockTime, // No need to call cash group for oracle rate, it is up to date here // and we are assured to be referring to this market. market.oracleRate ) ) ); // Calculate the running total totalAssetValue = totalAssetValue.add(netAssetValueInMarket); } } /// @notice Returns just the bits in a bitmap that are idiosyncratic function getNTokenifCashBits( address tokenAddress, uint256 currencyId, uint256 lastInitializedTime, uint256 blockTime, uint256 maxMarketIndex ) internal view returns (bytes32) { // If max market index is less than or equal to 2, there are never ifCash assets by construction if (maxMarketIndex <= 2) return bytes32(0); bytes32 assetsBitmap = BitmapAssetsHandler.getAssetsBitmap(tokenAddress, currencyId); // Handles the case when there are no assets at the first initialization if (assetsBitmap == 0) return assetsBitmap; uint256 tRef = DateTime.getReferenceTime(blockTime); if (tRef == lastInitializedTime) { // This is a more efficient way to turn off ifCash assets in the common case when the market is // initialized immediately return assetsBitmap & ~(Constants.ACTIVE_MARKETS_MASK); } else { // In this branch, initialize markets has occurred past the time above. It would occur in these // two scenarios (both should be exceedingly rare): // 1. initializing a cash group with 3+ markets for the first time (not beginning on the tRef) // 2. somehow initialize markets has been delayed for more than 24 hours for (uint i = 1; i <= maxMarketIndex; i++) { // In this loop we get the maturity of each active market and turn off the corresponding bit // one by one. It is less efficient than the option above. uint256 maturity = tRef + DateTime.getTradedMarket(i); (uint256 bitNum, /* */) = DateTime.getBitNumFromMaturity(lastInitializedTime, maturity); assetsBitmap = assetsBitmap.setBit(bitNum, false); } return assetsBitmap; } } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./nTokenHandler.sol"; import "../../global/LibStorage.sol"; import "../../math/SafeInt256.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library nTokenSupply { using SafeInt256 for int256; using SafeMath for uint256; /// @notice Retrieves stored nToken supply and related factors. Do not use accumulatedNOTEPerNToken for calculating /// incentives! Use `getUpdatedAccumulatedNOTEPerNToken` instead. function getStoredNTokenSupplyFactors(address tokenAddress) internal view returns ( uint256 totalSupply, uint256 accumulatedNOTEPerNToken, uint256 lastAccumulatedTime ) { mapping(address => nTokenTotalSupplyStorage) storage store = LibStorage.getNTokenTotalSupplyStorage(); nTokenTotalSupplyStorage storage nTokenStorage = store[tokenAddress]; totalSupply = nTokenStorage.totalSupply; // NOTE: DO NOT USE THIS RETURNED VALUE FOR CALCULATING INCENTIVES. The accumulatedNOTEPerNToken // must be updated given the block time. Use `getUpdatedAccumulatedNOTEPerNToken` instead accumulatedNOTEPerNToken = nTokenStorage.accumulatedNOTEPerNToken; lastAccumulatedTime = nTokenStorage.lastAccumulatedTime; } /// @notice Returns the updated accumulated NOTE per nToken for calculating incentives function getUpdatedAccumulatedNOTEPerNToken(address tokenAddress, uint256 blockTime) internal view returns ( uint256 totalSupply, uint256 accumulatedNOTEPerNToken, uint256 lastAccumulatedTime ) { ( totalSupply, accumulatedNOTEPerNToken, lastAccumulatedTime ) = getStoredNTokenSupplyFactors(tokenAddress); // nToken totalSupply is never allowed to drop to zero but we check this here to avoid // divide by zero errors during initialization. Also ensure that lastAccumulatedTime is not // zero to avoid a massive accumulation amount on initialization. if (blockTime > lastAccumulatedTime && lastAccumulatedTime > 0 && totalSupply > 0) { // prettier-ignore ( /* currencyId */, uint256 emissionRatePerYear, /* initializedTime */, /* assetArrayLength */, /* parameters */ ) = nTokenHandler.getNTokenContext(tokenAddress); uint256 additionalNOTEAccumulatedPerNToken = _calculateAdditionalNOTE( // Emission rate is denominated in whole tokens, scale to 1e8 decimals here emissionRatePerYear.mul(uint256(Constants.INTERNAL_TOKEN_PRECISION)), // Time since last accumulation (overflow checked above) blockTime - lastAccumulatedTime, totalSupply ); accumulatedNOTEPerNToken = accumulatedNOTEPerNToken.add(additionalNOTEAccumulatedPerNToken); require(accumulatedNOTEPerNToken < type(uint128).max); // dev: accumulated NOTE overflow } } /// @notice additionalNOTEPerNToken accumulated since last accumulation time in 1e18 precision function _calculateAdditionalNOTE( uint256 emissionRatePerYear, uint256 timeSinceLastAccumulation, uint256 totalSupply ) private pure returns (uint256) { // If we use 18 decimal places as the accumulation precision then we will overflow uint128 when // a single nToken has accumulated 3.4 x 10^20 NOTE tokens. This isn't possible since the max // NOTE that can accumulate is 10^16 (100 million NOTE in 1e8 precision) so we should be safe // using 18 decimal places and uint128 storage slot // timeSinceLastAccumulation (SECONDS) // accumulatedNOTEPerSharePrecision (1e18) // emissionRatePerYear (INTERNAL_TOKEN_PRECISION) // DIVIDE BY // YEAR (SECONDS) // totalSupply (INTERNAL_TOKEN_PRECISION) return timeSinceLastAccumulation .mul(Constants.INCENTIVE_ACCUMULATION_PRECISION) .mul(emissionRatePerYear) .div(Constants.YEAR) // totalSupply > 0 is checked in the calling function .div(totalSupply); } /// @notice Updates the nToken token supply amount when minting or redeeming. /// @param tokenAddress address of the nToken /// @param netChange positive or negative change to the total nToken supply /// @param blockTime current block time /// @return accumulatedNOTEPerNToken updated to the given block time function changeNTokenSupply( address tokenAddress, int256 netChange, uint256 blockTime ) internal returns (uint256) { ( uint256 totalSupply, uint256 accumulatedNOTEPerNToken, /* uint256 lastAccumulatedTime */ ) = getUpdatedAccumulatedNOTEPerNToken(tokenAddress, blockTime); // Update storage variables mapping(address => nTokenTotalSupplyStorage) storage store = LibStorage.getNTokenTotalSupplyStorage(); nTokenTotalSupplyStorage storage nTokenStorage = store[tokenAddress]; int256 newTotalSupply = int256(totalSupply).add(netChange); // We allow newTotalSupply to equal zero here even though it is prevented from being redeemed down to // exactly zero by other internal logic inside nTokenRedeem. This is meant to be purely an overflow check. require(0 <= newTotalSupply && uint256(newTotalSupply) < type(uint96).max); // dev: nToken supply overflow nTokenStorage.totalSupply = uint96(newTotalSupply); // NOTE: overflow checked inside getUpdatedAccumulatedNOTEPerNToken so that behavior here mirrors what // the user would see if querying the view function nTokenStorage.accumulatedNOTEPerNToken = uint128(accumulatedNOTEPerNToken); require(blockTime < type(uint32).max); // dev: block time overflow nTokenStorage.lastAccumulatedTime = uint32(blockTime); return accumulatedNOTEPerNToken; } /// @notice Called by governance to set the new emission rate function setIncentiveEmissionRate(address tokenAddress, uint32 newEmissionsRate, uint256 blockTime) internal { // Ensure that the accumulatedNOTEPerNToken updates to the current block time before we update the // emission rate changeNTokenSupply(tokenAddress, 0, blockTime); mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage(); nTokenContext storage context = store[tokenAddress]; context.incentiveAnnualEmissionRate = newEmissionsRate; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./Types.sol"; import "./Constants.sol"; import "../../interfaces/notional/IRewarder.sol"; import "../../interfaces/aave/ILendingPool.sol"; library LibStorage { /// @dev Offset for the initial slot in lib storage, gives us this number of storage slots /// available in StorageLayoutV1 and all subsequent storage layouts that inherit from it. uint256 private constant STORAGE_SLOT_BASE = 1000000; /// @dev Set to MAX_TRADED_MARKET_INDEX * 2, Solidity does not allow assigning constants from imported values uint256 private constant NUM_NTOKEN_MARKET_FACTORS = 14; /// @dev Theoretical maximum for MAX_PORTFOLIO_ASSETS, however, we limit this to MAX_TRADED_MARKET_INDEX /// in practice. It is possible to exceed that value during liquidation up to 14 potential assets. uint256 private constant MAX_PORTFOLIO_ASSETS = 16; /// @dev Storage IDs for storage buckets. Each id maps to an internal storage /// slot used for a particular mapping /// WARNING: APPEND ONLY enum StorageId { Unused, AccountStorage, nTokenContext, nTokenAddress, nTokenDeposit, nTokenInitialization, Balance, Token, SettlementRate, CashGroup, Market, AssetsBitmap, ifCashBitmap, PortfolioArray, // WARNING: this nTokenTotalSupply storage object was used for a buggy version // of the incentives calculation. It should only be used for accounts who have // not claimed before the migration nTokenTotalSupply_deprecated, AssetRate, ExchangeRate, nTokenTotalSupply, SecondaryIncentiveRewarder, LendingPool } /// @dev Mapping from an account address to account context function getAccountStorage() internal pure returns (mapping(address => AccountContext) storage store) { uint256 slot = _getStorageSlot(StorageId.AccountStorage); assembly { store.slot := slot } } /// @dev Mapping from an nToken address to nTokenContext function getNTokenContextStorage() internal pure returns (mapping(address => nTokenContext) storage store) { uint256 slot = _getStorageSlot(StorageId.nTokenContext); assembly { store.slot := slot } } /// @dev Mapping from currency id to nTokenAddress function getNTokenAddressStorage() internal pure returns (mapping(uint256 => address) storage store) { uint256 slot = _getStorageSlot(StorageId.nTokenAddress); assembly { store.slot := slot } } /// @dev Mapping from currency id to uint32 fixed length array of /// deposit factors. Deposit shares and leverage thresholds are stored striped to /// reduce the number of storage reads. function getNTokenDepositStorage() internal pure returns (mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store) { uint256 slot = _getStorageSlot(StorageId.nTokenDeposit); assembly { store.slot := slot } } /// @dev Mapping from currency id to fixed length array of initialization factors, /// stored striped like deposit shares. function getNTokenInitStorage() internal pure returns (mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store) { uint256 slot = _getStorageSlot(StorageId.nTokenInitialization); assembly { store.slot := slot } } /// @dev Mapping from account to currencyId to it's balance storage for that currency function getBalanceStorage() internal pure returns (mapping(address => mapping(uint256 => BalanceStorage)) storage store) { uint256 slot = _getStorageSlot(StorageId.Balance); assembly { store.slot := slot } } /// @dev Mapping from currency id to a boolean for underlying or asset token to /// the TokenStorage function getTokenStorage() internal pure returns (mapping(uint256 => mapping(bool => TokenStorage)) storage store) { uint256 slot = _getStorageSlot(StorageId.Token); assembly { store.slot := slot } } /// @dev Mapping from currency id to maturity to its corresponding SettlementRate function getSettlementRateStorage() internal pure returns (mapping(uint256 => mapping(uint256 => SettlementRateStorage)) storage store) { uint256 slot = _getStorageSlot(StorageId.SettlementRate); assembly { store.slot := slot } } /// @dev Mapping from currency id to maturity to its tightly packed cash group parameters function getCashGroupStorage() internal pure returns (mapping(uint256 => bytes32) storage store) { uint256 slot = _getStorageSlot(StorageId.CashGroup); assembly { store.slot := slot } } /// @dev Mapping from currency id to maturity to settlement date for a market function getMarketStorage() internal pure returns (mapping(uint256 => mapping(uint256 => mapping(uint256 => MarketStorage))) storage store) { uint256 slot = _getStorageSlot(StorageId.Market); assembly { store.slot := slot } } /// @dev Mapping from account to currency id to its assets bitmap function getAssetsBitmapStorage() internal pure returns (mapping(address => mapping(uint256 => bytes32)) storage store) { uint256 slot = _getStorageSlot(StorageId.AssetsBitmap); assembly { store.slot := slot } } /// @dev Mapping from account to currency id to its maturity to its corresponding ifCash balance function getifCashBitmapStorage() internal pure returns (mapping(address => mapping(uint256 => mapping(uint256 => ifCashStorage))) storage store) { uint256 slot = _getStorageSlot(StorageId.ifCashBitmap); assembly { store.slot := slot } } /// @dev Mapping from account to its fixed length array of portfolio assets function getPortfolioArrayStorage() internal pure returns (mapping(address => PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS]) storage store) { uint256 slot = _getStorageSlot(StorageId.PortfolioArray); assembly { store.slot := slot } } function getDeprecatedNTokenTotalSupplyStorage() internal pure returns (mapping(address => nTokenTotalSupplyStorage_deprecated) storage store) { uint256 slot = _getStorageSlot(StorageId.nTokenTotalSupply_deprecated); assembly { store.slot := slot } } /// @dev Mapping from nToken address to its total supply values function getNTokenTotalSupplyStorage() internal pure returns (mapping(address => nTokenTotalSupplyStorage) storage store) { uint256 slot = _getStorageSlot(StorageId.nTokenTotalSupply); assembly { store.slot := slot } } /// @dev Returns the exchange rate between an underlying currency and asset for trading /// and free collateral. Mapping is from currency id to rate storage object. function getAssetRateStorage() internal pure returns (mapping(uint256 => AssetRateStorage) storage store) { uint256 slot = _getStorageSlot(StorageId.AssetRate); assembly { store.slot := slot } } /// @dev Returns the exchange rate between an underlying currency and ETH for free /// collateral purposes. Mapping is from currency id to rate storage object. function getExchangeRateStorage() internal pure returns (mapping(uint256 => ETHRateStorage) storage store) { uint256 slot = _getStorageSlot(StorageId.ExchangeRate); assembly { store.slot := slot } } /// @dev Returns the address of a secondary incentive rewarder for an nToken if it exists function getSecondaryIncentiveRewarder() internal pure returns (mapping(address => IRewarder) storage store) { uint256 slot = _getStorageSlot(StorageId.SecondaryIncentiveRewarder); assembly { store.slot := slot } } /// @dev Returns the address of the lending pool function getLendingPool() internal pure returns (LendingPoolStorage storage store) { uint256 slot = _getStorageSlot(StorageId.LendingPool); assembly { store.slot := slot } } /// @dev Get the storage slot given a storage ID. /// @param storageId An entry in `StorageId` /// @return slot The storage slot. function _getStorageSlot(StorageId storageId) private pure returns (uint256 slot) { // This should never overflow with a reasonable `STORAGE_SLOT_EXP` // because Solidity will do a range check on `storageId` during the cast. return uint256(storageId) + STORAGE_SLOT_BASE; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../../global/Constants.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library DateTime { using SafeMath for uint256; /// @notice Returns the current reference time which is how all the AMM dates are calculated. function getReferenceTime(uint256 blockTime) internal pure returns (uint256) { require(blockTime >= Constants.QUARTER); return blockTime - (blockTime % Constants.QUARTER); } /// @notice Truncates a date to midnight UTC time function getTimeUTC0(uint256 time) internal pure returns (uint256) { require(time >= Constants.DAY); return time - (time % Constants.DAY); } /// @notice These are the predetermined market offsets for trading /// @dev Markets are 1-indexed because the 0 index means that no markets are listed for the cash group. function getTradedMarket(uint256 index) internal pure returns (uint256) { if (index == 1) return Constants.QUARTER; if (index == 2) return 2 * Constants.QUARTER; if (index == 3) return Constants.YEAR; if (index == 4) return 2 * Constants.YEAR; if (index == 5) return 5 * Constants.YEAR; if (index == 6) return 10 * Constants.YEAR; if (index == 7) return 20 * Constants.YEAR; revert("Invalid index"); } /// @notice Determines if the maturity falls on one of the valid on chain market dates. function isValidMarketMaturity( uint256 maxMarketIndex, uint256 maturity, uint256 blockTime ) internal pure returns (bool) { require(maxMarketIndex > 0, "CG: no markets listed"); require(maxMarketIndex <= Constants.MAX_TRADED_MARKET_INDEX, "CG: market index bound"); if (maturity % Constants.QUARTER != 0) return false; uint256 tRef = DateTime.getReferenceTime(blockTime); for (uint256 i = 1; i <= maxMarketIndex; i++) { if (maturity == tRef.add(DateTime.getTradedMarket(i))) return true; } return false; } /// @notice Determines if an idiosyncratic maturity is valid and returns the bit reference that is the case. function isValidMaturity( uint256 maxMarketIndex, uint256 maturity, uint256 blockTime ) internal pure returns (bool) { uint256 tRef = DateTime.getReferenceTime(blockTime); uint256 maxMaturity = tRef.add(DateTime.getTradedMarket(maxMarketIndex)); // Cannot trade past max maturity if (maturity > maxMaturity) return false; // prettier-ignore (/* */, bool isValid) = DateTime.getBitNumFromMaturity(blockTime, maturity); return isValid; } /// @notice Returns the market index for a given maturity, if the maturity is idiosyncratic /// will return the nearest market index that is larger than the maturity. /// @return uint marketIndex, bool isIdiosyncratic function getMarketIndex( uint256 maxMarketIndex, uint256 maturity, uint256 blockTime ) internal pure returns (uint256, bool) { require(maxMarketIndex > 0, "CG: no markets listed"); require(maxMarketIndex <= Constants.MAX_TRADED_MARKET_INDEX, "CG: market index bound"); uint256 tRef = DateTime.getReferenceTime(blockTime); for (uint256 i = 1; i <= maxMarketIndex; i++) { uint256 marketMaturity = tRef.add(DateTime.getTradedMarket(i)); // If market matches then is not idiosyncratic if (marketMaturity == maturity) return (i, false); // Returns the market that is immediately greater than the maturity if (marketMaturity > maturity) return (i, true); } revert("CG: no market found"); } /// @notice Given a bit number and the reference time of the first bit, returns the bit number /// of a given maturity. /// @return bitNum and a true or false if the maturity falls on the exact bit function getBitNumFromMaturity(uint256 blockTime, uint256 maturity) internal pure returns (uint256, bool) { uint256 blockTimeUTC0 = getTimeUTC0(blockTime); // Maturities must always divide days evenly if (maturity % Constants.DAY != 0) return (0, false); // Maturity cannot be in the past if (blockTimeUTC0 >= maturity) return (0, false); // Overflow check done above // daysOffset has no remainders, checked above uint256 daysOffset = (maturity - blockTimeUTC0) / Constants.DAY; // These if statements need to fall through to the next one if (daysOffset <= Constants.MAX_DAY_OFFSET) { return (daysOffset, true); } else if (daysOffset <= Constants.MAX_WEEK_OFFSET) { // (daysOffset - MAX_DAY_OFFSET) is the days overflow into the week portion, must be > 0 // (blockTimeUTC0 % WEEK) / DAY is the offset into the week portion // This returns the offset from the previous max offset in days uint256 offsetInDays = daysOffset - Constants.MAX_DAY_OFFSET + (blockTimeUTC0 % Constants.WEEK) / Constants.DAY; return ( // This converts the offset in days to its corresponding bit position, truncating down // if it does not divide evenly into DAYS_IN_WEEK Constants.WEEK_BIT_OFFSET + offsetInDays / Constants.DAYS_IN_WEEK, (offsetInDays % Constants.DAYS_IN_WEEK) == 0 ); } else if (daysOffset <= Constants.MAX_MONTH_OFFSET) { uint256 offsetInDays = daysOffset - Constants.MAX_WEEK_OFFSET + (blockTimeUTC0 % Constants.MONTH) / Constants.DAY; return ( Constants.MONTH_BIT_OFFSET + offsetInDays / Constants.DAYS_IN_MONTH, (offsetInDays % Constants.DAYS_IN_MONTH) == 0 ); } else if (daysOffset <= Constants.MAX_QUARTER_OFFSET) { uint256 offsetInDays = daysOffset - Constants.MAX_MONTH_OFFSET + (blockTimeUTC0 % Constants.QUARTER) / Constants.DAY; return ( Constants.QUARTER_BIT_OFFSET + offsetInDays / Constants.DAYS_IN_QUARTER, (offsetInDays % Constants.DAYS_IN_QUARTER) == 0 ); } // This is the maximum 1-indexed bit num, it is never valid because it is beyond the 20 // year max maturity return (256, false); } /// @notice Given a bit number and a block time returns the maturity that the bit number /// should reference. Bit numbers are one indexed. function getMaturityFromBitNum(uint256 blockTime, uint256 bitNum) internal pure returns (uint256) { require(bitNum != 0); // dev: cash group get maturity from bit num is zero require(bitNum <= 256); // dev: cash group get maturity from bit num overflow uint256 blockTimeUTC0 = getTimeUTC0(blockTime); uint256 firstBit; if (bitNum <= Constants.WEEK_BIT_OFFSET) { return blockTimeUTC0 + bitNum * Constants.DAY; } else if (bitNum <= Constants.MONTH_BIT_OFFSET) { firstBit = blockTimeUTC0 + Constants.MAX_DAY_OFFSET * Constants.DAY - // This backs up to the day that is divisible by a week (blockTimeUTC0 % Constants.WEEK); return firstBit + (bitNum - Constants.WEEK_BIT_OFFSET) * Constants.WEEK; } else if (bitNum <= Constants.QUARTER_BIT_OFFSET) { firstBit = blockTimeUTC0 + Constants.MAX_WEEK_OFFSET * Constants.DAY - (blockTimeUTC0 % Constants.MONTH); return firstBit + (bitNum - Constants.MONTH_BIT_OFFSET) * Constants.MONTH; } else { firstBit = blockTimeUTC0 + Constants.MAX_MONTH_OFFSET * Constants.DAY - (blockTimeUTC0 % Constants.QUARTER); return firstBit + (bitNum - Constants.QUARTER_BIT_OFFSET) * Constants.QUARTER; } } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../../interfaces/chainlink/AggregatorV2V3Interface.sol"; import "../../interfaces/notional/AssetRateAdapter.sol"; /// @notice Different types of internal tokens /// - UnderlyingToken: underlying asset for a cToken (except for Ether) /// - cToken: Compound interest bearing token /// - cETH: Special handling for cETH tokens /// - Ether: the one and only /// - NonMintable: tokens that do not have an underlying (therefore not cTokens) /// - aToken: Aave interest bearing tokens enum TokenType {UnderlyingToken, cToken, cETH, Ether, NonMintable, aToken} /// @notice Specifies the different trade action types in the system. Each trade action type is /// encoded in a tightly packed bytes32 object. Trade action type is the first big endian byte of the /// 32 byte trade action object. The schemas for each trade action type are defined below. enum TradeActionType { // (uint8 TradeActionType, uint8 MarketIndex, uint88 fCashAmount, uint32 minImpliedRate, uint120 unused) Lend, // (uint8 TradeActionType, uint8 MarketIndex, uint88 fCashAmount, uint32 maxImpliedRate, uint128 unused) Borrow, // (uint8 TradeActionType, uint8 MarketIndex, uint88 assetCashAmount, uint32 minImpliedRate, uint32 maxImpliedRate, uint88 unused) AddLiquidity, // (uint8 TradeActionType, uint8 MarketIndex, uint88 tokenAmount, uint32 minImpliedRate, uint32 maxImpliedRate, uint88 unused) RemoveLiquidity, // (uint8 TradeActionType, uint32 Maturity, int88 fCashResidualAmount, uint128 unused) PurchaseNTokenResidual, // (uint8 TradeActionType, address CounterpartyAddress, int88 fCashAmountToSettle) SettleCashDebt } /// @notice Specifies different deposit actions that can occur during BalanceAction or BalanceActionWithTrades enum DepositActionType { // No deposit action None, // Deposit asset cash, depositActionAmount is specified in asset cash external precision DepositAsset, // Deposit underlying tokens that are mintable to asset cash, depositActionAmount is specified in underlying token // external precision DepositUnderlying, // Deposits specified asset cash external precision amount into an nToken and mints the corresponding amount of // nTokens into the account DepositAssetAndMintNToken, // Deposits specified underlying in external precision, mints asset cash, and uses that asset cash to mint nTokens DepositUnderlyingAndMintNToken, // Redeems an nToken balance to asset cash. depositActionAmount is specified in nToken precision. Considered a deposit action // because it deposits asset cash into an account. If there are fCash residuals that cannot be sold off, will revert. RedeemNToken, // Converts specified amount of asset cash balance already in Notional to nTokens. depositActionAmount is specified in // Notional internal 8 decimal precision. ConvertCashToNToken } /// @notice Used internally for PortfolioHandler state enum AssetStorageState {NoChange, Update, Delete, RevertIfStored} /****** Calldata objects ******/ /// @notice Defines a balance action for batchAction struct BalanceAction { // Deposit action to take (if any) DepositActionType actionType; uint16 currencyId; // Deposit action amount must correspond to the depositActionType, see documentation above. uint256 depositActionAmount; // Withdraw an amount of asset cash specified in Notional internal 8 decimal precision uint256 withdrawAmountInternalPrecision; // If set to true, will withdraw entire cash balance. Useful if there may be an unknown amount of asset cash // residual left from trading. bool withdrawEntireCashBalance; // If set to true, will redeem asset cash to the underlying token on withdraw. bool redeemToUnderlying; } /// @notice Defines a balance action with a set of trades to do as well struct BalanceActionWithTrades { DepositActionType actionType; uint16 currencyId; uint256 depositActionAmount; uint256 withdrawAmountInternalPrecision; bool withdrawEntireCashBalance; bool redeemToUnderlying; // Array of tightly packed 32 byte objects that represent trades. See TradeActionType documentation bytes32[] trades; } /****** In memory objects ******/ /// @notice Internal object that represents settled cash balances struct SettleAmount { uint256 currencyId; int256 netCashChange; } /// @notice Internal object that represents a token struct Token { address tokenAddress; bool hasTransferFee; int256 decimals; TokenType tokenType; uint256 maxCollateralBalance; } /// @notice Internal object that represents an nToken portfolio struct nTokenPortfolio { CashGroupParameters cashGroup; PortfolioState portfolioState; int256 totalSupply; int256 cashBalance; uint256 lastInitializedTime; bytes6 parameters; address tokenAddress; } /// @notice Internal object used during liquidation struct LiquidationFactors { address account; // Aggregate free collateral of the account denominated in ETH underlying, 8 decimal precision int256 netETHValue; // Amount of net local currency asset cash before haircuts and buffers available int256 localAssetAvailable; // Amount of net collateral currency asset cash before haircuts and buffers available int256 collateralAssetAvailable; // Haircut value of nToken holdings denominated in asset cash, will be local or collateral nTokens based // on liquidation type int256 nTokenHaircutAssetValue; // nToken parameters for calculating liquidation amount bytes6 nTokenParameters; // ETH exchange rate from local currency to ETH ETHRate localETHRate; // ETH exchange rate from collateral currency to ETH ETHRate collateralETHRate; // Asset rate for the local currency, used in cross currency calculations to calculate local asset cash required AssetRateParameters localAssetRate; // Used during currency liquidations if the account has liquidity tokens CashGroupParameters collateralCashGroup; // Used during currency liquidations if it is only a calculation, defaults to false bool isCalculation; } /// @notice Internal asset array portfolio state struct PortfolioState { // Array of currently stored assets PortfolioAsset[] storedAssets; // Array of new assets to add PortfolioAsset[] newAssets; uint256 lastNewAssetIndex; // Holds the length of stored assets after accounting for deleted assets uint256 storedAssetLength; } /// @notice In memory ETH exchange rate used during free collateral calculation. struct ETHRate { // The decimals (i.e. 10^rateDecimalPlaces) of the exchange rate, defined by the rate oracle int256 rateDecimals; // The exchange rate from base to ETH (if rate invert is required it is already done) int256 rate; // Amount of buffer as a multiple with a basis of 100 applied to negative balances. int256 buffer; // Amount of haircut as a multiple with a basis of 100 applied to positive balances int256 haircut; // Liquidation discount as a multiple with a basis of 100 applied to the exchange rate // as an incentive given to liquidators. int256 liquidationDiscount; } /// @notice Internal object used to handle balance state during a transaction struct BalanceState { uint16 currencyId; // Cash balance stored in balance state at the beginning of the transaction int256 storedCashBalance; // nToken balance stored at the beginning of the transaction int256 storedNTokenBalance; // The net cash change as a result of asset settlement or trading int256 netCashChange; // Net asset transfers into or out of the account int256 netAssetTransferInternalPrecision; // Net token transfers into or out of the account int256 netNTokenTransfer; // Net token supply change from minting or redeeming int256 netNTokenSupplyChange; // The last time incentives were claimed for this currency uint256 lastClaimTime; // Accumulator for incentives that the account no longer has a claim over uint256 accountIncentiveDebt; } /// @dev Asset rate used to convert between underlying cash and asset cash struct AssetRateParameters { // Address of the asset rate oracle AssetRateAdapter rateOracle; // The exchange rate from base to quote (if invert is required it is already done) int256 rate; // The decimals of the underlying, the rate converts to the underlying decimals int256 underlyingDecimals; } /// @dev Cash group when loaded into memory struct CashGroupParameters { uint16 currencyId; uint256 maxMarketIndex; AssetRateParameters assetRate; bytes32 data; } /// @dev A portfolio asset when loaded in memory struct PortfolioAsset { // Asset currency id uint256 currencyId; uint256 maturity; // Asset type, fCash or liquidity token. uint256 assetType; // fCash amount or liquidity token amount int256 notional; // Used for managing portfolio asset state uint256 storageSlot; // The state of the asset for when it is written to storage AssetStorageState storageState; } /// @dev Market object as represented in memory struct MarketParameters { bytes32 storageSlot; uint256 maturity; // Total amount of fCash available for purchase in the market. int256 totalfCash; // Total amount of cash available for purchase in the market. int256 totalAssetCash; // Total amount of liquidity tokens (representing a claim on liquidity) in the market. int256 totalLiquidity; // This is the previous annualized interest rate in RATE_PRECISION that the market traded // at. This is used to calculate the rate anchor to smooth interest rates over time. uint256 lastImpliedRate; // Time lagged version of lastImpliedRate, used to value fCash assets at market rates while // remaining resistent to flash loan attacks. uint256 oracleRate; // This is the timestamp of the previous trade uint256 previousTradeTime; } /****** Storage objects ******/ /// @dev Token object in storage: /// 20 bytes for token address /// 1 byte for hasTransferFee /// 1 byte for tokenType /// 1 byte for tokenDecimals /// 9 bytes for maxCollateralBalance (may not always be set) struct TokenStorage { // Address of the token address tokenAddress; // Transfer fees will change token deposit behavior bool hasTransferFee; TokenType tokenType; uint8 decimalPlaces; // Upper limit on how much of this token the contract can hold at any time uint72 maxCollateralBalance; } /// @dev Exchange rate object as it is represented in storage, total storage is 25 bytes. struct ETHRateStorage { // Address of the rate oracle AggregatorV2V3Interface rateOracle; // The decimal places of precision that the rate oracle uses uint8 rateDecimalPlaces; // True of the exchange rate must be inverted bool mustInvert; // NOTE: both of these governance values are set with BUFFER_DECIMALS precision // Amount of buffer to apply to the exchange rate for negative balances. uint8 buffer; // Amount of haircut to apply to the exchange rate for positive balances uint8 haircut; // Liquidation discount in percentage point terms, 106 means a 6% discount uint8 liquidationDiscount; } /// @dev Asset rate oracle object as it is represented in storage, total storage is 21 bytes. struct AssetRateStorage { // Address of the rate oracle AssetRateAdapter rateOracle; // The decimal places of the underlying asset uint8 underlyingDecimalPlaces; } /// @dev Governance parameters for a cash group, total storage is 9 bytes + 7 bytes for liquidity token haircuts /// and 7 bytes for rate scalars, total of 23 bytes. Note that this is stored packed in the storage slot so there /// are no indexes stored for liquidityTokenHaircuts or rateScalars, maxMarketIndex is used instead to determine the /// length. struct CashGroupSettings { // Index of the AMMs on chain that will be made available. Idiosyncratic fCash // that is dated less than the longest AMM will be tradable. uint8 maxMarketIndex; // Time window in 5 minute increments that the rate oracle will be averaged over uint8 rateOracleTimeWindow5Min; // Total fees per trade, specified in BPS uint8 totalFeeBPS; // Share of the fees given to the protocol, denominated in percentage uint8 reserveFeeShare; // Debt buffer specified in 5 BPS increments uint8 debtBuffer5BPS; // fCash haircut specified in 5 BPS increments uint8 fCashHaircut5BPS; // If an account has a negative cash balance, it can be settled by incurring debt at the 3 month market. This // is the basis points for the penalty rate that will be added the current 3 month oracle rate. uint8 settlementPenaltyRate5BPS; // If an account has fCash that is being liquidated, this is the discount that the liquidator can purchase it for uint8 liquidationfCashHaircut5BPS; // If an account has fCash that is being liquidated, this is the discount that the liquidator can purchase it for uint8 liquidationDebtBuffer5BPS; // Liquidity token haircut applied to cash claims, specified as a percentage between 0 and 100 uint8[] liquidityTokenHaircuts; // Rate scalar used to determine the slippage of the market uint8[] rateScalars; } /// @dev Holds account level context information used to determine settlement and /// free collateral actions. Total storage is 28 bytes struct AccountContext { // Used to check when settlement must be triggered on an account uint40 nextSettleTime; // For lenders that never incur debt, we use this flag to skip the free collateral check. bytes1 hasDebt; // Length of the account's asset array uint8 assetArrayLength; // If this account has bitmaps set, this is the corresponding currency id uint16 bitmapCurrencyId; // 9 total active currencies possible (2 bytes each) bytes18 activeCurrencies; } /// @dev Holds nToken context information mapped via the nToken address, total storage is /// 16 bytes struct nTokenContext { // Currency id that the nToken represents uint16 currencyId; // Annual incentive emission rate denominated in WHOLE TOKENS (multiply by // INTERNAL_TOKEN_PRECISION to get the actual rate) uint32 incentiveAnnualEmissionRate; // The last block time at utc0 that the nToken was initialized at, zero if it // has never been initialized uint32 lastInitializedTime; // Length of the asset array, refers to the number of liquidity tokens an nToken // currently holds uint8 assetArrayLength; // Each byte is a specific nToken parameter bytes5 nTokenParameters; // Reserved bytes for future usage bytes15 _unused; // Set to true if a secondary rewarder is set bool hasSecondaryRewarder; } /// @dev Holds account balance information, total storage 32 bytes struct BalanceStorage { // Number of nTokens held by the account uint80 nTokenBalance; // Last time the account claimed their nTokens uint32 lastClaimTime; // Incentives that the account no longer has a claim over uint56 accountIncentiveDebt; // Cash balance of the account int88 cashBalance; } /// @dev Holds information about a settlement rate, total storage 25 bytes struct SettlementRateStorage { uint40 blockTime; uint128 settlementRate; uint8 underlyingDecimalPlaces; } /// @dev Holds information about a market, total storage is 42 bytes so this spans /// two storage words struct MarketStorage { // Total fCash in the market uint80 totalfCash; // Total asset cash in the market uint80 totalAssetCash; // Last annualized interest rate the market traded at uint32 lastImpliedRate; // Last recorded oracle rate for the market uint32 oracleRate; // Last time a trade was made uint32 previousTradeTime; // This is stored in slot + 1 uint80 totalLiquidity; } struct ifCashStorage { // Notional amount of fCash at the slot, limited to int128 to allow for // future expansion int128 notional; } /// @dev A single portfolio asset in storage, total storage of 19 bytes struct PortfolioAssetStorage { // Currency Id for the asset uint16 currencyId; // Maturity of the asset uint40 maturity; // Asset type (fCash or Liquidity Token marker) uint8 assetType; // Notional int88 notional; } /// @dev nToken total supply factors for the nToken, includes factors related /// to claiming incentives, total storage 32 bytes. This is the deprecated version struct nTokenTotalSupplyStorage_deprecated { // Total supply of the nToken uint96 totalSupply; // Integral of the total supply used for calculating the average total supply uint128 integralTotalSupply; // Last timestamp the supply value changed, used for calculating the integralTotalSupply uint32 lastSupplyChangeTime; } /// @dev nToken total supply factors for the nToken, includes factors related /// to claiming incentives, total storage 32 bytes. struct nTokenTotalSupplyStorage { // Total supply of the nToken uint96 totalSupply; // How many NOTE incentives should be issued per nToken in 1e18 precision uint128 accumulatedNOTEPerNToken; // Last timestamp when the accumulation happened uint32 lastAccumulatedTime; } /// @dev Used in view methods to return account balances in a developer friendly manner struct AccountBalance { uint16 currencyId; int256 cashBalance; int256 nTokenBalance; uint256 lastClaimTime; uint256 accountIncentiveDebt; } // SPDX-License-Identifier: BSD-4-Clause /* * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting. * Author: Mikhail Vladimirov <[email protected]> */ pragma solidity ^0.5.0 || ^0.6.0 || ^0.7.0; /** * Smart contract library of mathematical functions operating with signed * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is * basically a simple fraction whose numerator is signed 128-bit integer and * denominator is 2^64. As long as denominator is always the same, there is no * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are * represented by int128 type holding only the numerator. */ library ABDKMath64x64 { /* * Minimum value signed 64.64-bit fixed point number may have. */ int128 private constant MIN_64x64 = -0x80000000000000000000000000000000; /* * Maximum value signed 64.64-bit fixed point number may have. */ int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; /** * Convert signed 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromInt (int256 x) internal pure returns (int128) { require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF); return int128 (x << 64); } /** * Convert signed 64.64 fixed point number into signed 64-bit integer number * rounding down. * * @param x signed 64.64-bit fixed point number * @return signed 64-bit integer number */ function toInt (int128 x) internal pure returns (int64) { return int64 (x >> 64); } /** * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromUInt (uint256 x) internal pure returns (int128) { require (x <= 0x7FFFFFFFFFFFFFFF); return int128 (x << 64); } /** * Convert signed 64.64 fixed point number into unsigned 64-bit integer * number rounding down. Revert on underflow. * * @param x signed 64.64-bit fixed point number * @return unsigned 64-bit integer number */ function toUInt (int128 x) internal pure returns (uint64) { require (x >= 0); return uint64 (x >> 64); } /** * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point * number rounding down. Revert on overflow. * * @param x signed 128.128-bin fixed point number * @return signed 64.64-bit fixed point number */ function from128x128 (int256 x) internal pure returns (int128) { int256 result = x >> 64; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Convert signed 64.64 fixed point number into signed 128.128 fixed point * number. * * @param x signed 64.64-bit fixed point number * @return signed 128.128 fixed point number */ function to128x128 (int128 x) internal pure returns (int256) { return int256 (x) << 64; } /** * Calculate x + y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function add (int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) + y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x - y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sub (int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) - y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x * y rounding down. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function mul (int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) * y >> 64; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point * number and y is signed 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y signed 256-bit integer number * @return signed 256-bit integer number */ function muli (int128 x, int256 y) internal pure returns (int256) { if (x == MIN_64x64) { require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF && y <= 0x1000000000000000000000000000000000000000000000000); return -y << 63; } else { bool negativeResult = false; if (x < 0) { x = -x; negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint256 absoluteResult = mulu (x, uint256 (y)); if (negativeResult) { require (absoluteResult <= 0x8000000000000000000000000000000000000000000000000000000000000000); return -int256 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int256 (absoluteResult); } } } /** * Calculate x * y rounding down, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y unsigned 256-bit integer number * @return unsigned 256-bit integer number */ function mulu (int128 x, uint256 y) internal pure returns (uint256) { if (y == 0) return 0; require (x >= 0); uint256 lo = (uint256 (x) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64; uint256 hi = uint256 (x) * (y >> 128); require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); hi <<= 64; require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo); return hi + lo; } /** * Calculate x / y rounding towards zero. Revert on overflow or when y is * zero. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function div (int128 x, int128 y) internal pure returns (int128) { require (y != 0); int256 result = (int256 (x) << 64) / y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x / y rounding towards zero, where x and y are signed 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x signed 256-bit integer number * @param y signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function divi (int256 x, int256 y) internal pure returns (int128) { require (y != 0); bool negativeResult = false; if (x < 0) { x = -x; // We rely on overflow behavior here negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint128 absoluteResult = divuu (uint256 (x), uint256 (y)); if (negativeResult) { require (absoluteResult <= 0x80000000000000000000000000000000); return -int128 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int128 (absoluteResult); // We rely on overflow behavior here } } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function divu (uint256 x, uint256 y) internal pure returns (int128) { require (y != 0); uint128 result = divuu (x, y); require (result <= uint128 (MAX_64x64)); return int128 (result); } /** * Calculate -x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function neg (int128 x) internal pure returns (int128) { require (x != MIN_64x64); return -x; } /** * Calculate |x|. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function abs (int128 x) internal pure returns (int128) { require (x != MIN_64x64); return x < 0 ? -x : x; } /** * Calculate 1 / x rounding towards zero. Revert on overflow or when x is * zero. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function inv (int128 x) internal pure returns (int128) { require (x != 0); int256 result = int256 (0x100000000000000000000000000000000) / x; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function avg (int128 x, int128 y) internal pure returns (int128) { return int128 ((int256 (x) + int256 (y)) >> 1); } /** * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down. * Revert on overflow or in case x * y is negative. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function gavg (int128 x, int128 y) internal pure returns (int128) { int256 m = int256 (x) * int256 (y); require (m >= 0); require (m < 0x4000000000000000000000000000000000000000000000000000000000000000); return int128 (sqrtu (uint256 (m))); } /** * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y uint256 value * @return signed 64.64-bit fixed point number */ function pow (int128 x, uint256 y) internal pure returns (int128) { bool negative = x < 0 && y & 1 == 1; uint256 absX = uint128 (x < 0 ? -x : x); uint256 absResult; absResult = 0x100000000000000000000000000000000; if (absX <= 0x10000000000000000) { absX <<= 63; while (y != 0) { if (y & 0x1 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; if (y & 0x2 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; if (y & 0x4 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; if (y & 0x8 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; y >>= 4; } absResult >>= 64; } else { uint256 absXShift = 63; if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; } if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; } if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; } if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; } if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; } if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; } uint256 resultShift = 0; while (y != 0) { require (absXShift < 64); if (y & 0x1 != 0) { absResult = absResult * absX >> 127; resultShift += absXShift; if (absResult > 0x100000000000000000000000000000000) { absResult >>= 1; resultShift += 1; } } absX = absX * absX >> 127; absXShift <<= 1; if (absX >= 0x100000000000000000000000000000000) { absX >>= 1; absXShift += 1; } y >>= 1; } require (resultShift < 64); absResult >>= 64 - resultShift; } int256 result = negative ? -int256 (absResult) : int256 (absResult); require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate sqrt (x) rounding down. Revert if x < 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sqrt (int128 x) internal pure returns (int128) { require (x >= 0); return int128 (sqrtu (uint256 (x) << 64)); } /** * Calculate binary logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function log_2 (int128 x) internal pure returns (int128) { require (x > 0); int256 msb = 0; int256 xc = x; if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; } if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore int256 result = msb - 64 << 64; uint256 ux = uint256 (x) << uint256 (127 - msb); for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) { ux *= ux; uint256 b = ux >> 255; ux >>= 127 + b; result += bit * int256 (b); } return int128 (result); } /** * Calculate natural logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function ln (int128 x) internal pure returns (int128) { require (x > 0); return int128 ( uint256 (log_2 (x)) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128); } /** * Calculate binary exponent of x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function exp_2 (int128 x) internal pure returns (int128) { require (x < 0x400000000000000000); // Overflow if (x < -0x400000000000000000) return 0; // Underflow uint256 result = 0x80000000000000000000000000000000; if (x & 0x8000000000000000 > 0) result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128; if (x & 0x4000000000000000 > 0) result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128; if (x & 0x2000000000000000 > 0) result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128; if (x & 0x1000000000000000 > 0) result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128; if (x & 0x800000000000000 > 0) result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128; if (x & 0x400000000000000 > 0) result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128; if (x & 0x200000000000000 > 0) result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128; if (x & 0x100000000000000 > 0) result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128; if (x & 0x80000000000000 > 0) result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128; if (x & 0x40000000000000 > 0) result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128; if (x & 0x20000000000000 > 0) result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128; if (x & 0x10000000000000 > 0) result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128; if (x & 0x8000000000000 > 0) result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128; if (x & 0x4000000000000 > 0) result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128; if (x & 0x2000000000000 > 0) result = result * 0x1000162E525EE054754457D5995292026 >> 128; if (x & 0x1000000000000 > 0) result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128; if (x & 0x800000000000 > 0) result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128; if (x & 0x400000000000 > 0) result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128; if (x & 0x200000000000 > 0) result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128; if (x & 0x100000000000 > 0) result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128; if (x & 0x80000000000 > 0) result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128; if (x & 0x40000000000 > 0) result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128; if (x & 0x20000000000 > 0) result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128; if (x & 0x10000000000 > 0) result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128; if (x & 0x8000000000 > 0) result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128; if (x & 0x4000000000 > 0) result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128; if (x & 0x2000000000 > 0) result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128; if (x & 0x1000000000 > 0) result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128; if (x & 0x800000000 > 0) result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128; if (x & 0x400000000 > 0) result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128; if (x & 0x200000000 > 0) result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128; if (x & 0x100000000 > 0) result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128; if (x & 0x80000000 > 0) result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128; if (x & 0x40000000 > 0) result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128; if (x & 0x20000000 > 0) result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128; if (x & 0x10000000 > 0) result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128; if (x & 0x8000000 > 0) result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128; if (x & 0x4000000 > 0) result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128; if (x & 0x2000000 > 0) result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128; if (x & 0x1000000 > 0) result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128; if (x & 0x800000 > 0) result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128; if (x & 0x400000 > 0) result = result * 0x100000000002C5C85FDF477B662B26945 >> 128; if (x & 0x200000 > 0) result = result * 0x10000000000162E42FEFA3AE53369388C >> 128; if (x & 0x100000 > 0) result = result * 0x100000000000B17217F7D1D351A389D40 >> 128; if (x & 0x80000 > 0) result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128; if (x & 0x40000 > 0) result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128; if (x & 0x20000 > 0) result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128; if (x & 0x10000 > 0) result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128; if (x & 0x8000 > 0) result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128; if (x & 0x4000 > 0) result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128; if (x & 0x2000 > 0) result = result * 0x1000000000000162E42FEFA39F02B772C >> 128; if (x & 0x1000 > 0) result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128; if (x & 0x800 > 0) result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128; if (x & 0x400 > 0) result = result * 0x100000000000002C5C85FDF473DEA871F >> 128; if (x & 0x200 > 0) result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128; if (x & 0x100 > 0) result = result * 0x100000000000000B17217F7D1CF79E949 >> 128; if (x & 0x80 > 0) result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128; if (x & 0x40 > 0) result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128; if (x & 0x20 > 0) result = result * 0x100000000000000162E42FEFA39EF366F >> 128; if (x & 0x10 > 0) result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128; if (x & 0x8 > 0) result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128; if (x & 0x4 > 0) result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128; if (x & 0x2 > 0) result = result * 0x1000000000000000162E42FEFA39EF358 >> 128; if (x & 0x1 > 0) result = result * 0x10000000000000000B17217F7D1CF79AB >> 128; result >>= uint256 (63 - (x >> 64)); require (result <= uint256 (MAX_64x64)); return int128 (result); } /** * Calculate natural exponent of x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function exp (int128 x) internal pure returns (int128) { require (x < 0x400000000000000000); // Overflow if (x < -0x400000000000000000) return 0; // Underflow return exp_2 ( int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128)); } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return unsigned 64.64-bit fixed point number */ function divuu (uint256 x, uint256 y) private pure returns (uint128) { require (y != 0); uint256 result; if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) result = (x << 64) / y; else { uint256 msb = 192; uint256 xc = x >> 192; if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1); require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 hi = result * (y >> 128); uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 xh = x >> 192; uint256 xl = x << 64; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here lo = hi << 128; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here assert (xh == hi >> 128); result += xl / y; } require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return uint128 (result); } /** * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer * number. * * @param x unsigned 256-bit integer number * @return unsigned 128-bit integer number */ function sqrtu (uint256 x) private pure returns (uint128) { if (x == 0) return 0; else { uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return uint128 (r < r1 ? r : r1); } } } // SPDX-License-Identifier: GPL-v3 pragma solidity >=0.7.0; /// @notice Used as a wrapper for tokens that are interest bearing for an /// underlying token. Follows the cToken interface, however, can be adapted /// for other interest bearing tokens. interface AssetRateAdapter { function token() external view returns (address); function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); function underlying() external view returns (address); function getExchangeRateStateful() external returns (int256); function getExchangeRateView() external view returns (int256); function getAnnualizedSupplyRate() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0; import "./AggregatorInterface.sol"; import "./AggregatorV3Interface.sol"; interface AggregatorV2V3Interface is AggregatorInterface, AggregatorV3Interface { } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0; interface AggregatorInterface { function latestAnswer() external view returns (int256); function latestTimestamp() external view returns (uint256); function latestRound() external view returns (uint256); function getAnswer(uint256 roundId) external view returns (int256); function getTimestamp(uint256 roundId) external view returns (uint256); event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 updatedAt); event NewRound(uint256 indexed roundId, address indexed startedBy, uint256 startedAt); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0; interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; interface IRewarder { function claimRewards( address account, uint16 currencyId, uint256 nTokenBalanceBefore, uint256 nTokenBalanceAfter, int256 netNTokenSupplyChange, uint256 NOTETokensClaimed ) external; } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; struct LendingPoolStorage { ILendingPool lendingPool; } interface ILendingPool { /** * @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens. * - E.g. User deposits 100 USDC and gets in return 100 aUSDC * @param asset The address of the underlying asset to deposit * @param amount The amount to be deposited * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens * is a different wallet * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function deposit( address asset, uint256 amount, address onBehalfOf, uint16 referralCode ) external; /** * @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC * @param asset The address of the underlying asset to withdraw * @param amount The underlying amount to be withdrawn * - Send the value type(uint256).max in order to withdraw the whole aToken balance * @param to Address that will receive the underlying, same as msg.sender if the user * wants to receive it on his own wallet, or a different address if the beneficiary is a * different wallet * @return The final amount withdrawn **/ function withdraw( address asset, uint256 amount, address to ) external returns (uint256); /** * @dev Returns the normalized income normalized income of the reserve * @param asset The address of the underlying asset of the reserve * @return The reserve's normalized income */ function getReserveNormalizedIncome(address asset) external view returns (uint256); /** * @dev Returns the state and configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The state of the reserve **/ function getReserveData(address asset) external view returns (ReserveData memory); // refer to the whitepaper, section 1.1 basic concepts for a formal description of these properties. struct ReserveData { //stores the reserve configuration ReserveConfigurationMap configuration; //the liquidity index. Expressed in ray uint128 liquidityIndex; //variable borrow index. Expressed in ray uint128 variableBorrowIndex; //the current supply rate. Expressed in ray uint128 currentLiquidityRate; //the current variable borrow rate. Expressed in ray uint128 currentVariableBorrowRate; //the current stable borrow rate. Expressed in ray uint128 currentStableBorrowRate; uint40 lastUpdateTimestamp; //tokens addresses address aTokenAddress; address stableDebtTokenAddress; address variableDebtTokenAddress; //address of the interest rate strategy address interestRateStrategyAddress; //the id of the reserve. Represents the position in the list of the active reserves uint8 id; } struct ReserveConfigurationMap { //bit 0-15: LTV //bit 16-31: Liq. threshold //bit 32-47: Liq. bonus //bit 48-55: Decimals //bit 56: Reserve is active //bit 57: reserve is frozen //bit 58: borrowing is enabled //bit 59: stable rate borrowing enabled //bit 60-63: reserved //bit 64-79: reserve factor uint256 data; } struct UserConfigurationMap { uint256 data; } enum InterestRateMode {NONE, STABLE, VARIABLE} } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./TokenHandler.sol"; import "../nToken/nTokenHandler.sol"; import "../nToken/nTokenSupply.sol"; import "../../math/SafeInt256.sol"; import "../../external/MigrateIncentives.sol"; import "../../../interfaces/notional/IRewarder.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library Incentives { using SafeMath for uint256; using SafeInt256 for int256; /// @notice Calculates the total incentives to claim including those claimed under the previous /// less accurate calculation. Once an account is migrated it will only claim incentives under /// the more accurate regime function calculateIncentivesToClaim( BalanceState memory balanceState, address tokenAddress, uint256 accumulatedNOTEPerNToken, uint256 finalNTokenBalance ) internal view returns (uint256 incentivesToClaim) { if (balanceState.lastClaimTime > 0) { // If lastClaimTime is set then the account had incentives under the // previous regime. Will calculate the final amount of incentives to claim here // under the previous regime. incentivesToClaim = MigrateIncentives.migrateAccountFromPreviousCalculation( tokenAddress, balanceState.storedNTokenBalance.toUint(), balanceState.lastClaimTime, // In this case the accountIncentiveDebt is stored as lastClaimIntegralSupply under // the old calculation balanceState.accountIncentiveDebt ); // This marks the account as migrated and lastClaimTime will no longer be used balanceState.lastClaimTime = 0; // This value will be set immediately after this, set this to zero so that the calculation // establishes a new baseline. balanceState.accountIncentiveDebt = 0; } // If an account was migrated then they have no accountIncentivesDebt and should accumulate // incentives based on their share since the new regime calculation started. // If an account is just initiating their nToken balance then storedNTokenBalance will be zero // and they will have no incentives to claim. // This calculation uses storedNTokenBalance which is the balance of the account up until this point, // this is important to ensure that the account does not claim for nTokens that they will mint or // redeem on a going forward basis. // The calculation below has the following precision: // storedNTokenBalance (INTERNAL_TOKEN_PRECISION) // MUL accumulatedNOTEPerNToken (INCENTIVE_ACCUMULATION_PRECISION) // DIV INCENTIVE_ACCUMULATION_PRECISION // = INTERNAL_TOKEN_PRECISION - (accountIncentivesDebt) INTERNAL_TOKEN_PRECISION incentivesToClaim = incentivesToClaim.add( balanceState.storedNTokenBalance.toUint() .mul(accumulatedNOTEPerNToken) .div(Constants.INCENTIVE_ACCUMULATION_PRECISION) .sub(balanceState.accountIncentiveDebt) ); // Update accountIncentivesDebt denominated in INTERNAL_TOKEN_PRECISION which marks the portion // of the accumulatedNOTE that the account no longer has a claim over. Use the finalNTokenBalance // here instead of storedNTokenBalance to mark the overall incentives claim that the account // does not have a claim over. We do not aggregate this value with the previous accountIncentiveDebt // because accumulatedNOTEPerNToken is already an aggregated value. // The calculation below has the following precision: // finalNTokenBalance (INTERNAL_TOKEN_PRECISION) // MUL accumulatedNOTEPerNToken (INCENTIVE_ACCUMULATION_PRECISION) // DIV INCENTIVE_ACCUMULATION_PRECISION // = INTERNAL_TOKEN_PRECISION balanceState.accountIncentiveDebt = finalNTokenBalance .mul(accumulatedNOTEPerNToken) .div(Constants.INCENTIVE_ACCUMULATION_PRECISION); } /// @notice Incentives must be claimed every time nToken balance changes. /// @dev BalanceState.accountIncentiveDebt is updated in place here function claimIncentives( BalanceState memory balanceState, address account, uint256 finalNTokenBalance ) internal returns (uint256 incentivesToClaim) { uint256 blockTime = block.timestamp; address tokenAddress = nTokenHandler.nTokenAddress(balanceState.currencyId); // This will updated the nToken storage and return what the accumulatedNOTEPerNToken // is up until this current block time in 1e18 precision uint256 accumulatedNOTEPerNToken = nTokenSupply.changeNTokenSupply( tokenAddress, balanceState.netNTokenSupplyChange, blockTime ); incentivesToClaim = calculateIncentivesToClaim( balanceState, tokenAddress, accumulatedNOTEPerNToken, finalNTokenBalance ); // If a secondary incentive rewarder is set, then call it IRewarder rewarder = nTokenHandler.getSecondaryRewarder(tokenAddress); if (address(rewarder) != address(0)) { rewarder.claimRewards( account, balanceState.currencyId, // When this method is called from finalize, the storedNTokenBalance has not // been updated to finalNTokenBalance yet so this is the balance before the change. balanceState.storedNTokenBalance.toUint(), finalNTokenBalance, // When the rewarder is called, totalSupply has been updated already so may need to // adjust its calculation using the net supply change figure here. Supply change // may be zero when nTokens are transferred. balanceState.netNTokenSupplyChange, incentivesToClaim ); } if (incentivesToClaim > 0) TokenHandler.transferIncentive(account, incentivesToClaim); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../../math/SafeInt256.sol"; import "../../global/LibStorage.sol"; import "../../global/Types.sol"; import "../../global/Constants.sol"; import "../../global/Deployments.sol"; import "./protocols/AaveHandler.sol"; import "./protocols/CompoundHandler.sol"; import "./protocols/GenericToken.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; /// @notice Handles all external token transfers and events library TokenHandler { using SafeInt256 for int256; using SafeMath for uint256; function setMaxCollateralBalance(uint256 currencyId, uint72 maxCollateralBalance) internal { mapping(uint256 => mapping(bool => TokenStorage)) storage store = LibStorage.getTokenStorage(); TokenStorage storage tokenStorage = store[currencyId][false]; tokenStorage.maxCollateralBalance = maxCollateralBalance; } function getAssetToken(uint256 currencyId) internal view returns (Token memory) { return _getToken(currencyId, false); } function getUnderlyingToken(uint256 currencyId) internal view returns (Token memory) { return _getToken(currencyId, true); } /// @notice Gets token data for a particular currency id, if underlying is set to true then returns /// the underlying token. (These may not always exist) function _getToken(uint256 currencyId, bool underlying) private view returns (Token memory) { mapping(uint256 => mapping(bool => TokenStorage)) storage store = LibStorage.getTokenStorage(); TokenStorage storage tokenStorage = store[currencyId][underlying]; return Token({ tokenAddress: tokenStorage.tokenAddress, hasTransferFee: tokenStorage.hasTransferFee, // No overflow, restricted on storage decimals: int256(10**tokenStorage.decimalPlaces), tokenType: tokenStorage.tokenType, maxCollateralBalance: tokenStorage.maxCollateralBalance }); } /// @notice Sets a token for a currency id. function setToken( uint256 currencyId, bool underlying, TokenStorage memory tokenStorage ) internal { mapping(uint256 => mapping(bool => TokenStorage)) storage store = LibStorage.getTokenStorage(); if (tokenStorage.tokenType == TokenType.Ether && currencyId == Constants.ETH_CURRENCY_ID) { // Hardcoded parameters for ETH just to make sure we don't get it wrong. TokenStorage storage ts = store[currencyId][true]; ts.tokenAddress = address(0); ts.hasTransferFee = false; ts.tokenType = TokenType.Ether; ts.decimalPlaces = Constants.ETH_DECIMAL_PLACES; ts.maxCollateralBalance = 0; return; } // Check token address require(tokenStorage.tokenAddress != address(0), "TH: address is zero"); // Once a token is set we cannot override it. In the case that we do need to do change a token address // then we should explicitly upgrade this method to allow for a token to be changed. Token memory token = _getToken(currencyId, underlying); require( token.tokenAddress == tokenStorage.tokenAddress || token.tokenAddress == address(0), "TH: token cannot be reset" ); require(0 < tokenStorage.decimalPlaces && tokenStorage.decimalPlaces <= Constants.MAX_DECIMAL_PLACES, "TH: invalid decimals"); // Validate token type require(tokenStorage.tokenType != TokenType.Ether); // dev: ether can only be set once if (underlying) { // Underlying tokens cannot have max collateral balances, the contract only has a balance temporarily // during mint and redeem actions. require(tokenStorage.maxCollateralBalance == 0); // dev: underlying cannot have max collateral balance require(tokenStorage.tokenType == TokenType.UnderlyingToken); // dev: underlying token inconsistent } else { require(tokenStorage.tokenType != TokenType.UnderlyingToken); // dev: underlying token inconsistent } if (tokenStorage.tokenType == TokenType.cToken || tokenStorage.tokenType == TokenType.aToken) { // Set the approval for the underlying so that we can mint cTokens or aTokens Token memory underlyingToken = getUnderlyingToken(currencyId); // cTokens call transfer from the tokenAddress, but aTokens use the LendingPool // to initiate all transfers address approvalAddress = tokenStorage.tokenType == TokenType.cToken ? tokenStorage.tokenAddress : address(LibStorage.getLendingPool().lendingPool); // ERC20 tokens should return true on success for an approval, but Tether // does not return a value here so we use the NonStandard interface here to // check that the approval was successful. IEIP20NonStandard(underlyingToken.tokenAddress).approve( approvalAddress, type(uint256).max ); GenericToken.checkReturnCode(); } store[currencyId][underlying] = tokenStorage; } /** * @notice If a token is mintable then will mint it. At this point we expect to have the underlying * balance in the contract already. * @param assetToken the asset token to mint * @param underlyingAmountExternal the amount of underlying to transfer to the mintable token * @return the amount of asset tokens minted, will always be a positive integer */ function mint(Token memory assetToken, uint16 currencyId, uint256 underlyingAmountExternal) internal returns (int256) { // aTokens return the principal plus interest value when calling the balanceOf selector. We cannot use this // value in internal accounting since it will not allow individual users to accrue aToken interest. Use the // scaledBalanceOf function call instead for internal accounting. bytes4 balanceOfSelector = assetToken.tokenType == TokenType.aToken ? AaveHandler.scaledBalanceOfSelector : GenericToken.defaultBalanceOfSelector; uint256 startingBalance = GenericToken.checkBalanceViaSelector(assetToken.tokenAddress, address(this), balanceOfSelector); if (assetToken.tokenType == TokenType.aToken) { Token memory underlyingToken = getUnderlyingToken(currencyId); AaveHandler.mint(underlyingToken, underlyingAmountExternal); } else if (assetToken.tokenType == TokenType.cToken) { CompoundHandler.mint(assetToken, underlyingAmountExternal); } else if (assetToken.tokenType == TokenType.cETH) { CompoundHandler.mintCETH(assetToken); } else { revert(); // dev: non mintable token } uint256 endingBalance = GenericToken.checkBalanceViaSelector(assetToken.tokenAddress, address(this), balanceOfSelector); // This is the starting and ending balance in external precision return SafeInt256.toInt(endingBalance.sub(startingBalance)); } /** * @notice If a token is redeemable to underlying will redeem it and transfer the underlying balance * to the account * @param assetToken asset token to redeem * @param currencyId the currency id of the token * @param account account to transfer the underlying to * @param assetAmountExternal the amount to transfer in asset token denomination and external precision * @return the actual amount of underlying tokens transferred. this is used as a return value back to the * user, is not used for internal accounting purposes */ function redeem( Token memory assetToken, uint256 currencyId, address account, uint256 assetAmountExternal ) internal returns (int256) { uint256 transferAmount; if (assetToken.tokenType == TokenType.cETH) { transferAmount = CompoundHandler.redeemCETH(assetToken, account, assetAmountExternal); } else { Token memory underlyingToken = getUnderlyingToken(currencyId); if (assetToken.tokenType == TokenType.aToken) { transferAmount = AaveHandler.redeem(underlyingToken, account, assetAmountExternal); } else if (assetToken.tokenType == TokenType.cToken) { transferAmount = CompoundHandler.redeem(assetToken, underlyingToken, account, assetAmountExternal); } else { revert(); // dev: non redeemable token } } // Use the negative value here to signify that assets have left the protocol return SafeInt256.toInt(transferAmount).neg(); } /// @notice Handles transfers into and out of the system denominated in the external token decimal /// precision. function transfer( Token memory token, address account, uint256 currencyId, int256 netTransferExternal ) internal returns (int256 actualTransferExternal) { // This will be true in all cases except for deposits where the token has transfer fees. For // aTokens this value is set before convert from scaled balances to principal plus interest actualTransferExternal = netTransferExternal; if (token.tokenType == TokenType.aToken) { Token memory underlyingToken = getUnderlyingToken(currencyId); // aTokens need to be converted when we handle the transfer since the external balance format // is not the same as the internal balance format that we use netTransferExternal = AaveHandler.convertFromScaledBalanceExternal( underlyingToken.tokenAddress, netTransferExternal ); } if (netTransferExternal > 0) { // Deposits must account for transfer fees. int256 netDeposit = _deposit(token, account, uint256(netTransferExternal)); // If an aToken has a transfer fee this will still return a balance figure // in scaledBalanceOf terms due to the selector if (token.hasTransferFee) actualTransferExternal = netDeposit; } else if (token.tokenType == TokenType.Ether) { // netTransferExternal can only be negative or zero at this point GenericToken.transferNativeTokenOut(account, uint256(netTransferExternal.neg())); } else { GenericToken.safeTransferOut( token.tokenAddress, account, // netTransferExternal is zero or negative here uint256(netTransferExternal.neg()) ); } } /// @notice Handles token deposits into Notional. If there is a transfer fee then we must /// calculate the net balance after transfer. Amounts are denominated in the destination token's /// precision. function _deposit( Token memory token, address account, uint256 amount ) private returns (int256) { uint256 startingBalance; uint256 endingBalance; bytes4 balanceOfSelector = token.tokenType == TokenType.aToken ? AaveHandler.scaledBalanceOfSelector : GenericToken.defaultBalanceOfSelector; if (token.hasTransferFee) { startingBalance = GenericToken.checkBalanceViaSelector(token.tokenAddress, address(this), balanceOfSelector); } GenericToken.safeTransferIn(token.tokenAddress, account, amount); if (token.hasTransferFee || token.maxCollateralBalance > 0) { // If aTokens have a max collateral balance then it will be applied against the scaledBalanceOf. This is probably // the correct behavior because if collateral accrues interest over time we should not somehow go over the // maxCollateralBalance due to the passage of time. endingBalance = GenericToken.checkBalanceViaSelector(token.tokenAddress, address(this), balanceOfSelector); } if (token.maxCollateralBalance > 0) { int256 internalPrecisionBalance = convertToInternal(token, SafeInt256.toInt(endingBalance)); // Max collateral balance is stored as uint72, no overflow require(internalPrecisionBalance <= SafeInt256.toInt(token.maxCollateralBalance)); // dev: over max collateral balance } // Math is done in uint inside these statements and will revert on negative if (token.hasTransferFee) { return SafeInt256.toInt(endingBalance.sub(startingBalance)); } else { return SafeInt256.toInt(amount); } } function convertToInternal(Token memory token, int256 amount) internal pure returns (int256) { // If token decimals > INTERNAL_TOKEN_PRECISION: // on deposit: resulting dust will accumulate to protocol // on withdraw: protocol may lose dust amount. However, withdraws are only calculated based // on a conversion from internal token precision to external token precision so therefore dust // amounts cannot be specified for withdraws. // If token decimals < INTERNAL_TOKEN_PRECISION then this will add zeros to the // end of amount and will not result in dust. if (token.decimals == Constants.INTERNAL_TOKEN_PRECISION) return amount; return amount.mul(Constants.INTERNAL_TOKEN_PRECISION).div(token.decimals); } function convertToExternal(Token memory token, int256 amount) internal pure returns (int256) { if (token.decimals == Constants.INTERNAL_TOKEN_PRECISION) return amount; // If token decimals > INTERNAL_TOKEN_PRECISION then this will increase amount // by adding a number of zeros to the end and will not result in dust. // If token decimals < INTERNAL_TOKEN_PRECISION: // on deposit: Deposits are specified in external token precision and there is no loss of precision when // tokens are converted from external to internal precision // on withdraw: this calculation will round down such that the protocol retains the residual cash balance return amount.mul(token.decimals).div(Constants.INTERNAL_TOKEN_PRECISION); } function transferIncentive(address account, uint256 tokensToTransfer) internal { GenericToken.safeTransferOut(Deployments.NOTE_TOKEN_ADDRESS, account, tokensToTransfer); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../global/LibStorage.sol"; import "./balances/BalanceHandler.sol"; import "./portfolio/BitmapAssetsHandler.sol"; import "./portfolio/PortfolioHandler.sol"; library AccountContextHandler { using PortfolioHandler for PortfolioState; bytes18 private constant TURN_OFF_PORTFOLIO_FLAGS = 0x7FFF7FFF7FFF7FFF7FFF7FFF7FFF7FFF7FFF; event AccountContextUpdate(address indexed account); /// @notice Returns the account context of a given account function getAccountContext(address account) internal view returns (AccountContext memory) { mapping(address => AccountContext) storage store = LibStorage.getAccountStorage(); return store[account]; } /// @notice Sets the account context of a given account function setAccountContext(AccountContext memory accountContext, address account) internal { mapping(address => AccountContext) storage store = LibStorage.getAccountStorage(); store[account] = accountContext; emit AccountContextUpdate(account); } function isBitmapEnabled(AccountContext memory accountContext) internal pure returns (bool) { return accountContext.bitmapCurrencyId != 0; } /// @notice Enables a bitmap type portfolio for an account. A bitmap type portfolio allows /// an account to hold more fCash than a normal portfolio, except only in a single currency. /// Once enabled, it cannot be disabled or changed. An account can only enable a bitmap if /// it has no assets or debt so that we ensure no assets are left stranded. /// @param accountContext refers to the account where the bitmap will be enabled /// @param currencyId the id of the currency to enable /// @param blockTime the current block time to set the next settle time function enableBitmapForAccount( AccountContext memory accountContext, uint16 currencyId, uint256 blockTime ) internal view { require(!isBitmapEnabled(accountContext), "Cannot change bitmap"); require(0 < currencyId && currencyId <= Constants.MAX_CURRENCIES, "Invalid currency id"); // Account cannot have assets or debts require(accountContext.assetArrayLength == 0, "Cannot have assets"); require(accountContext.hasDebt == 0x00, "Cannot have debt"); // Ensure that the active currency is set to false in the array so that there is no double // counting during FreeCollateral setActiveCurrency(accountContext, currencyId, false, Constants.ACTIVE_IN_BALANCES); accountContext.bitmapCurrencyId = currencyId; // Setting this is required to initialize the assets bitmap uint256 nextSettleTime = DateTime.getTimeUTC0(blockTime); require(nextSettleTime < type(uint40).max); // dev: blockTime overflow accountContext.nextSettleTime = uint40(nextSettleTime); } /// @notice Returns true if the context needs to settle function mustSettleAssets(AccountContext memory accountContext) internal view returns (bool) { uint256 blockTime = block.timestamp; if (isBitmapEnabled(accountContext)) { // nextSettleTime will be set to utc0 after settlement so we // settle if this is strictly less than utc0 return accountContext.nextSettleTime < DateTime.getTimeUTC0(blockTime); } else { // 0 value occurs on an uninitialized account // Assets mature exactly on the blockTime (not one second past) so in this // case we settle on the block timestamp return 0 < accountContext.nextSettleTime && accountContext.nextSettleTime <= blockTime; } } /// @notice Checks if a currency id (uint16 max) is in the 9 slots in the account /// context active currencies list. /// @dev NOTE: this may be more efficient as a binary search since we know that the array /// is sorted function isActiveInBalances(AccountContext memory accountContext, uint256 currencyId) internal pure returns (bool) { require(currencyId != 0 && currencyId <= Constants.MAX_CURRENCIES); // dev: invalid currency id bytes18 currencies = accountContext.activeCurrencies; if (accountContext.bitmapCurrencyId == currencyId) return true; while (currencies != 0x00) { uint256 cid = uint16(bytes2(currencies) & Constants.UNMASK_FLAGS); if (cid == currencyId) { // Currency found, return if it is active in balances or not return bytes2(currencies) & Constants.ACTIVE_IN_BALANCES == Constants.ACTIVE_IN_BALANCES; } currencies = currencies << 16; } return false; } /// @notice Iterates through the active currency list and removes, inserts or does nothing /// to ensure that the active currency list is an ordered byte array of uint16 currency ids /// that refer to the currencies that an account is active in. /// /// This is called to ensure that currencies are active when the account has a non zero cash balance, /// a non zero nToken balance or a portfolio asset. function setActiveCurrency( AccountContext memory accountContext, uint256 currencyId, bool isActive, bytes2 flags ) internal pure { require(0 < currencyId && currencyId <= Constants.MAX_CURRENCIES); // dev: invalid currency id // If the bitmapped currency is already set then return here. Turning off the bitmap currency // id requires other logical handling so we will do it elsewhere. if (isActive && accountContext.bitmapCurrencyId == currencyId) return; bytes18 prefix; bytes18 suffix = accountContext.activeCurrencies; uint256 shifts; /// There are six possible outcomes from this search: /// 1. The currency id is in the list /// - it must be set to active, do nothing /// - it must be set to inactive, shift suffix and concatenate /// 2. The current id is greater than the one in the search: /// - it must be set to active, append to prefix and then concatenate the suffix, /// ensure that we do not lose the last 2 bytes if set. /// - it must be set to inactive, it is not in the list, do nothing /// 3. Reached the end of the list: /// - it must be set to active, check that the last two bytes are not set and then /// append to the prefix /// - it must be set to inactive, do nothing while (suffix != 0x00) { uint256 cid = uint256(uint16(bytes2(suffix) & Constants.UNMASK_FLAGS)); // if matches and isActive then return, already in list if (cid == currencyId && isActive) { // set flag and return accountContext.activeCurrencies = accountContext.activeCurrencies | (bytes18(flags) >> (shifts * 16)); return; } // if matches and not active then shift suffix to remove if (cid == currencyId && !isActive) { // turn off flag, if both flags are off then remove suffix = suffix & ~bytes18(flags); if (bytes2(suffix) & ~Constants.UNMASK_FLAGS == 0x0000) suffix = suffix << 16; accountContext.activeCurrencies = prefix | (suffix >> (shifts * 16)); return; } // if greater than and isActive then insert into prefix if (cid > currencyId && isActive) { prefix = prefix | (bytes18(bytes2(uint16(currencyId)) | flags) >> (shifts * 16)); // check that the total length is not greater than 9, meaning that the last // two bytes of the active currencies array should be zero require((accountContext.activeCurrencies << 128) == 0x00); // dev: AC: too many currencies // append the suffix accountContext.activeCurrencies = prefix | (suffix >> ((shifts + 1) * 16)); return; } // if past the point of the currency id and not active, not in list if (cid > currencyId && !isActive) return; prefix = prefix | (bytes18(bytes2(suffix)) >> (shifts * 16)); suffix = suffix << 16; shifts += 1; } // If reached this point and not active then return if (!isActive) return; // if end and isActive then insert into suffix, check max length require(shifts < 9); // dev: AC: too many currencies accountContext.activeCurrencies = prefix | (bytes18(bytes2(uint16(currencyId)) | flags) >> (shifts * 16)); } function _clearPortfolioActiveFlags(bytes18 activeCurrencies) internal pure returns (bytes18) { bytes18 result; // This is required to clear the suffix as we append below bytes18 suffix = activeCurrencies & TURN_OFF_PORTFOLIO_FLAGS; uint256 shifts; // This loop will append all currencies that are active in balances into the result. while (suffix != 0x00) { if (bytes2(suffix) & Constants.ACTIVE_IN_BALANCES == Constants.ACTIVE_IN_BALANCES) { // If any flags are active, then append. result = result | (bytes18(bytes2(suffix)) >> shifts); shifts += 16; } suffix = suffix << 16; } return result; } /// @notice Stores a portfolio array and updates the account context information, this method should /// be used whenever updating a portfolio array except in the case of nTokens function storeAssetsAndUpdateContext( AccountContext memory accountContext, address account, PortfolioState memory portfolioState, bool isLiquidation ) internal { // Each of these parameters is recalculated based on the entire array of assets in store assets, // regardless of whether or not they have been updated. (bool hasDebt, bytes32 portfolioCurrencies, uint8 assetArrayLength, uint40 nextSettleTime) = portfolioState.storeAssets(account); accountContext.nextSettleTime = nextSettleTime; require(mustSettleAssets(accountContext) == false); // dev: cannot store matured assets accountContext.assetArrayLength = assetArrayLength; // During liquidation it is possible for an array to go over the max amount of assets allowed due to // liquidity tokens being withdrawn into fCash. if (!isLiquidation) { require(assetArrayLength <= uint8(Constants.MAX_TRADED_MARKET_INDEX)); // dev: max assets allowed } // Sets the hasDebt flag properly based on whether or not portfolio has asset debt, meaning // a negative fCash balance. if (hasDebt) { accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_ASSET_DEBT; } else { // Turns off the ASSET_DEBT flag accountContext.hasDebt = accountContext.hasDebt & ~Constants.HAS_ASSET_DEBT; } // Clear the active portfolio active flags and they will be recalculated in the next step accountContext.activeCurrencies = _clearPortfolioActiveFlags(accountContext.activeCurrencies); uint256 lastCurrency; while (portfolioCurrencies != 0) { // Portfolio currencies will not have flags, it is just an byte array of all the currencies found // in a portfolio. They are appended in a sorted order so we can compare to the previous currency // and only set it if they are different. uint256 currencyId = uint16(bytes2(portfolioCurrencies)); if (currencyId != lastCurrency) { setActiveCurrency(accountContext, currencyId, true, Constants.ACTIVE_IN_PORTFOLIO); } lastCurrency = currencyId; portfolioCurrencies = portfolioCurrencies << 16; } } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; import "./Bitmap.sol"; /** * Packs an uint value into a "floating point" storage slot. Used for storing * lastClaimIntegralSupply values in balance storage. For these values, we don't need * to maintain exact precision but we don't want to be limited by storage size overflows. * * A floating point value is defined by the 48 most significant bits and an 8 bit number * of bit shifts required to restore its precision. The unpacked value will always be less * than the packed value with a maximum absolute loss of precision of (2 ** bitShift) - 1. */ library FloatingPoint56 { function packTo56Bits(uint256 value) internal pure returns (uint56) { uint256 bitShift; // If the value is over the uint48 max value then we will shift it down // given the index of the most significant bit. We store this bit shift // in the least significant byte of the 56 bit slot available. if (value > type(uint48).max) bitShift = (Bitmap.getMSB(value) - 47); uint256 shiftedValue = value >> bitShift; return uint56((shiftedValue << 8) | bitShift); } function unpackFrom56Bits(uint256 value) internal pure returns (uint256) { // The least significant 8 bits will be the amount to bit shift uint256 bitShift = uint256(uint8(value)); return ((value >> 8) << bitShift); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../global/LibStorage.sol"; import "../internal/nToken/nTokenHandler.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; /** * @notice Deployed library for migration of incentives from the old (inaccurate) calculation * to a newer, more accurate calculation based on SushiSwap MasterChef math. The more accurate * calculation is inside `Incentives.sol` and this library holds the legacy calculation. System * migration code can be found in `MigrateIncentivesFix.sol` */ library MigrateIncentives { using SafeMath for uint256; /// @notice Calculates the claimable incentives for a particular nToken and account in the /// previous regime. This should only ever be called ONCE for an account / currency combination /// to get the incentives accrued up until the migration date. function migrateAccountFromPreviousCalculation( address tokenAddress, uint256 nTokenBalance, uint256 lastClaimTime, uint256 lastClaimIntegralSupply ) external view returns (uint256) { ( uint256 finalEmissionRatePerYear, uint256 finalTotalIntegralSupply, uint256 finalMigrationTime ) = _getMigratedIncentiveValues(tokenAddress); // This if statement should never be true but we return 0 just in case if (lastClaimTime == 0 || lastClaimTime >= finalMigrationTime) return 0; // No overflow here, checked above. All incentives are claimed up until finalMigrationTime // using the finalTotalIntegralSupply. Both these values are set on migration and will not // change. uint256 timeSinceMigration = finalMigrationTime - lastClaimTime; // (timeSinceMigration * INTERNAL_TOKEN_PRECISION * finalEmissionRatePerYear) / YEAR uint256 incentiveRate = timeSinceMigration .mul(uint256(Constants.INTERNAL_TOKEN_PRECISION)) // Migration emission rate is stored as is, denominated in whole tokens .mul(finalEmissionRatePerYear).mul(uint256(Constants.INTERNAL_TOKEN_PRECISION)) .div(Constants.YEAR); // Returns the average supply using the integral of the total supply. uint256 avgTotalSupply = finalTotalIntegralSupply.sub(lastClaimIntegralSupply).div(timeSinceMigration); if (avgTotalSupply == 0) return 0; uint256 incentivesToClaim = nTokenBalance.mul(incentiveRate).div(avgTotalSupply); // incentiveRate has a decimal basis of 1e16 so divide by token precision to reduce to 1e8 incentivesToClaim = incentivesToClaim.div(uint256(Constants.INTERNAL_TOKEN_PRECISION)); return incentivesToClaim; } function _getMigratedIncentiveValues( address tokenAddress ) private view returns ( uint256 finalEmissionRatePerYear, uint256 finalTotalIntegralSupply, uint256 finalMigrationTime ) { mapping(address => nTokenTotalSupplyStorage_deprecated) storage store = LibStorage.getDeprecatedNTokenTotalSupplyStorage(); nTokenTotalSupplyStorage_deprecated storage d_nTokenStorage = store[tokenAddress]; // The total supply value is overridden as emissionRatePerYear during the initialization finalEmissionRatePerYear = d_nTokenStorage.totalSupply; finalTotalIntegralSupply = d_nTokenStorage.integralTotalSupply; finalMigrationTime = d_nTokenStorage.lastSupplyChangeTime; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; /// @title Hardcoded deployed contracts are listed here. These are hardcoded to reduce /// gas costs for immutable addresses. They must be updated per environment that Notional /// is deployed to. library Deployments { address internal constant NOTE_TOKEN_ADDRESS = 0xCFEAead4947f0705A14ec42aC3D44129E1Ef3eD5; } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../../../global/Types.sol"; import "../../../global/LibStorage.sol"; import "../../../math/SafeInt256.sol"; import "../TokenHandler.sol"; import "../../../../interfaces/aave/IAToken.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library AaveHandler { using SafeMath for uint256; using SafeInt256 for int256; int256 internal constant RAY = 1e27; int256 internal constant halfRAY = RAY / 2; bytes4 internal constant scaledBalanceOfSelector = IAToken.scaledBalanceOf.selector; /** * @notice Mints an amount of aTokens corresponding to the the underlying. * @param underlyingToken address of the underlying token to pass to Aave * @param underlyingAmountExternal amount of underlying to deposit, in external precision */ function mint(Token memory underlyingToken, uint256 underlyingAmountExternal) internal { // In AaveV3 this method is renamed to supply() but deposit() is still available for // backwards compatibility: https://github.com/aave/aave-v3-core/blob/master/contracts/protocol/pool/Pool.sol#L755 // We use deposit here so that mainnet-fork tests against Aave v2 will pass. LibStorage.getLendingPool().lendingPool.deposit( underlyingToken.tokenAddress, underlyingAmountExternal, address(this), 0 ); } /** * @notice Redeems and sends an amount of aTokens to the specified account * @param underlyingToken address of the underlying token to pass to Aave * @param account account to receive the underlying * @param assetAmountExternal amount of aTokens in scaledBalanceOf terms */ function redeem( Token memory underlyingToken, address account, uint256 assetAmountExternal ) internal returns (uint256 underlyingAmountExternal) { underlyingAmountExternal = convertFromScaledBalanceExternal( underlyingToken.tokenAddress, SafeInt256.toInt(assetAmountExternal) ).toUint(); LibStorage.getLendingPool().lendingPool.withdraw( underlyingToken.tokenAddress, underlyingAmountExternal, account ); } /** * @notice Takes an assetAmountExternal (in this case is the Aave balanceOf representing principal plus interest) * and returns another assetAmountExternal value which represents the Aave scaledBalanceOf (representing a proportional * claim on Aave principal plus interest onto the future). This conversion ensures that depositors into Notional will * receive future Aave interest. * @dev There is no loss of precision within this function since it does the exact same calculation as Aave. * @param currencyId is the currency id * @param assetAmountExternal an Aave token amount representing principal plus interest supplied by the user. This must * be positive in this function, this method is only called when depositing aTokens directly * @return scaledAssetAmountExternal the Aave scaledBalanceOf equivalent. The decimal precision of this value will * be in external precision. */ function convertToScaledBalanceExternal(uint256 currencyId, int256 assetAmountExternal) internal view returns (int256) { if (assetAmountExternal == 0) return 0; require(assetAmountExternal > 0); Token memory underlyingToken = TokenHandler.getUnderlyingToken(currencyId); // We know that this value must be positive int256 index = _getReserveNormalizedIncome(underlyingToken.tokenAddress); // Mimic the WadRay math performed by Aave (but do it in int256 instead) int256 halfIndex = index / 2; // Overflow will occur when: (a * RAY + halfIndex) > int256.max require(assetAmountExternal <= (type(int256).max - halfIndex) / RAY); // if index is zero then this will revert return (assetAmountExternal * RAY + halfIndex) / index; } /** * @notice Takes an assetAmountExternal (in this case is the internal scaledBalanceOf in external decimal precision) * and returns another assetAmountExternal value which represents the Aave balanceOf representing the principal plus interest * that will be transferred. This is required to maintain compatibility with Aave's ERC20 transfer functions. * @dev There is no loss of precision because this does exactly what Aave's calculation would do * @param underlyingToken token address of the underlying asset * @param netScaledBalanceExternal an amount representing the scaledBalanceOf in external decimal precision calculated from * Notional cash balances. This amount may be positive or negative depending on if assets are being deposited (positive) or * withdrawn (negative). * @return netBalanceExternal the Aave balanceOf equivalent as a signed integer */ function convertFromScaledBalanceExternal(address underlyingToken, int256 netScaledBalanceExternal) internal view returns (int256 netBalanceExternal) { if (netScaledBalanceExternal == 0) return 0; // We know that this value must be positive int256 index = _getReserveNormalizedIncome(underlyingToken); // Use the absolute value here so that the halfRay rounding is applied correctly for negative values int256 abs = netScaledBalanceExternal.abs(); // Mimic the WadRay math performed by Aave (but do it in int256 instead) // Overflow will occur when: (abs * index + halfRay) > int256.max // Here the first term is computed at compile time so it just does a division. If index is zero then // solidity will revert. require(abs <= (type(int256).max - halfRAY) / index); int256 absScaled = (abs * index + halfRAY) / RAY; return netScaledBalanceExternal > 0 ? absScaled : absScaled.neg(); } /// @dev getReserveNormalizedIncome returns a uint256, so we know that the return value here is /// always positive even though we are converting to a signed int function _getReserveNormalizedIncome(address underlyingAsset) private view returns (int256) { return SafeInt256.toInt( LibStorage.getLendingPool().lendingPool.getReserveNormalizedIncome(underlyingAsset) ); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./GenericToken.sol"; import "../../../../interfaces/compound/CErc20Interface.sol"; import "../../../../interfaces/compound/CEtherInterface.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../global/Types.sol"; library CompoundHandler { using SafeMath for uint256; // Return code for cTokens that represents no error uint256 internal constant COMPOUND_RETURN_CODE_NO_ERROR = 0; function mintCETH(Token memory token) internal { // Reverts on error CEtherInterface(token.tokenAddress).mint{value: msg.value}(); } function mint(Token memory token, uint256 underlyingAmountExternal) internal returns (int256) { uint256 success = CErc20Interface(token.tokenAddress).mint(underlyingAmountExternal); require(success == COMPOUND_RETURN_CODE_NO_ERROR, "Mint"); } function redeemCETH( Token memory assetToken, address account, uint256 assetAmountExternal ) internal returns (uint256 underlyingAmountExternal) { // Although the contract should never end with any ETH or underlying token balances, we still do this // starting and ending check in the case that tokens are accidentally sent to the contract address. They // will not be sent to some lucky address in a windfall. uint256 startingBalance = address(this).balance; uint256 success = CErc20Interface(assetToken.tokenAddress).redeem(assetAmountExternal); require(success == COMPOUND_RETURN_CODE_NO_ERROR, "Redeem"); uint256 endingBalance = address(this).balance; underlyingAmountExternal = endingBalance.sub(startingBalance); // Withdraws the underlying amount out to the destination account GenericToken.transferNativeTokenOut(account, underlyingAmountExternal); } function redeem( Token memory assetToken, Token memory underlyingToken, address account, uint256 assetAmountExternal ) internal returns (uint256 underlyingAmountExternal) { // Although the contract should never end with any ETH or underlying token balances, we still do this // starting and ending check in the case that tokens are accidentally sent to the contract address. They // will not be sent to some lucky address in a windfall. uint256 startingBalance = GenericToken.checkBalanceViaSelector(underlyingToken.tokenAddress, address(this), GenericToken.defaultBalanceOfSelector); uint256 success = CErc20Interface(assetToken.tokenAddress).redeem(assetAmountExternal); require(success == COMPOUND_RETURN_CODE_NO_ERROR, "Redeem"); uint256 endingBalance = GenericToken.checkBalanceViaSelector(underlyingToken.tokenAddress, address(this), GenericToken.defaultBalanceOfSelector); underlyingAmountExternal = endingBalance.sub(startingBalance); // Withdraws the underlying amount out to the destination account GenericToken.safeTransferOut(underlyingToken.tokenAddress, account, underlyingAmountExternal); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; import "../../../../interfaces/IEIP20NonStandard.sol"; library GenericToken { bytes4 internal constant defaultBalanceOfSelector = IEIP20NonStandard.balanceOf.selector; /** * @dev Manually checks the balance of an account using the method selector. Reduces bytecode size and allows * for overriding the balanceOf selector to use scaledBalanceOf for aTokens */ function checkBalanceViaSelector( address token, address account, bytes4 balanceOfSelector ) internal returns (uint256 balance) { (bool success, bytes memory returnData) = token.staticcall(abi.encodeWithSelector(balanceOfSelector, account)); require(success); (balance) = abi.decode(returnData, (uint256)); } function transferNativeTokenOut( address account, uint256 amount ) internal { // This does not work with contracts, but is reentrancy safe. If contracts want to withdraw underlying // ETH they will have to withdraw the cETH token and then redeem it manually. payable(account).transfer(amount); } function safeTransferOut( address token, address account, uint256 amount ) internal { IEIP20NonStandard(token).transfer(account, amount); checkReturnCode(); } function safeTransferIn( address token, address account, uint256 amount ) internal { IEIP20NonStandard(token).transferFrom(account, address(this), amount); checkReturnCode(); } function checkReturnCode() internal pure { bool success; uint256[1] memory result; assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 success := 1 // set success to true } case 32 { // This is a compliant ERC-20 returndatacopy(result, 0, 32) success := mload(result) // Set `success = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } require(success, "ERC20"); } } // 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: GPL-3.0-only pragma solidity ^0.7.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IAToken { /** * @dev Returns the scaled balance of the user. The scaled balance is the sum of all the * updated stored balance divided by the reserve's liquidity index at the moment of the update * @param user The user whose balance is calculated * @return The scaled balance of the user **/ function scaledBalanceOf(address user) external view returns (uint256); function UNDERLYING_ASSET_ADDRESS() external view returns (address); function symbol() external view returns (string memory); } interface IScaledBalanceToken { /** * @dev Returns the scaled balance of the user. The scaled balance is the sum of all the * updated stored balance divided by the reserve's liquidity index at the moment of the update * @param user The user whose balance is calculated * @return The scaled balance of the user **/ function scaledBalanceOf(address user) external view returns (uint256); /** * @dev Returns the scaled balance of the user and the scaled total supply. * @param user The address of the user * @return The scaled balance of the user * @return The scaled balance and the scaled total supply **/ function getScaledUserBalanceAndSupply(address user) external view returns (uint256, uint256); /** * @dev Returns the scaled total supply of the variable debt token. Represents sum(debt/index) * @return The scaled total supply **/ function scaledTotalSupply() external view returns (uint256); } interface IATokenFull is IScaledBalanceToken, IERC20 { function decimals() external view returns (uint8); } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.7.0; import "./CTokenInterface.sol"; interface CErc20Interface { /*** User Interface ***/ function mint(uint mintAmount) external returns (uint); function redeem(uint redeemTokens) external returns (uint); function redeemUnderlying(uint redeemAmount) external returns (uint); function borrow(uint borrowAmount) external returns (uint); function repayBorrow(uint repayAmount) external returns (uint); function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint); function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) external returns (uint); } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.7.0; interface CEtherInterface { function mint() external payable; } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; /** * @title EIP20NonStandardInterface * @dev Version of ERC20 with no return values for `transfer` and `transferFrom` * See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ interface IEIP20NonStandard { /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return balance */ function balanceOf(address owner) external view returns (uint256 balance); /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer */ function transfer(address dst, uint256 amount) external; /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer */ function transferFrom(address src, address dst, uint256 amount) external; /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `approve` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved */ function approve(address spender, uint256 amount) external; /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return remaining The number of tokens allowed to be spent */ function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.7.0; interface CTokenInterface { /*** User Interface ***/ function underlying() external view returns (address); function transfer(address dst, uint amount) external returns (bool); function transferFrom(address src, address dst, uint amount) external returns (bool); function approve(address spender, uint amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint); function balanceOf(address owner) external view returns (uint); function balanceOfUnderlying(address owner) external returns (uint); function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint); function borrowRatePerBlock() external view returns (uint); function supplyRatePerBlock() external view returns (uint); function totalBorrowsCurrent() external returns (uint); function borrowBalanceCurrent(address account) external returns (uint); function borrowBalanceStored(address account) external view returns (uint); function exchangeRateCurrent() external returns (uint); function exchangeRateStored() external view returns (uint); function getCash() external view returns (uint); function accrueInterest() external returns (uint); function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint); } // 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: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./PortfolioHandler.sol"; import "./BitmapAssetsHandler.sol"; import "../AccountContextHandler.sol"; import "../../global/Types.sol"; import "../../math/SafeInt256.sol"; /// @notice Helper library for transferring assets from one portfolio to another library TransferAssets { using AccountContextHandler for AccountContext; using PortfolioHandler for PortfolioState; using SafeInt256 for int256; /// @notice Decodes asset ids function decodeAssetId(uint256 id) internal pure returns ( uint256 currencyId, uint256 maturity, uint256 assetType ) { assetType = uint8(id); maturity = uint40(id >> 8); currencyId = uint16(id >> 48); } /// @notice Encodes asset ids function encodeAssetId( uint256 currencyId, uint256 maturity, uint256 assetType ) internal pure returns (uint256) { require(currencyId <= Constants.MAX_CURRENCIES); require(maturity <= type(uint40).max); require(assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX); return uint256( (bytes32(uint256(uint16(currencyId))) << 48) | (bytes32(uint256(uint40(maturity))) << 8) | bytes32(uint256(uint8(assetType))) ); } /// @dev Used to flip the sign of assets to decrement the `from` account that is sending assets function invertNotionalAmountsInPlace(PortfolioAsset[] memory assets) internal pure { for (uint256 i; i < assets.length; i++) { assets[i].notional = assets[i].notional.neg(); } } /// @dev Useful method for hiding the logic of updating an account. WARNING: the account /// context returned from this method may not be the same memory location as the account /// context provided if the account is settled. function placeAssetsInAccount( address account, AccountContext memory accountContext, PortfolioAsset[] memory assets ) internal returns (AccountContext memory) { // If an account has assets that require settlement then placing assets inside it // may cause issues. require(!accountContext.mustSettleAssets(), "Account must settle"); if (accountContext.isBitmapEnabled()) { // Adds fCash assets into the account and finalized storage BitmapAssetsHandler.addMultipleifCashAssets(account, accountContext, assets); } else { PortfolioState memory portfolioState = PortfolioHandler.buildPortfolioState( account, accountContext.assetArrayLength, assets.length ); // This will add assets in memory portfolioState.addMultipleAssets(assets); // This will store assets and update the account context in memory accountContext.storeAssetsAndUpdateContext(account, portfolioState, false); } return accountContext; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../../global/Types.sol"; import "../../global/Constants.sol"; import "../markets/CashGroup.sol"; import "../markets/AssetRate.sol"; import "../markets/DateTime.sol"; import "../portfolio/PortfolioHandler.sol"; import "../../math/SafeInt256.sol"; import "../../math/ABDKMath64x64.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library AssetHandler { using SafeMath for uint256; using SafeInt256 for int256; using CashGroup for CashGroupParameters; using AssetRate for AssetRateParameters; function isLiquidityToken(uint256 assetType) internal pure returns (bool) { return assetType >= Constants.MIN_LIQUIDITY_TOKEN_INDEX && assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX; } /// @notice Liquidity tokens settle every 90 days (not at the designated maturity). This method /// calculates the settlement date for any PortfolioAsset. function getSettlementDate(PortfolioAsset memory asset) internal pure returns (uint256) { require(asset.assetType > 0 && asset.assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX); // dev: settlement date invalid asset type // 3 month tokens and fCash tokens settle at maturity if (asset.assetType <= Constants.MIN_LIQUIDITY_TOKEN_INDEX) return asset.maturity; uint256 marketLength = DateTime.getTradedMarket(asset.assetType - 1); // Liquidity tokens settle at tRef + 90 days. The formula to get a maturity is: // maturity = tRef + marketLength // Here we calculate: // tRef = (maturity - marketLength) + 90 days return asset.maturity.sub(marketLength).add(Constants.QUARTER); } /// @notice Returns the continuously compounded discount rate given an oracle rate and a time to maturity. /// The formula is: e^(-rate * timeToMaturity). function getDiscountFactor(uint256 timeToMaturity, uint256 oracleRate) internal pure returns (int256) { int128 expValue = ABDKMath64x64.fromUInt(oracleRate.mul(timeToMaturity).div(Constants.IMPLIED_RATE_TIME)); expValue = ABDKMath64x64.div(expValue, Constants.RATE_PRECISION_64x64); expValue = ABDKMath64x64.exp(ABDKMath64x64.neg(expValue)); expValue = ABDKMath64x64.mul(expValue, Constants.RATE_PRECISION_64x64); int256 discountFactor = ABDKMath64x64.toInt(expValue); return discountFactor; } /// @notice Present value of an fCash asset without any risk adjustments. function getPresentfCashValue( int256 notional, uint256 maturity, uint256 blockTime, uint256 oracleRate ) internal pure returns (int256) { if (notional == 0) return 0; // NOTE: this will revert if maturity < blockTime. That is the correct behavior because we cannot // discount matured assets. uint256 timeToMaturity = maturity.sub(blockTime); int256 discountFactor = getDiscountFactor(timeToMaturity, oracleRate); require(discountFactor <= Constants.RATE_PRECISION); // dev: get present value invalid discount factor return notional.mulInRatePrecision(discountFactor); } /// @notice Present value of an fCash asset with risk adjustments. Positive fCash value will be discounted more /// heavily than the oracle rate given and vice versa for negative fCash. function getRiskAdjustedPresentfCashValue( CashGroupParameters memory cashGroup, int256 notional, uint256 maturity, uint256 blockTime, uint256 oracleRate ) internal pure returns (int256) { if (notional == 0) return 0; // NOTE: this will revert if maturity < blockTime. That is the correct behavior because we cannot // discount matured assets. uint256 timeToMaturity = maturity.sub(blockTime); int256 discountFactor; if (notional > 0) { // If fCash is positive then discounting by a higher rate will result in a smaller // discount factor (e ^ -x), meaning a lower positive fCash value. discountFactor = getDiscountFactor( timeToMaturity, oracleRate.add(cashGroup.getfCashHaircut()) ); } else { uint256 debtBuffer = cashGroup.getDebtBuffer(); // If the adjustment exceeds the oracle rate we floor the value of the fCash // at the notional value. We don't want to require the account to hold more than // absolutely required. if (debtBuffer >= oracleRate) return notional; discountFactor = getDiscountFactor(timeToMaturity, oracleRate - debtBuffer); } require(discountFactor <= Constants.RATE_PRECISION); // dev: get risk adjusted pv, invalid discount factor return notional.mulInRatePrecision(discountFactor); } /// @notice Returns the non haircut claims on cash and fCash by the liquidity token. function getCashClaims(PortfolioAsset memory token, MarketParameters memory market) internal pure returns (int256 assetCash, int256 fCash) { require(isLiquidityToken(token.assetType) && token.notional >= 0); // dev: invalid asset, get cash claims assetCash = market.totalAssetCash.mul(token.notional).div(market.totalLiquidity); fCash = market.totalfCash.mul(token.notional).div(market.totalLiquidity); } /// @notice Returns the haircut claims on cash and fCash function getHaircutCashClaims( PortfolioAsset memory token, MarketParameters memory market, CashGroupParameters memory cashGroup ) internal pure returns (int256 assetCash, int256 fCash) { require(isLiquidityToken(token.assetType) && token.notional >= 0); // dev: invalid asset get haircut cash claims require(token.currencyId == cashGroup.currencyId); // dev: haircut cash claims, currency id mismatch // This won't overflow, the liquidity token haircut is stored as an uint8 int256 haircut = int256(cashGroup.getLiquidityHaircut(token.assetType)); assetCash = _calcToken(market.totalAssetCash, token.notional, haircut, market.totalLiquidity); fCash = _calcToken(market.totalfCash, token.notional, haircut, market.totalLiquidity); return (assetCash, fCash); } /// @dev This is here to clean up the stack in getHaircutCashClaims function _calcToken( int256 numerator, int256 tokens, int256 haircut, int256 liquidity ) private pure returns (int256) { return numerator.mul(tokens).mul(haircut).div(Constants.PERCENTAGE_DECIMALS).div(liquidity); } /// @notice Returns the asset cash claim and the present value of the fCash asset (if it exists) function getLiquidityTokenValue( uint256 index, CashGroupParameters memory cashGroup, MarketParameters memory market, PortfolioAsset[] memory assets, uint256 blockTime, bool riskAdjusted ) internal view returns (int256, int256) { PortfolioAsset memory liquidityToken = assets[index]; { (uint256 marketIndex, bool idiosyncratic) = DateTime.getMarketIndex( cashGroup.maxMarketIndex, liquidityToken.maturity, blockTime ); // Liquidity tokens can never be idiosyncratic require(!idiosyncratic); // dev: idiosyncratic liquidity token // This market will always be initialized, if a liquidity token exists that means the // market has some liquidity in it. cashGroup.loadMarket(market, marketIndex, true, blockTime); } int256 assetCashClaim; int256 fCashClaim; if (riskAdjusted) { (assetCashClaim, fCashClaim) = getHaircutCashClaims(liquidityToken, market, cashGroup); } else { (assetCashClaim, fCashClaim) = getCashClaims(liquidityToken, market); } // Find the matching fCash asset and net off the value, assumes that the portfolio is sorted and // in that case we know the previous asset will be the matching fCash asset if (index > 0) { PortfolioAsset memory maybefCash = assets[index - 1]; if ( maybefCash.assetType == Constants.FCASH_ASSET_TYPE && maybefCash.currencyId == liquidityToken.currencyId && maybefCash.maturity == liquidityToken.maturity ) { // Net off the fCashClaim here and we will discount it to present value in the second pass. // WARNING: this modifies the portfolio in memory and therefore we cannot store this portfolio! maybefCash.notional = maybefCash.notional.add(fCashClaim); // This state will prevent the fCash asset from being stored. maybefCash.storageState = AssetStorageState.RevertIfStored; return (assetCashClaim, 0); } } // If not matching fCash asset found then get the pv directly if (riskAdjusted) { int256 pv = getRiskAdjustedPresentfCashValue( cashGroup, fCashClaim, liquidityToken.maturity, blockTime, market.oracleRate ); return (assetCashClaim, pv); } else { int256 pv = getPresentfCashValue(fCashClaim, liquidityToken.maturity, blockTime, market.oracleRate); return (assetCashClaim, pv); } } /// @notice Returns present value of all assets in the cash group as asset cash and the updated /// portfolio index where the function has ended. /// @return the value of the cash group in asset cash function getNetCashGroupValue( PortfolioAsset[] memory assets, CashGroupParameters memory cashGroup, MarketParameters memory market, uint256 blockTime, uint256 portfolioIndex ) internal view returns (int256, uint256) { int256 presentValueAsset; int256 presentValueUnderlying; // First calculate value of liquidity tokens because we need to net off fCash value // before discounting to present value for (uint256 i = portfolioIndex; i < assets.length; i++) { if (!isLiquidityToken(assets[i].assetType)) continue; if (assets[i].currencyId != cashGroup.currencyId) break; (int256 assetCashClaim, int256 pv) = getLiquidityTokenValue( i, cashGroup, market, assets, blockTime, true // risk adjusted ); presentValueAsset = presentValueAsset.add(assetCashClaim); presentValueUnderlying = presentValueUnderlying.add(pv); } uint256 j = portfolioIndex; for (; j < assets.length; j++) { PortfolioAsset memory a = assets[j]; if (a.assetType != Constants.FCASH_ASSET_TYPE) continue; // If we hit a different currency id then we've accounted for all assets in this currency // j will mark the index where we don't have this currency anymore if (a.currencyId != cashGroup.currencyId) break; uint256 oracleRate = cashGroup.calculateOracleRate(a.maturity, blockTime); int256 pv = getRiskAdjustedPresentfCashValue( cashGroup, a.notional, a.maturity, blockTime, oracleRate ); presentValueUnderlying = presentValueUnderlying.add(pv); } presentValueAsset = presentValueAsset.add( cashGroup.assetRate.convertFromUnderlying(presentValueUnderlying) ); return (presentValueAsset, j); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../AccountContextHandler.sol"; import "../markets/CashGroup.sol"; import "../valuation/AssetHandler.sol"; import "../../math/Bitmap.sol"; import "../../math/SafeInt256.sol"; import "../../global/LibStorage.sol"; import "../../global/Constants.sol"; import "../../global/Types.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library BitmapAssetsHandler { using SafeMath for uint256; using SafeInt256 for int256; using Bitmap for bytes32; using CashGroup for CashGroupParameters; using AccountContextHandler for AccountContext; function getAssetsBitmap(address account, uint256 currencyId) internal view returns (bytes32 assetsBitmap) { mapping(address => mapping(uint256 => bytes32)) storage store = LibStorage.getAssetsBitmapStorage(); return store[account][currencyId]; } function setAssetsBitmap( address account, uint256 currencyId, bytes32 assetsBitmap ) internal { require(assetsBitmap.totalBitsSet() <= Constants.MAX_BITMAP_ASSETS, "Over max assets"); mapping(address => mapping(uint256 => bytes32)) storage store = LibStorage.getAssetsBitmapStorage(); store[account][currencyId] = assetsBitmap; } function getifCashNotional( address account, uint256 currencyId, uint256 maturity ) internal view returns (int256 notional) { mapping(address => mapping(uint256 => mapping(uint256 => ifCashStorage))) storage store = LibStorage.getifCashBitmapStorage(); return store[account][currencyId][maturity].notional; } /// @notice Adds multiple assets to a bitmap portfolio function addMultipleifCashAssets( address account, AccountContext memory accountContext, PortfolioAsset[] memory assets ) internal { require(accountContext.isBitmapEnabled()); // dev: bitmap currency not set uint256 currencyId = accountContext.bitmapCurrencyId; for (uint256 i; i < assets.length; i++) { PortfolioAsset memory asset = assets[i]; if (asset.notional == 0) continue; require(asset.currencyId == currencyId); // dev: invalid asset in set ifcash assets require(asset.assetType == Constants.FCASH_ASSET_TYPE); // dev: invalid asset in set ifcash assets int256 finalNotional; finalNotional = addifCashAsset( account, currencyId, asset.maturity, accountContext.nextSettleTime, asset.notional ); if (finalNotional < 0) accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_ASSET_DEBT; } } /// @notice Add an ifCash asset in the bitmap and mapping. Updates the bitmap in memory /// but not in storage. /// @return the updated assets bitmap and the final notional amount function addifCashAsset( address account, uint256 currencyId, uint256 maturity, uint256 nextSettleTime, int256 notional ) internal returns (int256) { bytes32 assetsBitmap = getAssetsBitmap(account, currencyId); mapping(address => mapping(uint256 => mapping(uint256 => ifCashStorage))) storage store = LibStorage.getifCashBitmapStorage(); ifCashStorage storage fCashSlot = store[account][currencyId][maturity]; (uint256 bitNum, bool isExact) = DateTime.getBitNumFromMaturity(nextSettleTime, maturity); require(isExact); // dev: invalid maturity in set ifcash asset if (assetsBitmap.isBitSet(bitNum)) { // Bit is set so we read and update the notional amount int256 finalNotional = notional.add(fCashSlot.notional); require(type(int128).min <= finalNotional && finalNotional <= type(int128).max); // dev: bitmap notional overflow fCashSlot.notional = int128(finalNotional); // If the new notional is zero then turn off the bit if (finalNotional == 0) { assetsBitmap = assetsBitmap.setBit(bitNum, false); } setAssetsBitmap(account, currencyId, assetsBitmap); return finalNotional; } if (notional != 0) { // Bit is not set so we turn it on and update the mapping directly, no read required. require(type(int128).min <= notional && notional <= type(int128).max); // dev: bitmap notional overflow fCashSlot.notional = int128(notional); assetsBitmap = assetsBitmap.setBit(bitNum, true); setAssetsBitmap(account, currencyId, assetsBitmap); } return notional; } /// @notice Returns the present value of an asset function getPresentValue( address account, uint256 currencyId, uint256 maturity, uint256 blockTime, CashGroupParameters memory cashGroup, bool riskAdjusted ) internal view returns (int256) { int256 notional = getifCashNotional(account, currencyId, maturity); // In this case the asset has matured and the total value is just the notional amount if (maturity <= blockTime) { return notional; } else { uint256 oracleRate = cashGroup.calculateOracleRate(maturity, blockTime); if (riskAdjusted) { return AssetHandler.getRiskAdjustedPresentfCashValue( cashGroup, notional, maturity, blockTime, oracleRate ); } else { return AssetHandler.getPresentfCashValue( notional, maturity, blockTime, oracleRate ); } } } function getNetPresentValueFromBitmap( address account, uint256 currencyId, uint256 nextSettleTime, uint256 blockTime, CashGroupParameters memory cashGroup, bool riskAdjusted, bytes32 assetsBitmap ) internal view returns (int256 totalValueUnderlying, bool hasDebt) { uint256 bitNum = assetsBitmap.getNextBitNum(); while (bitNum != 0) { uint256 maturity = DateTime.getMaturityFromBitNum(nextSettleTime, bitNum); int256 pv = getPresentValue( account, currencyId, maturity, blockTime, cashGroup, riskAdjusted ); totalValueUnderlying = totalValueUnderlying.add(pv); if (pv < 0) hasDebt = true; // Turn off the bit and look for the next one assetsBitmap = assetsBitmap.setBit(bitNum, false); bitNum = assetsBitmap.getNextBitNum(); } } /// @notice Get the net present value of all the ifCash assets function getifCashNetPresentValue( address account, uint256 currencyId, uint256 nextSettleTime, uint256 blockTime, CashGroupParameters memory cashGroup, bool riskAdjusted ) internal view returns (int256 totalValueUnderlying, bool hasDebt) { bytes32 assetsBitmap = getAssetsBitmap(account, currencyId); return getNetPresentValueFromBitmap( account, currencyId, nextSettleTime, blockTime, cashGroup, riskAdjusted, assetsBitmap ); } /// @notice Returns the ifCash assets as an array function getifCashArray( address account, uint256 currencyId, uint256 nextSettleTime ) internal view returns (PortfolioAsset[] memory) { bytes32 assetsBitmap = getAssetsBitmap(account, currencyId); uint256 index = assetsBitmap.totalBitsSet(); PortfolioAsset[] memory assets = new PortfolioAsset[](index); index = 0; uint256 bitNum = assetsBitmap.getNextBitNum(); while (bitNum != 0) { uint256 maturity = DateTime.getMaturityFromBitNum(nextSettleTime, bitNum); int256 notional = getifCashNotional(account, currencyId, maturity); PortfolioAsset memory asset = assets[index]; asset.currencyId = currencyId; asset.maturity = maturity; asset.assetType = Constants.FCASH_ASSET_TYPE; asset.notional = notional; index += 1; // Turn off the bit and look for the next one assetsBitmap = assetsBitmap.setBit(bitNum, false); bitNum = assetsBitmap.getNextBitNum(); } return assets; } }
Turn off the bit and look for the next one
assetsBitmap = assetsBitmap.setBit(bitNum, false);
10,065,371
[ 1, 15858, 3397, 326, 2831, 471, 2324, 364, 326, 1024, 1245, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5411, 7176, 12224, 273, 7176, 12224, 18, 542, 5775, 12, 3682, 2578, 16, 629, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.24; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } /** * @title Beths base contract * @author clemlak (https://www.beths.co) * @notice Place bets using Ether, based on the "pari mutuel" principle * Only the owner of the contract can create bets, he can also take a cut on every payouts * @dev This is the base contract for our dapp, we manage here all the things related to the "house" */ contract BethsHouse is Ownable { /** * @notice Emitted when the house cut percentage is changed * @param newHouseCutPercentage The new percentage */ event HouseCutPercentageChanged(uint newHouseCutPercentage); /** * @notice The percentage taken by the house on every game * @dev Can be changed later with the changeHouseCutPercentage() function */ uint public houseCutPercentage = 10; /** * @notice Changes the house cut percentage * @dev To prevent abuses, the new percentage is checked * @param newHouseCutPercentage The new house cut percentage */ function changeHouseCutPercentage(uint newHouseCutPercentage) external onlyOwner { // This prevents us from being too greedy ;) if (newHouseCutPercentage >= 0 && newHouseCutPercentage < 20) { houseCutPercentage = newHouseCutPercentage; emit HouseCutPercentageChanged(newHouseCutPercentage); } } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /** * @title We manage all the things related to our games here * @author Clemlak (https://www.beths.co) */ contract BethsGame is BethsHouse { /** * @notice We use the SafeMath library in order to prevent overflow errors * @dev Don't forget to use add(), sub(), ... instead of +, -, ... */ using SafeMath for uint256; /** * @notice Emitted when a new game is opened * @param gameId The id of the corresponding game * @param teamA The name of the team A * @param teamB The name of the team B * @param description A small description of the game * @param frozenTimestamp The exact moment when the game will be frozen */ event GameHasOpened(uint gameId, string teamA, string teamB, string description, uint frozenTimestamp); /** * @notice Emitted when a game is frozen * @param gameId The id of the corresponding game */ event GameHasFrozen(uint gameId); /** * @notice Emitted when a game is closed * @param gameId The id of the corresponding game * @param result The result of the game (see: enum GameResults) */ event GameHasClosed(uint gameId, GameResults result); /** * @notice All the different states a game can have (only 1 at a time) */ enum GameStates { Open, Frozen, Closed } /** * @notice All the possible results (only 1 at a time) * @dev All new games are initialized with a NotYet result */ enum GameResults { NotYet, TeamA, Draw, TeamB } /** * @notice This struct defines what a game is */ struct Game { string teamA; uint amountToTeamA; string teamB; uint amountToTeamB; uint amountToDraw; string description; uint frozenTimestamp; uint bettorsCount; GameResults result; GameStates state; bool isHouseCutWithdrawn; } /** * @notice We store all our games in an array */ Game[] public games; /** * @notice This function creates a new game * @dev Can only be called externally by the owner * @param teamA The name of the team A * @param teamB The name of the team B * @param description A small description of the game * @param frozenTimestamp A timestamp representing when the game will be frozen */ function createNewGame( string teamA, string teamB, string description, uint frozenTimestamp ) external onlyOwner { // We push the new game directly into our array uint gameId = games.push(Game( teamA, 0, teamB, 0, 0, description, frozenTimestamp, 0, GameResults.NotYet, GameStates.Open, false )) - 1; emit GameHasOpened(gameId, teamA, teamB, description, frozenTimestamp); } /** * @notice We use this function to froze a game * @dev Can only be called externally by the owner * @param gameId The id of the corresponding game */ function freezeGame(uint gameId) external onlyOwner whenGameIsOpen(gameId) { games[gameId].state = GameStates.Frozen; emit GameHasFrozen(gameId); } /** * @notice We use this function to close a game * @dev Can only be called by the owner when a game is frozen * @param gameId The id of a specific game * @param result The result of the game (see: enum GameResults) */ function closeGame(uint gameId, GameResults result) external onlyOwner whenGameIsFrozen(gameId) { games[gameId].state = GameStates.Closed; games[gameId].result = result; emit GameHasClosed(gameId, result); } /** * @notice Returns some basic information about a specific game * @dev This function DOES NOT return the bets-related info, the current state or the result of the game * @param gameId The id of the corresponding game */ function getGameInfo(uint gameId) public view returns ( string, string, string ) { return ( games[gameId].teamA, games[gameId].teamB, games[gameId].description ); } /** * @notice Returns all the info related to the bets * @dev Use other functions for more info * @param gameId The id of the corresponding game */ function getGameAmounts(uint gameId) public view returns ( uint, uint, uint, uint, uint ) { return ( games[gameId].amountToTeamA, games[gameId].amountToDraw, games[gameId].amountToTeamB, games[gameId].bettorsCount, games[gameId].frozenTimestamp ); } /** * @notice Returns the state of a specific game * @dev Use other functions for more info * @param gameId The id of the corresponding game */ function getGameState(uint gameId) public view returns (GameStates) { return games[gameId].state; } /** * @notice Returns the result of a specific game * @dev Use other functions for more info * @param gameId The id of the corresponding game */ function getGameResult(uint gameId) public view returns (GameResults) { return games[gameId].result; } /** * @notice Returns the total number of games */ function getTotalGames() public view returns (uint) { return games.length; } /** * @dev Compare 2 strings and returns true if they are identical * This function even work if a string is in memory and the other in storage * @param a The first string * @param b The second string */ function compareStrings(string a, string b) internal pure returns (bool) { return keccak256(abi.encodePacked(a)) == keccak256(abi.encodePacked(b)); } /** * @dev Prevent to interact if the game is not open * @param gameId The id of a specific game */ modifier whenGameIsOpen(uint gameId) { require(games[gameId].state == GameStates.Open); _; } /** * @dev Prevent to interact if the game is not frozen * @param gameId The id of a specific game */ modifier whenGameIsFrozen(uint gameId) { require(games[gameId].state == GameStates.Frozen); _; } /** * @dev Prevent to interact if the game is not closed * @param gameId The id of a specific game */ modifier whenGameIsClosed(uint gameId) { require(games[gameId].state == GameStates.Closed); _; } } /** * @title We manage all the things related to our bets here * @author Clemlak (https://www.beths.co) */ contract BethsBet is BethsGame { /** * @notice Emitted when a new bet is placed * @param gameId The name of the corresponding game * @param result The result expected by the bettor (see: enum GameResults) * @param amount How much the bettor placed */ event NewBetPlaced(uint gameId, GameResults result, uint amount); /** * @notice The minimum amount needed to place bet (in Wei) * @dev Can be changed later by the changeMinimumBetAmount() function */ uint public minimumBetAmount = 1000000000; /** * @notice This struct defines what a bet is */ struct Bet { uint gameId; GameResults result; uint amount; bool isPayoutWithdrawn; } /** * @notice We store all our bets in an array */ Bet[] public bets; /** * @notice This links bets with bettors */ mapping (uint => address) public betToAddress; /** * @notice This links the bettor to their bets */ mapping (address => uint[]) public addressToBets; /** * @notice Changes the minimum amount needed to place a bet * @dev The amount is in Wei and must be greater than 0 (can only be changed by the owner) * @param newMinimumBetAmount The new amount */ function changeMinimumBetAmount(uint newMinimumBetAmount) external onlyOwner { if (newMinimumBetAmount > 0) { minimumBetAmount = newMinimumBetAmount; } } /** * @notice Place a new bet * @dev This function is payable and we'll use the amount we receive as the bet amount * Bets can only be placed while the game is open * @param gameId The id of the corresponding game * @param result The result expected by the bettor (see enum GameResults) */ function placeNewBet(uint gameId, GameResults result) public whenGameIsOpen(gameId) payable { // We check if the bet amount is greater or equal to our minimum if (msg.value >= minimumBetAmount) { // We push our bet in our main array uint betId = bets.push(Bet(gameId, result, msg.value, false)) - 1; // We link the bet with the bettor betToAddress[betId] = msg.sender; // We link the address with their bets addressToBets[msg.sender].push(betId); // Then we update our game games[gameId].bettorsCount = games[gameId].bettorsCount.add(1); // And we update the amount bet on the expected result if (result == GameResults.TeamA) { games[gameId].amountToTeamA = games[gameId].amountToTeamA.add(msg.value); } else if (result == GameResults.Draw) { games[gameId].amountToDraw = games[gameId].amountToDraw.add(msg.value); } else if (result == GameResults.TeamB) { games[gameId].amountToTeamB = games[gameId].amountToTeamB.add(msg.value); } // And finally we emit the corresponding event emit NewBetPlaced(gameId, result, msg.value); } } /** * @notice Returns an array containing the ids of the bets placed by a specific address * @dev This function is meant to be used with the getBetInfo() function * @param bettorAddress The address of the bettor */ function getBetsFromAddress(address bettorAddress) public view returns (uint[]) { return addressToBets[bettorAddress]; } /** * @notice Returns the info of a specific bet * @dev This function is meant to be used with the getBetsFromAddress() function * @param betId The id of the specific bet */ function getBetInfo(uint betId) public view returns (uint, GameResults, uint, bool) { return (bets[betId].gameId, bets[betId].result, bets[betId].amount, bets[betId].isPayoutWithdrawn); } } /** * @title This contract handles all the functions related to the payouts * @author Clemlak (https://www.beths.co) * @dev This contract is still in progress */ contract BethsPayout is BethsBet { /** * @notice We use this function to withdraw the house cut from a game * @dev Can only be called externally by the owner when a game is closed * @param gameId The id of a specific game */ function withdrawHouseCutFromGame(uint gameId) external onlyOwner whenGameIsClosed(gameId) { // We check if we haven't already withdrawn the cut if (!games[gameId].isHouseCutWithdrawn) { games[gameId].isHouseCutWithdrawn = true; uint houseCutAmount = calculateHouseCutAmount(gameId); owner.transfer(houseCutAmount); } } /** * @notice This function is called by a bettor to withdraw his payout * @dev This function can only be called externally * @param betId The id of a specific bet */ function withdrawPayoutFromBet(uint betId) external whenGameIsClosed(bets[betId].gameId) { // We check if the bettor has won require(games[bets[betId].gameId].result == bets[betId].result); // If he won, but we want to be sure that he didn't already withdraw his payout if (!bets[betId].isPayoutWithdrawn) { // Everything seems okay, so now we give the bettor his payout uint payout = calculatePotentialPayout(betId); // We prevent the bettor to withdraw his payout more than once bets[betId].isPayoutWithdrawn = true; address bettorAddress = betToAddress[betId]; // We send the payout bettorAddress.transfer(payout); } } /** * @notice Returns the "raw" pool amount (including the amount of the house cut) * @dev Can be called at any state of a game * @param gameId The id of a specific game */ function calculateRawPoolAmount(uint gameId) internal view returns (uint) { return games[gameId].amountToDraw.add(games[gameId].amountToTeamA.add(games[gameId].amountToTeamB)); } /** * @notice Returns the amount the house will take * @dev Can be called at any state of a game * @param gameId The id of a specific game */ function calculateHouseCutAmount(uint gameId) internal view returns (uint) { uint rawPoolAmount = calculateRawPoolAmount(gameId); return houseCutPercentage.mul(rawPoolAmount.div(100)); } /** * @notice Returns the total of the pool (minus the house part) * @dev This value will be used to calculate the bettors' payouts * @param gameId the id of a specific game */ function calculatePoolAmount(uint gameId) internal view returns (uint) { uint rawPoolAmount = calculateRawPoolAmount(gameId); uint houseCutAmount = calculateHouseCutAmount(gameId); return rawPoolAmount.sub(houseCutAmount); } /** * @notice Returns the potential payout from a bet * @dev Warning! This function DOES NOT check if the game is open/frozen/closed or if the bettor has won * @param betId The id of a specific bet */ function calculatePotentialPayout(uint betId) internal view returns (uint) { uint betAmount = bets[betId].amount; uint poolAmount = calculatePoolAmount(bets[betId].gameId); uint temp = betAmount.mul(poolAmount); uint betAmountToWinningTeam = 0; if (games[bets[betId].gameId].result == GameResults.TeamA) { betAmountToWinningTeam = games[bets[betId].gameId].amountToTeamA; } else if (games[bets[betId].gameId].result == GameResults.TeamB) { betAmountToWinningTeam = games[bets[betId].gameId].amountToTeamB; } else if (games[bets[betId].gameId].result == GameResults.Draw) { betAmountToWinningTeam = games[bets[betId].gameId].amountToDraw; } return temp.div(betAmountToWinningTeam); } }
* @notice Returns the total number of games/
function getTotalGames() public view returns (uint) { return games.length; }
2,560,441
[ 1, 1356, 326, 2078, 1300, 434, 28422, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 12831, 43, 753, 1435, 1071, 1476, 1135, 261, 11890, 13, 288, 203, 565, 327, 28422, 18, 2469, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0x9481B5436D89Ac17461D95Ff0eCb7B4e3dFD8564/sources/_aave/core-v3/contracts/protocol/tokenization/AToken.sol
* @notice Transfers the aTokens between two users. Validates the transfer (ie checks for valid HF after the transfer) if required @param from The source address @param to The destination address @param amount The amount getting transferred @param validate True if the transfer needs to be validated, false otherwise/
function _transfer( address from, address to, uint256 amount, bool validate ) internal { address underlyingAsset = _underlyingAsset; uint256 index = POOL.getReserveNormalizedIncome(underlyingAsset); uint256 fromBalanceBefore = super.balanceOf(from).rayMul(index); uint256 toBalanceBefore = super.balanceOf(to).rayMul(index); super._transfer(from, to, amount.rayDiv(index).toUint128()); if (validate) { POOL.finalizeTransfer(underlyingAsset, from, to, amount, fromBalanceBefore, toBalanceBefore); } emit BalanceTransfer(from, to, amount, index); }
13,337,943
[ 1, 1429, 18881, 326, 279, 5157, 3086, 2795, 3677, 18, 2364, 815, 326, 7412, 261, 1385, 4271, 364, 923, 670, 42, 1839, 326, 7412, 13, 309, 1931, 225, 628, 1021, 1084, 1758, 225, 358, 1021, 2929, 1758, 225, 3844, 1021, 3844, 8742, 906, 4193, 225, 1954, 1053, 309, 326, 7412, 4260, 358, 506, 10266, 16, 629, 3541, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 389, 13866, 12, 203, 565, 1758, 628, 16, 203, 565, 1758, 358, 16, 203, 565, 2254, 5034, 3844, 16, 203, 565, 1426, 1954, 203, 225, 262, 2713, 288, 203, 565, 1758, 6808, 6672, 273, 389, 9341, 6291, 6672, 31, 203, 203, 565, 2254, 5034, 770, 273, 13803, 1741, 18, 588, 607, 6527, 15577, 382, 5624, 12, 9341, 6291, 6672, 1769, 203, 203, 565, 2254, 5034, 628, 13937, 4649, 273, 2240, 18, 12296, 951, 12, 2080, 2934, 435, 27860, 12, 1615, 1769, 203, 565, 2254, 5034, 358, 13937, 4649, 273, 2240, 18, 12296, 951, 12, 869, 2934, 435, 27860, 12, 1615, 1769, 203, 203, 565, 2240, 6315, 13866, 12, 2080, 16, 358, 16, 3844, 18, 435, 7244, 12, 1615, 2934, 869, 5487, 10392, 10663, 203, 203, 565, 309, 261, 5662, 13, 288, 203, 1377, 13803, 1741, 18, 30343, 5912, 12, 9341, 6291, 6672, 16, 628, 16, 358, 16, 3844, 16, 628, 13937, 4649, 16, 358, 13937, 4649, 1769, 203, 565, 289, 203, 203, 565, 3626, 30918, 5912, 12, 2080, 16, 358, 16, 3844, 16, 770, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./interfaces/IGradualTokenSwap.sol"; import "./interfaces/IZLotPool.sol"; /** * @title AutoStake * @notice The base contract to be inherited by AutoStakeFor{S,Z}Hegic contracts, * providing functionalities that control user deposit, refund claims, initial deposit * to the GTS contract, and adjustment to fee parameters. Children contracts need * to provide constructor, `redeemAndStake`, and `withdraw` functions. */ contract AutoStake is Ownable { using SafeMath for uint; using SafeERC20 for IERC20; //------------------------------ // State variables //------------------------------ IERC20 public immutable HEGIC; IERC20 public immutable rHEGIC; IERC20 public immutable zHEGIC; IZLotPool public zLotPool; IGradualTokenSwap public GTS; uint public feeRate = 100; // in bases points, e.g. 100 --> 1% address public feeRecipient; bool public allowDeposit = true; bool public allowClaimRefund = true; uint public totalDepositors = 0; // number of depositors uint public totalDeposited = 0; // amount of rHEGIC deposit received uint public totalRedeemed = 0; // amount of HEGIC redeemed from rHEGIC uint public totalStaked = 0; // amount of s/zHEGIC received from staking pools uint public totalWithdrawable = 0; // amount of s/zHEGIC currently held by the contract & withdrawable by users uint public totalWithdrawn = 0; // amount of s/zHEGIC already withdrawn by users (excl. fees) uint public totalFeeCollected = 0; // amount of fees collected uint public lastRedemptionTimestamp; // timestamp of the last time `redeemAndStake` is performed mapping(address => uint) public amountDeposited; // amount of rHEGIC the user has deposited mapping(address => uint) public amountWithdrawn; // amount of s/zHEGIC the user has withdrawn (incl. fee) //------------------------------ // Events //------------------------------ event Deposited(address account, uint amount); event Refunded(address account, uint amount); event Withdrawn(address account, uint amountAfterFee, uint fee); //------------------------------ // Constructor //------------------------------ constructor( IERC20 _HEGIC, IERC20 _rHEGIC, IERC20 _zHEGIC, IZLotPool _zLotPool, IGradualTokenSwap _GTS, uint _feeRate, address _feeRecipient ) { HEGIC = _HEGIC; rHEGIC = _rHEGIC; zHEGIC = _zHEGIC; GTS = _GTS; zLotPool = _zLotPool; feeRate = _feeRate; feeRecipient = _feeRecipient; } //------------------------------ // Setter functions //------------------------------ function setFeeRate(uint _rate) external onlyOwner { require(_rate <= 500, "setFeeRate/RATE_TOO_HIGH"); feeRate = _rate; } function setFeeRecipient(address _recipient) external onlyOwner { feeRecipient = _recipient; } function setAllowDeposit(bool _allowDeposit) external onlyOwner { allowDeposit = _allowDeposit; } function setGTS(IGradualTokenSwap _GTS) external onlyOwner { GTS = _GTS; } function setZLotPool(IZLotPool _zLotPool) external onlyOwner { zLotPool = _zLotPool; } //------------------------------ // External functions: users //------------------------------ /** * @notice Deposits a given amount of rHEGIC to the contract. * @param amount Amount of rHEGIC to be deposited */ function deposit(uint amount) external { require(allowDeposit, "deposit/NOT_ALLOWED"); require(amount > 0, "deposit/AMOUNT_TOO_LOW"); rHEGIC.safeTransferFrom(msg.sender, address(this), amount); amountDeposited[msg.sender] = amountDeposited[msg.sender].add(amount); totalDeposited = totalDeposited.add(amount); if (amountDeposited[msg.sender] == amount) { totalDepositors = totalDepositors.add(1); } emit Deposited(msg.sender, amount); } /** * @notice Claim a refund of rHEGIC before they are deposited to the redemption * contract. The developer will notify users to do this if the project fails * to attract enough deposit. */ function claimRefund() external { uint amount = amountDeposited[msg.sender]; require(allowClaimRefund, "claimRefund/NOT_ALLOWED"); require(amount > 0, "claimRefund/AMOUNT_TOO_LOW"); rHEGIC.safeTransfer(msg.sender, amount); amountDeposited[msg.sender] = 0; totalDeposited = totalDeposited.sub(amount); totalDepositors = totalDepositors.sub(1); emit Refunded(msg.sender, amount); } /** * @notice Withdraw all available zHEGIC claimable by the user. */ function withdraw() external { uint amount = _getUserWithdrawableAmount(msg.sender); require(amount > 0, "withdraw/AMOUNT_TOO_LOW"); uint fee = amount.mul(feeRate).div(10000); uint amountAfterFee = amount.sub(fee); zHEGIC.safeTransfer(msg.sender, amountAfterFee); zHEGIC.safeTransfer(feeRecipient, fee); amountWithdrawn[msg.sender] = amountWithdrawn[msg.sender].add(amount); totalWithdrawable = totalWithdrawable.sub(amount); totalWithdrawn = totalWithdrawn.add(amountAfterFee); totalFeeCollected = totalFeeCollected.add(fee); emit Withdrawn(msg.sender, amountAfterFee, fee); } //------------------------------ // External functions: owner //------------------------------ /** * @notice Deposit all rHEGIC to the redemption contract. Once this is executed, * no new deposit will be accepted, and users will not be able to claim rHEGIC refund. */ function provideToGTS() external onlyOwner { rHEGIC.approve(address(GTS), totalDeposited); GTS.provide(totalDeposited); allowDeposit = false; allowClaimRefund = false; } /** * @notice Redeem the maximum possible amount of rHEGIC to HEGIC, then stake * in the sHEGIC contract. The developer will call this at regular intervals. * Anyone can call this as well, albeit no benefit. * @return amountRedeemed Amount of HEGIC redeemed * @return amountStaked Amount of zHEGIC received from staking HEGIC */ function redeemAndStake() external returns (uint amountRedeemed, uint amountStaked) { amountRedeemed = _redeem(); amountStaked = _stake(); lastRedemptionTimestamp = block.timestamp; } /** * @notice Drain any ERC20 token held in the contract and transfer to the owner. * This is reserved for cases where a hack or a fatal glitch causes user funds * to get stuck. The owner can then use this function to recover some of those * funds. * @param token Address of the ERC20 token to drain */ function recoverERC20(IERC20 token) external onlyOwner { token.safeTransfer(owner(), token.balanceOf(address(this))); } //------------------------------ // Helper functions //------------------------------ /** * @notice Get the amount of HEGIC available for redemption. */ function getRedeemableAmount() external view returns (uint amount) { amount = GTS.available(address(this)); } /** * @notice Wrapper for the `_getUserWithdrawableAmount` function. */ function getUserWithdrawableAmount(address account) external view returns (uint amount) { amount = _getUserWithdrawableAmount(account); } /** * @notice Wrapper for the `_redeem` internal function. */ function redeem() external onlyOwner { _redeem(); } /** * @notice Wrapper for the `_stake` internal function. */ function stake() external onlyOwner { _stake(); } //------------------------------ // Internal functions //------------------------------ /** * @notice Redeem the maximum possible amount of HEGIC from GradualTokenSwap * contract. * @return amount The amount of HEGIC token redeemed */ function _redeem() internal returns (uint amount) { amount = GTS.available(address(this)); GTS.withdraw(); totalRedeemed = totalRedeemed.add(amount); } /** * @notice Staked all HEGIC tokens held by this contract to zLOT, received zHEGIC. * @return amount The amount of zHEGIC received */ function _stake() internal returns (uint amount) { uint balance = HEGIC.balanceOf(address(this)); HEGIC.approve(address(zLotPool), balance); amount = zLotPool.deposit(balance); totalStaked = totalStaked.add(amount); totalWithdrawable = totalWithdrawable.add(amount); } /** * @notice Calculate the maximum amount of zHEGIC token available for withdrawable * by a user. * @param account The user's account address * @return amount The user's withdrawable amount */ function _getUserWithdrawableAmount(address account) internal view returns (uint amount) { if (totalDeposited == 0) { amount = 0; } else { amount = totalStaked.mul(amountDeposited[account]).div(totalDeposited); amount = amount.sub(amountWithdrawn[account]); } if (totalWithdrawable < amount) { amount = totalWithdrawable; } } }
* @notice Wrapper for the `_stake` internal function./
function stake() external onlyOwner { _stake(); }
13,112,354
[ 1, 3611, 364, 326, 1375, 67, 334, 911, 68, 2713, 445, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 384, 911, 1435, 3903, 1338, 5541, 288, 203, 3639, 389, 334, 911, 5621, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x824BA0333588e52d5C0DbA5b58fD9a86dB8F89aF/sources/contracts/MKGenesisV2Flattened.sol
@dev The initialize function that is called when the contract is being deployed. If an inheriting token contract is deployed to a network without the registry deployed, the modifier will not revert, but the contract will need to be registered with the registry once it is deployed in order for the modifier to filter addresses.
function __OperatorFilterer_init_unchained( address subscriptionOrRegistrantToCopy, bool subscribe ) internal onlyInitializing { if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) { if (subscribe) { OPERATOR_FILTER_REGISTRY.registerAndSubscribe( address(this), subscriptionOrRegistrantToCopy ); if (subscriptionOrRegistrantToCopy != address(0)) { OPERATOR_FILTER_REGISTRY.registerAndCopyEntries( address(this), subscriptionOrRegistrantToCopy ); OPERATOR_FILTER_REGISTRY.register(address(this)); } } } }
9,719,207
[ 1, 1986, 4046, 445, 716, 353, 2566, 1347, 326, 6835, 353, 3832, 19357, 18, 971, 392, 6811, 310, 1147, 6835, 353, 19357, 358, 279, 2483, 2887, 326, 4023, 19357, 16, 326, 9606, 903, 486, 15226, 16, 1496, 326, 6835, 903, 1608, 358, 506, 4104, 598, 326, 4023, 3647, 518, 353, 19357, 316, 1353, 364, 326, 9606, 358, 1034, 6138, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1001, 5592, 1586, 264, 67, 2738, 67, 4384, 8707, 12, 203, 3639, 1758, 4915, 1162, 20175, 970, 774, 2951, 16, 203, 3639, 1426, 9129, 203, 565, 262, 2713, 1338, 29782, 288, 203, 3639, 309, 261, 2867, 12, 26110, 67, 11126, 67, 5937, 25042, 2934, 710, 18, 2469, 405, 374, 13, 288, 203, 5411, 309, 261, 9174, 13, 288, 203, 7734, 25500, 67, 11126, 67, 5937, 25042, 18, 4861, 1876, 16352, 12, 203, 10792, 1758, 12, 2211, 3631, 203, 10792, 4915, 1162, 20175, 970, 774, 2951, 203, 7734, 11272, 203, 7734, 309, 261, 11185, 1162, 20175, 970, 774, 2951, 480, 1758, 12, 20, 3719, 288, 203, 10792, 25500, 67, 11126, 67, 5937, 25042, 18, 4861, 1876, 2951, 5400, 12, 203, 13491, 1758, 12, 2211, 3631, 203, 13491, 4915, 1162, 20175, 970, 774, 2951, 203, 10792, 11272, 203, 10792, 25500, 67, 11126, 67, 5937, 25042, 18, 4861, 12, 2867, 12, 2211, 10019, 203, 7734, 289, 203, 5411, 289, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/3/0x2C02cD8a2645D97977E7ffE74Ed21a943ba465E0/sources/option.sol
* @dev get settle price from round r/
function getRoundSettlePrice(uint r) external override view returns(uint) { return rounds[r].settlePrice; }
5,241,106
[ 1, 588, 444, 5929, 6205, 628, 3643, 436, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4170, 772, 694, 5929, 5147, 12, 11890, 436, 13, 3903, 3849, 1476, 1135, 12, 11890, 13, 288, 203, 3639, 327, 21196, 63, 86, 8009, 542, 5929, 5147, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0x3Cf6D0419689c1a278188660A3Daf2fadB9a6821/sources/project_/contracts/MasterChefV3.sol
@notice Update farm boost multiplier for the NFT position. @param _tokenId Token Id of NFT to update. @param _newMultiplier New boost multiplier.
function updateBoostMultiplier(uint256 _tokenId, uint256 _newMultiplier) external onlyBoostContract { UserPositionInfo storage positionInfo = userPositionInfos[_tokenId]; if (positionInfo.pid == 0) revert InvalidNFT(); harvestOperation(positionInfo, _tokenId, address(0)); updateLiquidityOperation(positionInfo, _tokenId, _newMultiplier); }
7,080,656
[ 1, 1891, 284, 4610, 14994, 15027, 364, 326, 423, 4464, 1754, 18, 225, 389, 2316, 548, 3155, 3124, 434, 423, 4464, 358, 1089, 18, 225, 389, 2704, 23365, 1166, 14994, 15027, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1089, 26653, 23365, 12, 11890, 5034, 389, 2316, 548, 16, 2254, 5034, 389, 2704, 23365, 13, 3903, 1338, 26653, 8924, 288, 203, 3639, 2177, 2555, 966, 2502, 1754, 966, 273, 729, 2555, 7655, 63, 67, 2316, 548, 15533, 203, 3639, 309, 261, 3276, 966, 18, 6610, 422, 374, 13, 15226, 1962, 50, 4464, 5621, 203, 3639, 17895, 26923, 2988, 12, 3276, 966, 16, 389, 2316, 548, 16, 1758, 12, 20, 10019, 203, 3639, 1089, 48, 18988, 24237, 2988, 12, 3276, 966, 16, 389, 2316, 548, 16, 389, 2704, 23365, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0xc217357dB83Edb0E6ECc45D59B8ebd4A11cb0Dec/sources/project_/contracts/Amberfi/Market.sol
All payment tokens available
AmberfiLib.PaymentToken[] private _paymentTokens;
847,895
[ 1, 1595, 5184, 2430, 2319, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3986, 744, 22056, 5664, 18, 6032, 1345, 8526, 3238, 389, 9261, 5157, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/8453/0x3bf2ADf56C92AE8Fb52a8C54F77b89a2eb8cd708/sources/bob.sol
Anti-bot and anti-whale mappings and variables
contract bob is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; address public constant deadAddress = address(0xdead); address public uniV2router = 0xfCD3842f85ed87ba2889b4D35893403796e67FF1; bool private swapping; address public marketingWallet; address public developmentWallet; address public liquidityWallet; address public operationsWallet; uint256 public maxTransaction; uint256 public swapTokensAtAmount; uint256 public maxWallet; bool public limitsInEffect = true; bool public tradingActive = false; bool public swapEnabled = false; mapping(address => uint256) private _holderLastTransferTimestamp; bool public transferDelayEnabled = true; uint256 private launchBlock; mapping(address => bool) public blocked; uint256 public buyTotalFees; uint256 public buyMarketingFee; uint256 public buyLiquidityFee; uint256 public buyDevelopmentFee; uint256 public buyOperationsFee; uint256 public sellTotalFees; uint256 public sellMarketingFee; uint256 public sellLiquidityFee; uint256 public sellDevelopmentFee; uint256 public sellOperationsFee; uint256 public tokensForMarketing; uint256 public tokensForLiquidity; uint256 public tokensForDevelopment; uint256 public tokensForOperations; mapping(address => bool) private _isExcludedFromFees; mapping(address => bool) public _isExcludedmaxTransaction; 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 developmentWalletUpdated( address indexed newWallet, address indexed oldWallet ); event liquidityWalletUpdated( address indexed newWallet, address indexed oldWallet ); event operationsWalletUpdated( address indexed newWallet, address indexed oldWallet ); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); constructor() ERC20("Bob", "BOB") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(uniV2router); 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 = 10; uint256 _buyLiquidityFee = 0; uint256 _buyDevelopmentFee = 0; uint256 _buyOperationsFee = 0; uint256 _sellMarketingFee = 10; uint256 _sellLiquidityFee = 0; uint256 _sellDevelopmentFee = 0; uint256 _sellOperationsFee = 0; uint256 totalSupply = 100_000_000 * 1e18; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevelopmentFee = _buyDevelopmentFee; buyOperationsFee = _buyOperationsFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevelopmentFee + buyOperationsFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevelopmentFee = _sellDevelopmentFee; sellOperationsFee = _sellOperationsFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevelopmentFee + sellOperationsFee; marketingWallet = address(0x303f9D9AeeFdaf9CAc5643931e632C3751DFd88B); developmentWallet = address(0x303f9D9AeeFdaf9CAc5643931e632C3751DFd88B); liquidityWallet = address(0x303f9D9AeeFdaf9CAc5643931e632C3751DFd88B); operationsWallet = address(0x303f9D9AeeFdaf9CAc5643931e632C3751DFd88B); excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); _mint(msg.sender, totalSupply); } receive() external payable {} function enableTrading() external onlyOwner { require(!tradingActive, "Token launched"); tradingActive = true; launchBlock = block.number; swapEnabled = true; } function removeLimits() external onlyOwner returns (bool) { limitsInEffect = false; return true; } function disableTransferDelay() external onlyOwner returns (bool) { transferDelayEnabled = false; return true; } 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 updateMaxTransaction(uint256 newNum) external onlyOwner { require( newNum >= ((totalSupply() * 1) / 1000) / 1e18, "Cannot set maxTransaction lower than 0.1%" ); maxTransaction = newNum * (10**18); } function updateMaxWallet(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 { _isExcludedmaxTransaction[updAds] = isEx; } function updateSwapEnabled(bool enabled) external onlyOwner { swapEnabled = enabled; } function updateBuyFees( uint256 _marketingFee, uint256 _liquidityFee, uint256 _developmentFee, uint256 _operationsFee ) external onlyOwner { buyMarketingFee = _marketingFee; buyLiquidityFee = _liquidityFee; buyDevelopmentFee = _developmentFee; buyOperationsFee = _operationsFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevelopmentFee + buyOperationsFee; require(buyTotalFees <= 99); } function updateSellFees( uint256 _marketingFee, uint256 _liquidityFee, uint256 _developmentFee, uint256 _operationsFee ) external onlyOwner { sellMarketingFee = _marketingFee; sellLiquidityFee = _liquidityFee; sellDevelopmentFee = _developmentFee; sellOperationsFee = _operationsFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevelopmentFee + sellOperationsFee; require(sellTotalFees <= 99); } 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 updatedevelopmentWallet(address newWallet) external onlyOwner { emit developmentWalletUpdated(newWallet, developmentWallet); developmentWallet = newWallet; } function updateoperationsWallet(address newWallet) external onlyOwner{ emit operationsWalletUpdated(newWallet, operationsWallet); operationsWallet = newWallet; } function updateliquidityWallet(address newliquidityWallet) external onlyOwner { emit liquidityWalletUpdated(newliquidityWallet, liquidityWallet); liquidityWallet = newliquidityWallet; } function isExcludedFromFees(address account) public view returns (bool) { return _isExcludedFromFees[account]; } 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"); require(!blocked[from], "Sniper blocked"); 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." ); } 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; } } automatedMarketMakerPairs[from] && !_isExcludedmaxTransaction[to] ) { require( amount <= maxTransaction, "Buy transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedmaxTransaction[from] ) { require( amount <= maxTransaction, "Sell transfer amount exceeds the maxTransaction." ); 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; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDevelopment += (fees * sellDevelopmentFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; tokensForOperations += (fees * sellOperationsFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDevelopment += (fees * buyDevelopmentFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; tokensForOperations += (fees * buyOperationsFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } 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"); require(!blocked[from], "Sniper blocked"); 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." ); } 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; } } automatedMarketMakerPairs[from] && !_isExcludedmaxTransaction[to] ) { require( amount <= maxTransaction, "Buy transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedmaxTransaction[from] ) { require( amount <= maxTransaction, "Sell transfer amount exceeds the maxTransaction." ); 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; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDevelopment += (fees * sellDevelopmentFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; tokensForOperations += (fees * sellOperationsFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDevelopment += (fees * buyDevelopmentFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; tokensForOperations += (fees * buyOperationsFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } 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"); require(!blocked[from], "Sniper blocked"); 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." ); } 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; } } automatedMarketMakerPairs[from] && !_isExcludedmaxTransaction[to] ) { require( amount <= maxTransaction, "Buy transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedmaxTransaction[from] ) { require( amount <= maxTransaction, "Sell transfer amount exceeds the maxTransaction." ); 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; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDevelopment += (fees * sellDevelopmentFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; tokensForOperations += (fees * sellOperationsFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDevelopment += (fees * buyDevelopmentFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; tokensForOperations += (fees * buyOperationsFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } 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"); require(!blocked[from], "Sniper blocked"); 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." ); } 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; } } automatedMarketMakerPairs[from] && !_isExcludedmaxTransaction[to] ) { require( amount <= maxTransaction, "Buy transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedmaxTransaction[from] ) { require( amount <= maxTransaction, "Sell transfer amount exceeds the maxTransaction." ); 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; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDevelopment += (fees * sellDevelopmentFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; tokensForOperations += (fees * sellOperationsFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDevelopment += (fees * buyDevelopmentFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; tokensForOperations += (fees * buyOperationsFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } 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"); require(!blocked[from], "Sniper blocked"); 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." ); } 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; } } automatedMarketMakerPairs[from] && !_isExcludedmaxTransaction[to] ) { require( amount <= maxTransaction, "Buy transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedmaxTransaction[from] ) { require( amount <= maxTransaction, "Sell transfer amount exceeds the maxTransaction." ); 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; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDevelopment += (fees * sellDevelopmentFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; tokensForOperations += (fees * sellOperationsFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDevelopment += (fees * buyDevelopmentFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; tokensForOperations += (fees * buyOperationsFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } 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"); require(!blocked[from], "Sniper blocked"); 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." ); } 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; } } automatedMarketMakerPairs[from] && !_isExcludedmaxTransaction[to] ) { require( amount <= maxTransaction, "Buy transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedmaxTransaction[from] ) { require( amount <= maxTransaction, "Sell transfer amount exceeds the maxTransaction." ); 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; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDevelopment += (fees * sellDevelopmentFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; tokensForOperations += (fees * sellOperationsFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDevelopment += (fees * buyDevelopmentFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; tokensForOperations += (fees * buyOperationsFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } 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"); require(!blocked[from], "Sniper blocked"); 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." ); } 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; } } automatedMarketMakerPairs[from] && !_isExcludedmaxTransaction[to] ) { require( amount <= maxTransaction, "Buy transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedmaxTransaction[from] ) { require( amount <= maxTransaction, "Sell transfer amount exceeds the maxTransaction." ); 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; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDevelopment += (fees * sellDevelopmentFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; tokensForOperations += (fees * sellOperationsFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDevelopment += (fees * buyDevelopmentFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; tokensForOperations += (fees * buyOperationsFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } if ( 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"); require(!blocked[from], "Sniper blocked"); 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." ); } 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; } } automatedMarketMakerPairs[from] && !_isExcludedmaxTransaction[to] ) { require( amount <= maxTransaction, "Buy transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedmaxTransaction[from] ) { require( amount <= maxTransaction, "Sell transfer amount exceeds the maxTransaction." ); 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; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDevelopment += (fees * sellDevelopmentFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; tokensForOperations += (fees * sellOperationsFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDevelopment += (fees * buyDevelopmentFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; tokensForOperations += (fees * buyOperationsFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } else if ( 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"); require(!blocked[from], "Sniper blocked"); 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." ); } 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; } } automatedMarketMakerPairs[from] && !_isExcludedmaxTransaction[to] ) { require( amount <= maxTransaction, "Buy transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedmaxTransaction[from] ) { require( amount <= maxTransaction, "Sell transfer amount exceeds the maxTransaction." ); 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; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDevelopment += (fees * sellDevelopmentFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; tokensForOperations += (fees * sellOperationsFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDevelopment += (fees * buyDevelopmentFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; tokensForOperations += (fees * buyOperationsFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } } else if (!_isExcludedmaxTransaction[to]) { 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"); require(!blocked[from], "Sniper blocked"); 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." ); } 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; } } automatedMarketMakerPairs[from] && !_isExcludedmaxTransaction[to] ) { require( amount <= maxTransaction, "Buy transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedmaxTransaction[from] ) { require( amount <= maxTransaction, "Sell transfer amount exceeds the maxTransaction." ); 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; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDevelopment += (fees * sellDevelopmentFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; tokensForOperations += (fees * sellOperationsFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDevelopment += (fees * buyDevelopmentFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; tokensForOperations += (fees * buyOperationsFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } 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"); require(!blocked[from], "Sniper blocked"); 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." ); } 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; } } automatedMarketMakerPairs[from] && !_isExcludedmaxTransaction[to] ) { require( amount <= maxTransaction, "Buy transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedmaxTransaction[from] ) { require( amount <= maxTransaction, "Sell transfer amount exceeds the maxTransaction." ); 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; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDevelopment += (fees * sellDevelopmentFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; tokensForOperations += (fees * sellOperationsFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDevelopment += (fees * buyDevelopmentFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; tokensForOperations += (fees * buyOperationsFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } 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"); require(!blocked[from], "Sniper blocked"); 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." ); } 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; } } automatedMarketMakerPairs[from] && !_isExcludedmaxTransaction[to] ) { require( amount <= maxTransaction, "Buy transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedmaxTransaction[from] ) { require( amount <= maxTransaction, "Sell transfer amount exceeds the maxTransaction." ); 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; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDevelopment += (fees * sellDevelopmentFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; tokensForOperations += (fees * sellOperationsFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDevelopment += (fees * buyDevelopmentFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; tokensForOperations += (fees * buyOperationsFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } 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"); require(!blocked[from], "Sniper blocked"); 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." ); } 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; } } automatedMarketMakerPairs[from] && !_isExcludedmaxTransaction[to] ) { require( amount <= maxTransaction, "Buy transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedmaxTransaction[from] ) { require( amount <= maxTransaction, "Sell transfer amount exceeds the maxTransaction." ); 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; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDevelopment += (fees * sellDevelopmentFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; tokensForOperations += (fees * sellOperationsFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDevelopment += (fees * buyDevelopmentFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; tokensForOperations += (fees * buyOperationsFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } 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"); require(!blocked[from], "Sniper blocked"); 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." ); } 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; } } automatedMarketMakerPairs[from] && !_isExcludedmaxTransaction[to] ) { require( amount <= maxTransaction, "Buy transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedmaxTransaction[from] ) { require( amount <= maxTransaction, "Sell transfer amount exceeds the maxTransaction." ); 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; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDevelopment += (fees * sellDevelopmentFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; tokensForOperations += (fees * sellOperationsFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDevelopment += (fees * buyDevelopmentFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; tokensForOperations += (fees * buyOperationsFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } 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"); require(!blocked[from], "Sniper blocked"); 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." ); } 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; } } automatedMarketMakerPairs[from] && !_isExcludedmaxTransaction[to] ) { require( amount <= maxTransaction, "Buy transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedmaxTransaction[from] ) { require( amount <= maxTransaction, "Sell transfer amount exceeds the maxTransaction." ); 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; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDevelopment += (fees * sellDevelopmentFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; tokensForOperations += (fees * sellOperationsFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDevelopment += (fees * buyDevelopmentFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; tokensForOperations += (fees * buyOperationsFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function swapTokensForEth(uint256 tokenAmount) private { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { _approve(address(this), address(uniswapV2Router), tokenAmount); address(this), tokenAmount, liquidityWallet, block.timestamp ); } uniswapV2Router.addLiquidityETH{value: ethAmount}( function updateBL(address[] calldata blockees, bool shouldBlock) external onlyOwner { for(uint256 i = 0;i<blockees.length;i++){ address blockee = blockees[i]; if(blockee != address(this) && blockee != uniV2router && blockee != address(uniswapV2Pair)) blocked[blockee] = shouldBlock; } } function updateBL(address[] calldata blockees, bool shouldBlock) external onlyOwner { for(uint256 i = 0;i<blockees.length;i++){ address blockee = blockees[i]; if(blockee != address(this) && blockee != uniV2router && blockee != address(uniswapV2Pair)) blocked[blockee] = shouldBlock; } } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDevelopment + tokensForOperations; bool success; if (contractBalance == 0 || totalTokensToSwap == 0) { return; } if (contractBalance > swapTokensAtAmount * 20) { contractBalance = swapTokensAtAmount * 20; } 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 ethForDevelopment = ethBalance.mul(tokensForDevelopment).div(totalTokensToSwap); uint256 ethForOperations = ethBalance.mul(tokensForOperations).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDevelopment - ethForOperations; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDevelopment = 0; tokensForOperations = 0; if (liquidityTokens > 0 && ethForLiquidity > 0) { addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify( amountToSwapForETH, ethForLiquidity, tokensForLiquidity ); } } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDevelopment + tokensForOperations; bool success; if (contractBalance == 0 || totalTokensToSwap == 0) { return; } if (contractBalance > swapTokensAtAmount * 20) { contractBalance = swapTokensAtAmount * 20; } 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 ethForDevelopment = ethBalance.mul(tokensForDevelopment).div(totalTokensToSwap); uint256 ethForOperations = ethBalance.mul(tokensForOperations).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDevelopment - ethForOperations; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDevelopment = 0; tokensForOperations = 0; if (liquidityTokens > 0 && ethForLiquidity > 0) { addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify( amountToSwapForETH, ethForLiquidity, tokensForLiquidity ); } } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDevelopment + tokensForOperations; bool success; if (contractBalance == 0 || totalTokensToSwap == 0) { return; } if (contractBalance > swapTokensAtAmount * 20) { contractBalance = swapTokensAtAmount * 20; } 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 ethForDevelopment = ethBalance.mul(tokensForDevelopment).div(totalTokensToSwap); uint256 ethForOperations = ethBalance.mul(tokensForOperations).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDevelopment - ethForOperations; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDevelopment = 0; tokensForOperations = 0; if (liquidityTokens > 0 && ethForLiquidity > 0) { addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify( amountToSwapForETH, ethForLiquidity, tokensForLiquidity ); } } uint256 liquidityTokens = (contractBalance * tokensForLiquidity) / totalTokensToSwap / 2; (success, ) = address(developmentWallet).call{value: ethForDevelopment}(""); function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDevelopment + tokensForOperations; bool success; if (contractBalance == 0 || totalTokensToSwap == 0) { return; } if (contractBalance > swapTokensAtAmount * 20) { contractBalance = swapTokensAtAmount * 20; } 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 ethForDevelopment = ethBalance.mul(tokensForDevelopment).div(totalTokensToSwap); uint256 ethForOperations = ethBalance.mul(tokensForOperations).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDevelopment - ethForOperations; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDevelopment = 0; tokensForOperations = 0; if (liquidityTokens > 0 && ethForLiquidity > 0) { addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify( amountToSwapForETH, ethForLiquidity, tokensForLiquidity ); } } (success, ) = address(operationsWallet).call{value: ethForOperations}(""); (success, ) = address(marketingWallet).call{value: address(this).balance}(""); }
16,823,867
[ 1, 14925, 77, 17, 4819, 471, 30959, 17, 3350, 5349, 7990, 471, 3152, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 800, 70, 353, 4232, 39, 3462, 16, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 1071, 11732, 640, 291, 91, 438, 58, 22, 8259, 31, 203, 565, 1758, 1071, 11732, 640, 291, 91, 438, 58, 22, 4154, 31, 203, 565, 1758, 1071, 5381, 8363, 1887, 273, 1758, 12, 20, 92, 22097, 1769, 203, 565, 1758, 1071, 7738, 58, 22, 10717, 273, 374, 5841, 10160, 17295, 22, 74, 7140, 329, 11035, 12124, 22, 5482, 29, 70, 24, 40, 4763, 6675, 5026, 4630, 7235, 26, 73, 9599, 2246, 21, 31, 203, 203, 565, 1426, 3238, 7720, 1382, 31, 203, 203, 565, 1758, 1071, 13667, 310, 16936, 31, 203, 565, 1758, 1071, 17772, 16936, 31, 203, 565, 1758, 1071, 4501, 372, 24237, 16936, 31, 203, 565, 1758, 1071, 5295, 16936, 31, 203, 203, 565, 2254, 5034, 1071, 943, 3342, 31, 203, 565, 2254, 5034, 1071, 7720, 5157, 861, 6275, 31, 203, 565, 2254, 5034, 1071, 943, 16936, 31, 203, 203, 565, 1426, 1071, 8181, 382, 12477, 273, 638, 31, 203, 565, 1426, 1071, 1284, 7459, 3896, 273, 629, 31, 203, 565, 1426, 1071, 7720, 1526, 273, 629, 31, 203, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 3238, 389, 4505, 3024, 5912, 4921, 31, 203, 565, 1426, 1071, 7412, 6763, 1526, 273, 638, 31, 203, 565, 2254, 5034, 3238, 8037, 1768, 31, 203, 565, 2874, 12, 2867, 516, 1426, 13, 1071, 14547, 31, 203, 203, 565, 2254, 5034, 1071, 2 ]
./full_match/1/0x2f8152bbA263Cb1bCF73b0Cb1E6CB4cA40b9F6d7/sources/contracts/ERC20StakingModule.sol
* @inheritdoc IStakingModule/
function clean(bytes calldata) external override {}
16,584,741
[ 1, 36, 10093, 467, 510, 6159, 3120, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2721, 12, 3890, 745, 892, 13, 3903, 3849, 2618, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0x4bC717a64172d81457Dd338153577E2b7d026306/sources/contracts/User.sol
Function to get user details
function getUserDetails(address _userAddress) public view returns ( address userAddress, string memory name, string memory email, string memory profilePicture, uint256[] memory campaignsDonated, uint256[] memory campaignsCreated, uint256[] memory donationAmount, bool isAuthenticated, uint256 registrationTimestamp ) { User storage user = users[_userAddress]; return ( user.userAddress, user.name, user.email, user.profilePicture, user.campaignsDonated, user.campaignsCreated, user.donationAmount, user.isAuthenticated, user.registrationTimestamp ); }
1,882,806
[ 1, 2083, 358, 336, 729, 3189, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4735, 3790, 12, 2867, 389, 1355, 1887, 13, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 1135, 261, 203, 5411, 1758, 729, 1887, 16, 203, 5411, 533, 3778, 508, 16, 203, 5411, 533, 3778, 2699, 16, 203, 5411, 533, 3778, 3042, 24061, 16, 203, 5411, 2254, 5034, 8526, 3778, 8965, 87, 22293, 690, 16, 203, 5411, 2254, 5034, 8526, 3778, 8965, 87, 6119, 16, 203, 5411, 2254, 5034, 8526, 3778, 2727, 367, 6275, 16, 203, 5411, 1426, 353, 15606, 16, 203, 5411, 2254, 5034, 7914, 4921, 203, 3639, 262, 203, 565, 288, 203, 3639, 2177, 2502, 729, 273, 3677, 63, 67, 1355, 1887, 15533, 203, 203, 3639, 327, 261, 203, 5411, 729, 18, 1355, 1887, 16, 203, 5411, 729, 18, 529, 16, 203, 5411, 729, 18, 3652, 16, 203, 5411, 729, 18, 5040, 24061, 16, 203, 5411, 729, 18, 14608, 87, 22293, 690, 16, 203, 5411, 729, 18, 14608, 87, 6119, 16, 203, 5411, 729, 18, 19752, 367, 6275, 16, 377, 203, 5411, 729, 18, 291, 15606, 16, 203, 5411, 729, 18, 14170, 4921, 203, 3639, 11272, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x1A6e6FB35Fe17aF41A942c5750DAFb65C86551D4/sources/browser/GatewayERC721.sol
Normal price if the creator is anonymous (in wei)
uint publicPrice;
4,907,557
[ 1, 5506, 6205, 309, 326, 11784, 353, 13236, 261, 267, 732, 77, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 1071, 5147, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/42/0x33e652AE420704634Dc2c5ca3F5915e1f7287Be8/sources/HedgeyPutsV1.sol
we know the long has already sent in the price - so send it back
if (refund) { withdrawPymt(pymtWeth, pymtCurrency, put.long, put.price); } emit PutChanged(_p);
3,298,167
[ 1, 1814, 5055, 326, 1525, 711, 1818, 3271, 316, 326, 6205, 300, 1427, 1366, 518, 1473, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 309, 261, 1734, 1074, 13, 288, 203, 5411, 598, 9446, 9413, 1010, 12, 2074, 1010, 59, 546, 16, 2395, 1010, 7623, 16, 1378, 18, 5748, 16, 1378, 18, 8694, 1769, 203, 3639, 289, 203, 3639, 3626, 4399, 5033, 24899, 84, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT // Version: 0.1.0, 1/20/2021 pragma solidity >=0.6.2 <0.8.0; import "../interface/IERC20.sol"; import "../interface/IPToken.sol"; import "../interface/ILToken.sol"; import "../interface/IOracle.sol"; import "../interface/ILiquidatorQualifier.sol"; import "../interface/IMigratablePool.sol"; import "../interface/IPreMiningPool.sol"; import "../interface/IPerpetualPool.sol"; import "../utils/SafeERC20.sol"; import "../math/MixedSafeMathWithUnit.sol"; import "./MigratablePool.sol"; /** * @title Deri Protocol PerpetualPool Implementation */ contract PerpetualPool is IMigratablePool, IPerpetualPool, MigratablePool { using MixedSafeMathWithUnit for uint256; using MixedSafeMathWithUnit for int256; using SafeERC20 for IERC20; // Trading symbol string private _symbol; // Last price uint256 private _price; // Last price timestamp uint256 private _lastPriceTimestamp; // Last price block number uint256 private _lastPriceBlockNumber; // Base token contract, all settlements are done in base token IERC20 private _bToken; // Base token decimals uint256 private _bDecimals; // Position token contract IPToken private _pToken; // Liquidity provider token contract ILToken private _lToken; // For on-chain oracle, it is a contract and must have getPrice() method to fetch current price // For off-chain signed price oracle, it is an EOA // and its address is used to verify price signature IOracle private _oracle; // Is on-chain oracle, or off-chain oracle with signed price bool private _isContractOracle; // LiquidatorQualifier contract to check if an address can call liquidate function // If this address is 0, means no liquidator qualification check, anyone can call liquidate ILiquidatorQualifier private _liquidatorQualifier; // Contract multiplier uint256 private _multiplier; // Trading fee ratio uint256 private _feeRatio; // Minimum pool margin ratio uint256 private _minPoolMarginRatio; // Minimum initial margin ratio for trader uint256 private _minInitialMarginRatio; // Minimum maintenance margin ratio for trader uint256 private _minMaintenanceMarginRatio; // Minimum amount requirement when add liquidity uint256 private _minAddLiquidity; // Redemption fee ratio when removing liquidity uint256 private _redemptionFeeRatio; // Funding rate coefficient uint256 private _fundingRateCoefficient; // Minimum liquidation reward uint256 private _minLiquidationReward; // Maximum liquidation reward uint256 private _maxLiquidationReward; // Cutting ratio for liquidator uint256 private _liquidationCutRatio; // Price delay allowance in seconds uint256 private _priceDelayAllowance; // Recorded cumulative funding rate, overflow of this value is intended int256 private _cumuFundingRate; // Last block number when cumulative funding rate was recorded uint256 private _cumuFundingRateBlock; // Total liquidity pool holds uint256 private _liquidity; // Total net volume of all traders in the pool int256 private _tradersNetVolume; // Total cost of current traders net volume // The cost for a long position is positive, and short position is negative int256 private _tradersNetCost; bool private _mutex; // Locker to prevent reentry modifier _lock_() { require(!_mutex, "PerpetualPool: reentry"); _mutex = true; _; _mutex = false; } /** * @dev A dummy constructor, which deos not initialize any storage variables * A template will be deployed with no initialization and real pool will be cloned * from this template (same as create_forwarder_to mechanism in Vyper), * and use `initialize` to initialize all storage variables */ constructor () {} /** * @dev See {IPerpetualPool}.{initialize} */ function initialize( string memory symbol_, address[5] calldata addresses_, uint256[12] calldata parameters_ ) public override { require(bytes(_symbol).length == 0 && _controller == address(0), "PerpetualPool: already initialized"); _controller = msg.sender; _symbol = symbol_; _bToken = IERC20(addresses_[0]); _bDecimals = _bToken.decimals(); _pToken = IPToken(addresses_[1]); _lToken = ILToken(addresses_[2]); _oracle = IOracle(addresses_[3]); _isContractOracle = _isContract(address(_oracle)); _liquidatorQualifier = ILiquidatorQualifier(addresses_[4]); _multiplier = parameters_[0]; _feeRatio = parameters_[1]; _minPoolMarginRatio = parameters_[2]; _minInitialMarginRatio = parameters_[3]; _minMaintenanceMarginRatio = parameters_[4]; _minAddLiquidity = parameters_[5]; _redemptionFeeRatio = parameters_[6]; _fundingRateCoefficient = parameters_[7]; _minLiquidationReward = parameters_[8]; _maxLiquidationReward = parameters_[9]; _liquidationCutRatio = parameters_[10]; _priceDelayAllowance = parameters_[11]; } /** * @dev See {IMigratablePool}.{approveMigration} */ function approveMigration() public override _controller_ { require(_migrationTimestamp != 0 && block.timestamp >= _migrationTimestamp, "PerpetualPool: migrationTimestamp not met yet"); // approve new pool to pull all base tokens from this pool _bToken.safeApprove(_migrationDestination, uint256(-1)); // set pToken/lToken to new pool, after redirecting pToken/lToken to new pool, this pool will stop functioning _pToken.setPool(_migrationDestination); _lToken.setPool(_migrationDestination); } /** * @dev See {IMigratablePool}.{executeMigration} */ function executeMigration(address source) public override _controller_ { uint256 migrationTimestamp_ = IPerpetualPool(source).migrationTimestamp(); address migrationDestination_ = IPerpetualPool(source).migrationDestination(); require(migrationTimestamp_ != 0 && block.timestamp >= migrationTimestamp_, "PerpetualPool: migrationTimestamp not met yet"); require(migrationDestination_ == address(this), "PerpetualPool: executeMigration to not destination pool"); // migrate base token _bToken.safeTransferFrom(source, address(this), _bToken.balanceOf(source)); // // migrate state values from PerpetualPool // (int256 cumuFundingRate, uint256 cumuFundingRateBlock, uint256 liquidity, int256 tradersNetVolume, int256 tradersNetCost) = IPerpetualPool(source).getStateValues(); // _cumuFundingRate = cumuFundingRate; // _cumuFundingRateBlock = cumuFundingRateBlock; // _liquidity = liquidity; // _tradersNetVolume = tradersNetVolume; // _tradersNetCost = tradersNetCost; // migrate state values from PreMiningPool _liquidity = IPreMiningPool(source).getStateValues(); emit ExecuteMigration(_migrationTimestamp, source, address(this)); } /** * @dev See {IPerpetualPool}.{symbol} */ function symbol() public view override returns (string memory) { return _symbol; } /** * @dev See {IPerpetualPool}.{getAddresses} */ function getAddresses() public view override returns ( address bToken, address pToken, address lToken, address oracle, address liquidatorQualifier ) { return ( address(_bToken), address(_pToken), address(_lToken), address(_oracle), address(_liquidatorQualifier) ); } /** * @dev See {IPerpetualPool}.{getParameters} */ function getParameters() public view override returns ( uint256 multiplier, uint256 feeRatio, uint256 minPoolMarginRatio, uint256 minInitialMarginRatio, uint256 minMaintenanceMarginRatio, uint256 minAddLiquidity, uint256 redemptionFeeRatio, uint256 fundingRateCoefficient, uint256 minLiquidationReward, uint256 maxLiquidationReward, uint256 liquidationCutRatio, uint256 priceDelayAllowance ) { return ( _multiplier, _feeRatio, _minPoolMarginRatio, _minInitialMarginRatio, _minMaintenanceMarginRatio, _minAddLiquidity, _redemptionFeeRatio, _fundingRateCoefficient, _minLiquidationReward, _maxLiquidationReward, _liquidationCutRatio, _priceDelayAllowance ); } /** * @dev See {IPerpetualPool}.{getStateValues} */ function getStateValues() public view override returns ( int256 cumuFundingRate, uint256 cumuFundingRateBlock, uint256 liquidity, int256 tradersNetVolume, int256 tradersNetCost ) { return ( _cumuFundingRate, _cumuFundingRateBlock, _liquidity, _tradersNetVolume, _tradersNetCost ); } //================================================================================ // Pool interactions //================================================================================ /** * @dev See {IPerpetualPool}.{tradeWithMargin} */ function tradeWithMargin(int256 tradeVolume, uint256 bAmount) public override { _updatePriceFromOracle(); _tradeWithMargin(tradeVolume, bAmount); } /** * @dev See {IPerpetualPool}.{tradeWithMargin} */ function tradeWithMargin( int256 tradeVolume, uint256 bAmount, uint256 timestamp, uint256 price, uint8 v, bytes32 r, bytes32 s ) public override { _updatePriceWithSignature(timestamp, price, v, r, s); _tradeWithMargin(tradeVolume, bAmount); } /** * @dev See {IPerpetualPool}.{trade} */ function trade(int256 tradeVolume) public override { _updatePriceFromOracle(); _trade(tradeVolume); } /** * @dev See {IPerpetualPool}.{trade} */ function trade( int256 tradeVolume, uint256 timestamp, uint256 price, uint8 v, bytes32 r, bytes32 s ) public override { _updatePriceWithSignature(timestamp, price, v, r, s); _trade(tradeVolume); } /** * @dev See {IPerpetualPool}.{depositMargin} */ function depositMargin(uint256 bAmount) public override { _updatePriceFromOracle(); _depositMargin(bAmount); } /** * @dev See {IPerpetualPool}.{depositMargin} */ function depositMargin( uint256 bAmount, uint256 timestamp, uint256 price, uint8 v, bytes32 r, bytes32 s ) public override { _updatePriceWithSignature(timestamp, price, v, r, s); _depositMargin(bAmount); } /** * @dev See {IPerpetualPool}.{withdrawMargin} */ function withdrawMargin(uint256 bAmount) public override { _updatePriceFromOracle(); _withdrawMargin(bAmount); } /** * @dev See {IPerpetualPool}.{withdrawMargin} */ function withdrawMargin( uint256 bAmount, uint256 timestamp, uint256 price, uint8 v, bytes32 r, bytes32 s ) public override { _updatePriceWithSignature(timestamp, price, v, r, s); _withdrawMargin(bAmount); } /** * @dev See {IPerpetualPool}.{addLiquidity} */ function addLiquidity(uint256 bAmount) public override { _updatePriceFromOracle(); _addLiquidity(bAmount); } /** * @dev See {IPerpetualPool}.{addLiquidity} */ function addLiquidity( uint256 bAmount, uint256 timestamp, uint256 price, uint8 v, bytes32 r, bytes32 s ) public override { _updatePriceWithSignature(timestamp, price, v, r, s); _addLiquidity(bAmount); } /** * @dev See {IPerpetualPool}.{removeLiquidity} */ function removeLiquidity(uint256 lShares) public override { _updatePriceFromOracle(); _removeLiquidity(lShares); } /** * @dev See {IPerpetualPool}.{removeLiquidity} */ function removeLiquidity( uint256 lShares, uint256 timestamp, uint256 price, uint8 v, bytes32 r, bytes32 s ) public override { _updatePriceWithSignature(timestamp, price, v, r, s); _removeLiquidity(lShares); } /** * @dev See {IPerpetualPool}.{liquidate} */ function liquidate(address owner) public override { require( address(_liquidatorQualifier) == address(0) || _liquidatorQualifier.isQualifiedLiquidator(msg.sender), "PerpetualPool: not quanlified liquidator" ); _updatePriceFromOracle(); _liquidate(owner, block.timestamp, _price); } /** * @dev See {IPerpetualPool}.{liquidate} * * A price signature with timestamp after position's lastUpdateTimestamp * will be a valid liquidation price */ function liquidate( address owner, uint256 timestamp, uint256 price, uint8 v, bytes32 r, bytes32 s ) public override { require( address(_liquidatorQualifier) == address(0) || _liquidatorQualifier.isQualifiedLiquidator(msg.sender), "PerpetualPool: not quanlified liquidator" ); _checkPriceSignature(timestamp, price, v, r, s); _liquidate(owner, timestamp, price); } //================================================================================ // Pool critic logics //================================================================================ /** * @dev Low level tradeWithMargin implementation * _lock_ is not need in this function, as sub-functions will apply _lock_ */ function _tradeWithMargin(int256 tradeVolume, uint256 bAmount) internal { if (bAmount == 0) { _trade(tradeVolume); } else if (tradeVolume == 0) { _depositMargin(bAmount); } else { _depositMargin(bAmount); _trade(tradeVolume); } } /** * @dev Low level trade implementation */ function _trade(int256 tradeVolume) internal _lock_ { require(tradeVolume != 0, "PerpetualPool: trade with 0 volume"); require(tradeVolume.reformat(0) == tradeVolume, "PerpetualPool: trade volume must be int"); // get trader's position, trader must have a position token to call this function (int256 volume, int256 cost, int256 lastCumuFundingRate, uint256 margin,) = _pToken.getPosition(msg.sender); // update cumulative funding rate _updateCumuFundingRate(_price); // calculate trader's funding fee int256 funding = volume.mul(_cumuFundingRate - lastCumuFundingRate); // calculate trading fee for this transaction int256 curCost = tradeVolume.mul(_price).mul(_multiplier); uint256 fee = _feeRatio.mul(curCost.abs()); // calculate realized cost int256 realizedCost = 0; if ((volume >= 0 && tradeVolume >= 0) || (volume <= 0 && tradeVolume <= 0)) { // open in same direction, no realized cost } else if (volume.abs() <= tradeVolume.abs()) { // previous position is flipped realizedCost = curCost.mul(volume.abs()).div(tradeVolume.abs()).add(cost); } else { // previous position is partially closed realizedCost = cost.mul(tradeVolume.abs()).div(volume.abs()).add(curCost); } // total paid in this transaction, could be negative if there is realized pnl // this paid amount should be a valid value in base token decimals representation int256 paid = funding.add(fee).add(realizedCost).reformat(_bDecimals); // settlements volume = volume.add(tradeVolume); cost = cost.add(curCost).sub(realizedCost); margin = margin.sub(paid); _tradersNetVolume = _tradersNetVolume.add(tradeVolume); _tradersNetCost = _tradersNetCost.add(curCost).sub(realizedCost); _liquidity = _liquidity.add(paid); lastCumuFundingRate = _cumuFundingRate; // check margin requirements require(volume == 0 || _calculateMarginRatio(volume, cost, _price, margin) >= _minInitialMarginRatio, "PerpetualPool: trader insufficient margin"); require(_tradersNetVolume == 0 || _calculateMarginRatio(_tradersNetVolume.neg(), _tradersNetCost.neg(), _price, _liquidity) >= _minPoolMarginRatio, "PerpetualPool: pool insufficient liquidity"); _pToken.update(msg.sender, volume, cost, lastCumuFundingRate, margin, block.timestamp); emit Trade(msg.sender, tradeVolume, _price); } /** * @dev Low level depositMargin implementation */ function _depositMargin(uint256 bAmount) internal _lock_ { require(bAmount != 0, "PerpetualPool: deposit zero margin"); require(bAmount.reformat(_bDecimals) == bAmount, "PerpetualPool: _depositMargin bAmount not valid"); bAmount = _deflationCompatibleSafeTransferFrom(msg.sender, address(this), bAmount); if (!_pToken.exists(msg.sender)) { _pToken.mint(msg.sender, bAmount); } else { (int256 volume, int256 cost, int256 lastCumuFundingRate, uint256 margin,) = _pToken.getPosition(msg.sender); margin = margin.add(bAmount); _pToken.update(msg.sender, volume, cost, lastCumuFundingRate, margin, block.timestamp); } emit DepositMargin(msg.sender, bAmount); } /** * @dev Low level withdrawMargin implementation */ function _withdrawMargin(uint256 bAmount) internal _lock_ { require(bAmount != 0, "PerpetualPool: withdraw zero margin"); require(bAmount.reformat(_bDecimals) == bAmount, "PerpetualPool: _withdrawMargin bAmount not valid"); (int256 volume, int256 cost, int256 lastCumuFundingRate, uint256 margin,) = _pToken.getPosition(msg.sender); _updateCumuFundingRate(_price); int256 funding = volume.mul(_cumuFundingRate - lastCumuFundingRate).reformat(_bDecimals); margin = margin.sub(funding).sub(bAmount); _liquidity = _liquidity.add(funding); lastCumuFundingRate = _cumuFundingRate; require(volume == 0 || _calculateMarginRatio(volume, cost, _price, margin) >= _minInitialMarginRatio, "PerpetualPool: withdraw cause insufficient margin"); _pToken.update(msg.sender, volume, cost, lastCumuFundingRate, margin, block.timestamp); _bToken.safeTransfer(msg.sender, bAmount.rescale(_bDecimals)); emit WithdrawMargin(msg.sender, bAmount); } /** * @dev Low level addLiquidity implementation */ function _addLiquidity(uint256 bAmount) internal _lock_ { require(bAmount >= _minAddLiquidity, "PerpetualPool: add liquidity less than minimum requirement"); require(bAmount.reformat(_bDecimals) == bAmount, "PerpetualPool: _addLiquidity bAmount not valid"); _updateCumuFundingRate(_price); bAmount = _deflationCompatibleSafeTransferFrom(msg.sender, address(this), bAmount); uint256 poolDynamicEquity = _liquidity.add(_tradersNetCost.sub(_tradersNetVolume.mul(_price).mul(_multiplier))); uint256 totalSupply = _lToken.totalSupply(); uint256 lShares; if (totalSupply == 0) { lShares = bAmount; } else { lShares = bAmount.mul(totalSupply).div(poolDynamicEquity); } _lToken.mint(msg.sender, lShares); _liquidity = _liquidity.add(bAmount); emit AddLiquidity(msg.sender, lShares, bAmount); } /** * @dev Low level removeLiquidity implementation */ function _removeLiquidity(uint256 lShares) internal _lock_ { require(lShares > 0, "PerpetualPool: remove 0 liquidity"); uint256 balance = _lToken.balanceOf(msg.sender); require(lShares == balance || balance.sub(lShares) >= 10**18, "PerpetualPool: remaining liquidity shares must be 0 or at least 1"); _updateCumuFundingRate(_price); uint256 poolDynamicEquity = _liquidity.add(_tradersNetCost.sub(_tradersNetVolume.mul(_price).mul(_multiplier))); uint256 totalSupply = _lToken.totalSupply(); uint256 bAmount = lShares.mul(poolDynamicEquity).div(totalSupply); if (lShares < totalSupply) { bAmount = bAmount.sub(bAmount.mul(_redemptionFeeRatio)); } bAmount = bAmount.reformat(_bDecimals); _liquidity = _liquidity.sub(bAmount); require(_tradersNetVolume == 0 || _calculateMarginRatio(_tradersNetVolume.neg(), _tradersNetCost.neg(), _price, _liquidity) >= _minPoolMarginRatio, "PerpetualPool: remove liquidity cause pool insufficient liquidity"); _lToken.burn(msg.sender, lShares); _bToken.safeTransfer(msg.sender, bAmount.rescale(_bDecimals)); emit RemoveLiquidity(msg.sender, lShares, bAmount); } /** * @dev Low level liquidate implementation */ function _liquidate(address owner, uint256 timestamp, uint256 price) internal _lock_ { (int256 volume, int256 cost, , uint256 margin, uint256 lastUpdateTimestamp) = _pToken.getPosition(owner); require(timestamp > lastUpdateTimestamp, "PerpetualPool: liquidate price is before position timestamp"); int256 pnl = volume.mul(price).mul(_multiplier).sub(cost); require(pnl.add(margin) <= 0 || _calculateMarginRatio(volume, cost, price, margin) < _minMaintenanceMarginRatio, "PerpetualPool: cannot liquidate"); _liquidity = _liquidity.add(margin); _tradersNetVolume = _tradersNetVolume.sub(volume); _tradersNetCost = _tradersNetCost.sub(cost); _pToken.update(owner, 0, 0, 0, 0, 0); uint256 reward; if (margin <= _minLiquidationReward) { reward = _minLiquidationReward; } else if (margin >= _maxLiquidationReward) { reward = _maxLiquidationReward; } else { reward = margin.sub(_minLiquidationReward).mul(_liquidationCutRatio).add(_minLiquidationReward); } reward = reward.reformat(_bDecimals); _liquidity = _liquidity.sub(reward); _bToken.safeTransfer(msg.sender, reward.rescale(_bDecimals)); emit Liquidate(owner, volume, cost, margin, timestamp, price, msg.sender, reward); } //================================================================================ // Helpers //================================================================================ /** * @dev Check if an address is a contract */ function _isContract(address addr) internal view returns (bool) { uint32 size; assembly { size := extcodesize(addr) } return size > 0; } /** * margin + unrealizedPnl *@dev margin ratio = -------------------------------------- * abs(volume) * price * multiplier * * volume cannot be zero */ function _calculateMarginRatio(int256 volume, int256 cost, uint256 price, uint256 margin) internal view returns (uint256) { int256 value = volume.mul(price).mul(_multiplier); uint256 ratio = margin.add(value.sub(cost)).div(value.abs()); return ratio; } /** * _tradersNetVolume * price * multiplier * @dev rate per block = ------------------------------------------- * coefficient * _liquidity */ function _updateCumuFundingRate(uint256 price) private { if (block.number > _cumuFundingRateBlock) { int256 rate; if (_liquidity != 0) { rate = _tradersNetVolume.mul(price).mul(_multiplier).mul(_fundingRateCoefficient).div(_liquidity); } else { rate = 0; } int256 delta = rate * (int256(block.number.sub(_cumuFundingRateBlock))); // overflow is intended _cumuFundingRate += delta; // overflow is intended _cumuFundingRateBlock = block.number; } } /** * @dev Check price signature */ function _checkPriceSignature(uint256 timestamp, uint256 price, uint8 v, bytes32 r, bytes32 s) internal view { require(v == 27 || v == 28, "PerpetualPool: v not valid"); bytes32 message = keccak256(abi.encodePacked(_symbol, timestamp, price)); bytes32 hash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", message)); address signer = ecrecover(hash, v, r, s); require(signer == address(_oracle), "PerpetualPool: price not signed by oracle"); } /** * @dev Check price signature to verify if price is authorized, and update _price * only check/update once for one block */ function _updatePriceWithSignature( uint256 timestamp, uint256 price, uint8 v, bytes32 r, bytes32 s ) internal { if (block.number != _lastPriceBlockNumber) { require(timestamp >= _lastPriceTimestamp, "PerpetualPool: price is not the newest"); require(block.timestamp - timestamp <= _priceDelayAllowance, "PerpetualPool: price is older than allowance"); _checkPriceSignature(timestamp, price, v, r, s); _price = price; _lastPriceTimestamp = timestamp; _lastPriceBlockNumber = block.number; } } /** * @dev Update price from on-chain Oracle */ function _updatePriceFromOracle() internal { require(_isContractOracle, "PerpetualPool: wrong type of orcale"); if (block.number != _lastPriceBlockNumber) { _price = _oracle.getPrice(); _lastPriceBlockNumber = block.number; } } /** * @dev safeTransferFrom for base token with deflation protection * Returns the actual received amount in base token (as base 10**18) */ function _deflationCompatibleSafeTransferFrom(address from, address to, uint256 amount) internal returns (uint256) { uint256 preBalance = _bToken.balanceOf(to); _bToken.safeTransferFrom(from, to, amount.rescale(_bDecimals)); uint256 curBalance = _bToken.balanceOf(to); uint256 a = curBalance.sub(preBalance); uint256 b = 10**18; uint256 c = a * b; require(c / b == a, "PreMiningPool: _deflationCompatibleSafeTransferFrom multiplication overflows"); uint256 actualReceivedAmount = c / (10 ** _bDecimals); return actualReceivedAmount; } } // 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 Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `amount` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 amount); /** * @dev Emitted when `amount` tokens are moved from one account (`from`) to * another (`to`). * * Note that `amount` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 amount); /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token, usually a shorter version of the name. */ function symbol() external view returns (string memory); /** * @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() external view returns (uint8); /** * @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 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 the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` 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 amount) external returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "./IERC721.sol"; /** * @title Deri Protocol non-fungible position token interface */ interface IPToken is IERC721 { /** * @dev Emitted when `owner`'s position is updated */ event Update( address indexed owner, int256 volume, int256 cost, int256 lastCumuFundingRate, uint256 margin, uint256 lastUpdateTimestamp ); /** * @dev Position struct */ struct Position { // Position volume, long is positive and short is negative int256 volume; // Position cost, long position cost is positive, short position cost is negative int256 cost; // The last cumuFundingRate since last funding settlement for this position // The overflow for this value is intended int256 lastCumuFundingRate; // Margin associated with this position uint256 margin; // Last timestamp this position updated uint256 lastUpdateTimestamp; } /** * @dev Set pool address of position token * pool is the only controller of this contract * can only be called by current pool */ function setPool(address newPool) external; /** * @dev Returns address of current pool */ function pool() external view returns (address); /** * @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 total number of ever minted position tokens, including those burned */ function totalMinted() external view returns (uint256); /** * @dev Returns the total number of existent position tokens */ function totalSupply() external view returns (uint256); /** * @dev Returns if `owner` owns a position token in this contract */ function exists(address owner) external view returns (bool); /** * @dev Returns if position token of `tokenId` exists */ function exists(uint256 tokenId) external view returns (bool); /** * @dev Returns the position of owner `owner` * * `owner` must exist */ function getPosition(address owner) external view returns ( int256 volume, int256 cost, int256 lastCumuFundingRate, uint256 margin, uint256 lastUpdateTimestamp ); /** * @dev Returns the position of token `tokenId` * * `tokenId` must exist */ function getPosition(uint256 tokenId) external view returns ( int256 volume, int256 cost, int256 lastCumuFundingRate, uint256 margin, uint256 lastUpdateTimestamp ); /** * @dev Mint a position token for `owner` with intial margin of `margin` * * Can only be called by pool * `owner` cannot be zero address * `owner` must not exist before calling */ function mint(address owner, uint256 margin) external; /** * @dev Update the position token for `owner` * * Can only be called by pool * `owner` must exist */ function update( address owner, int256 volume, int256 cost, int256 lastCumuFundingRate, uint256 margin, uint256 lastUpdateTimestamp ) external; /** * @dev Burn the position token owned of `owner` * * Can only be called by pool * `owner` must exist */ function burn(address owner) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "./IERC20.sol"; /** * @title Deri Protocol liquidity provider token interface */ interface ILToken is IERC20 { /** * @dev Set the pool address of this LToken * pool is the only controller of this contract * can only be called by current pool */ function setPool(address newPool) external; /** * @dev Returns address of pool */ function pool() external view returns (address); /** * @dev Mint LToken to `account` of `amount` * * Can only be called by pool * `account` cannot be zero address */ function mint(address account, uint256 amount) external; /** * @dev Burn `amount` LToken of `account` * * Can only be called by pool * `account` cannot be zero address * `account` must owns at least `amount` LToken */ function burn(address account, uint256 amount) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @title Oracle interface */ interface IOracle { function getPrice() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @title Deri Protocol liquidator qualifier interface */ interface ILiquidatorQualifier { /** * @dev Check if `liquidator` is a qualified liquidator to call the `liquidate` function in PerpetualPool */ function isQualifiedLiquidator(address liquidator) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Deri Protocol migratable pool interface */ interface IMigratablePool { /** * @dev Emitted when migration is prepared * `source` pool will be migrated to `target` pool after `migrationTimestamp` */ event PrepareMigration(uint256 migrationTimestamp, address source, address target); /** * @dev Emmited when migration is executed * `source` pool is migrated to `target` pool */ event ExecuteMigration(uint256 migrationTimestamp, address source, address target); /** * @dev Set controller to `newController` * * can only be called by current controller or the controller has not been set */ function setController(address newController) external; /** * @dev Returns address of current controller */ function controller() external view returns (address); /** * @dev Returns the migrationTimestamp of this pool, zero means not set */ function migrationTimestamp() external view returns (uint256); /** * @dev Returns the destination pool this pool will migrate to after grace period * zero address means not set */ function migrationDestination() external view returns (address); /** * @dev Prepare a migration from this pool to `newPool` with `graceDays` as grace period * `graceDays` must be at least 3 days from now, allow users to verify the `newPool` code * * can only be called by controller */ function prepareMigration(address newPool, uint256 graceDays) external; /** * @dev Approve migration to `newPool` when grace period ends * after approvement, current pool will stop functioning * * can only be called by controller */ function approveMigration() external; /** * @dev Called from the `newPool` to migrate from `source` pool * the grace period of `source` pool must ends * current pool must be the destination pool set before grace period in the `source` pool * * can only be called by controller */ function executeMigration(address source) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "./IMigratablePool.sol"; /** * @title Deri Protocol PreMining PerpetualPool Interface */ interface IPreMiningPool is IMigratablePool { /** * @dev Emitted when `owner` add liquidity of `bAmount`, * and receive `lShares` liquidity token */ event AddLiquidity(address indexed owner, uint256 lShares, uint256 bAmount); /** * @dev Emitted when `owner` burn `lShares` of liquidity token, * and receive `bAmount` in base token */ event RemoveLiquidity(address indexed owner, uint256 lShares, uint256 bAmount); /** * @dev Initialize pool * * addresses: * bToken * lToken * * parameters: * minAddLiquidity * redemptionFeeRatio */ function initialize( string memory symbol_, address[2] calldata addresses_, uint256[2] calldata parameters_ ) external; /** * @dev Returns trading symbol */ function symbol() external view returns (string memory); /** * @dev Returns addresses of (bToken, pToken, lToken, oracle) in this pool */ function getAddresses() external view returns ( address bToken, address lToken ); /** * @dev Returns parameters of this pool */ function getParameters() external view returns ( uint256 minAddLiquidity, uint256 redemptionFeeRatio ); /** * @dev Returns currents state values of this pool */ function getStateValues() external view returns ( uint256 liquidity ); /** * @dev Add liquidity of `bAmount` in base token * * New liquidity provider token will be issued to the provider */ function addLiquidity(uint256 bAmount) external; /** * @dev Remove `lShares` of liquidity provider token * * The liquidity provider token will be burned and * the corresponding amount in base token will be sent to provider */ function removeLiquidity(uint256 lShares) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "./IMigratablePool.sol"; /** * @title Deri Protocol PerpetualPool Interface */ interface IPerpetualPool is IMigratablePool { /** * @dev Emitted when `owner` traded `tradeVolume` at `price` in pool */ event Trade(address indexed owner, int256 tradeVolume, uint256 price); /** * @dev Emitted when `owner` deposit margin of `bAmount` in base token */ event DepositMargin(address indexed owner, uint256 bAmount); /** * @dev Emitted when `owner` withdraw margin of `bAmount` in base token */ event WithdrawMargin(address indexed owner, uint256 bAmount); /** * @dev Emitted when `owner` add liquidity of `bAmount`, * and receive `lShares` liquidity token */ event AddLiquidity(address indexed owner, uint256 lShares, uint256 bAmount); /** * @dev Emitted when `owner` burn `lShares` of liquidity token, * and receive `bAmount` in base token */ event RemoveLiquidity(address indexed owner, uint256 lShares, uint256 bAmount); /** * @dev Emitted when `owner`'s position is liquidated */ event Liquidate( address indexed owner, int256 volume, int256 cost, uint256 margin, uint256 timestamp, uint256 price, address liquidator, uint256 reward ); /** * @dev Initialize pool * * addresses: * bToken * pToken * lToken * oracle * liquidatorQualifier * * parameters: * multiplier * feeRatio * minPoolMarginRatio * minInitialMarginRatio * minMaintenanceMarginRatio * minAddLiquidity * redemptionFeeRatio * fundingRateCoefficient * minLiquidationReward * maxLiquidationReward * liquidationCutRatio * priceDelayAllowance */ function initialize( string memory symbol_, address[5] calldata addresses_, uint256[12] calldata parameters_ ) external; /** * @dev Returns trading symbol */ function symbol() external view returns (string memory); /** * @dev Returns addresses of (bToken, pToken, lToken, oracle) in this pool */ function getAddresses() external view returns ( address bToken, address pToken, address lToken, address oracle, address liquidatorQualifier ); /** * @dev Returns parameters of this pool */ function getParameters() external view returns ( uint256 multiplier, uint256 feeRatio, uint256 minPoolMarginRatio, uint256 minInitialMarginRatio, uint256 minMaintenanceMarginRatio, uint256 minAddLiquidity, uint256 redemptionFeeRatio, uint256 fundingRateCoefficient, uint256 minLiquidationReward, uint256 maxLiquidationReward, uint256 liquidationCutRatio, uint256 priceDelayAllowance ); /** * @dev Returns currents state values of this pool */ function getStateValues() external view returns ( int256 cumuFundingRate, uint256 cumuFundingRateBlock, uint256 liquidity, int256 tradersNetVolume, int256 tradersNetCost ); /** * @dev Trade `tradeVolume` with pool while deposit margin of `bAmount` in base token * This function is the combination of `depositMargin` and `trade` * * The first version is implemented with an on-chain oracle contract * The second version is implemented with off-chain price provider with signature */ function tradeWithMargin(int256 tradeVolume, uint256 bAmount) external; function tradeWithMargin( int256 tradeVolume, uint256 bAmount, uint256 timestamp, uint256 price, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Trade `tradeVolume` with pool * * A trader must hold a Position Token (with sufficient margin in PToken) * before calling this function * * The first version is implemented with an on-chain oracle contract * The second version is implemented with off-chain price provider with signature */ function trade(int256 tradeVolume) external; function trade( int256 tradeVolume, uint256 timestamp, uint256 price, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Deposit margin of `bAmount` in base token * * If trader does not hold position token, a new position token will be minted * to trader with supplied margin * Otherwise, the position token of trader will be updated with added margin * * The first version is implemented with an on-chain oracle contract * The second version is implemented with off-chain price provider with signature */ function depositMargin(uint256 bAmount) external; function depositMargin( uint256 bAmount, uint256 timestamp, uint256 price, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Withdraw margin of `bAmount` in base token * * Trader must hold a position token * If trader holds any open position in position token, the left margin after withdraw * must be sufficient for the open position * * The first version is implemented with an on-chain oracle contract * The second version is implemented with off-chain price provider with signature */ function withdrawMargin(uint256 bAmount) external; function withdrawMargin( uint256 bAmount, uint256 timestamp, uint256 price, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Add liquidity of `bAmount` in base token * * New liquidity provider token will be issued to the provider * * The first version is implemented with an on-chain oracle contract * The second version is implemented with off-chain price provider with signature */ function addLiquidity(uint256 bAmount) external; function addLiquidity( uint256 bAmount, uint256 timestamp, uint256 price, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Remove `lShares` of liquidity provider token * * The liquidity provider token will be burned and * the corresponding amount in base token will be sent to provider * * The first version is implemented with an on-chain oracle contract * The second version is implemented with off-chain price provider with signature */ function removeLiquidity(uint256 lShares) external; function removeLiquidity( uint256 lShares, uint256 timestamp, uint256 price, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Liquidate the position owned by `owner` * Anyone can call this function to liquidate a position, as long as the liquidation line * is touched, the liquidator will be rewarded * * The first version is implemented with an on-chain oracle contract * The second version is implemented with off-chain price provider with signature */ function liquidate(address owner) external; function liquidate( address owner, uint256 timestamp, uint256 price, uint8 v, bytes32 r, bytes32 s ) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../interface/IERC20.sol"; import "../math/UnsignedSafeMath.sol"; import "./Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using UnsignedSafeMath 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); _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; /** * @title Mixed safe math with base unit of 10**18 */ library MixedSafeMathWithUnit { uint256 constant UONE = 10**18; uint256 constant UMAX = 2**255 - 1; int256 constant IONE = 10**18; int256 constant IMIN = -2**255; //================================================================================ // Conversions //================================================================================ /** * @dev Convert uint256 to int256 */ function utoi(uint256 a) internal pure returns (int256) { require(a <= UMAX, "MixedSafeMathWithUnit: convert uint256 to int256 overflow"); int256 b = int256(a); return b; } /** * @dev Convert int256 to uint256 */ function itou(int256 a) internal pure returns (uint256) { require(a >= 0, "MixedSafeMathWithUnit: convert int256 to uint256 overflow"); uint256 b = uint256(a); return b; } /** * @dev Take abs of int256 */ function abs(int256 a) internal pure returns (int256) { require(a != IMIN, "MixedSafeMathWithUnit: int256 abs overflow"); if (a >= 0) { return a; } else { return -a; } } /** * @dev Take negation of int256 */ function neg(int256 a) internal pure returns (int256) { require(a != IMIN, "MixedSafeMathWithUnit: int256 negate overflow"); return -a; } //================================================================================ // Rescale and reformat //================================================================================ function _rescale(uint256 a, uint256 decimals1, uint256 decimals2) internal pure returns (uint256) { uint256 scale1 = 10 ** decimals1; uint256 scale2 = 10 ** decimals2; uint256 b = a * scale2; require(b / scale2 == a, "MixedSafeMathWithUnit: rescale uint256 overflow"); uint256 c = b / scale1; return c; } function _rescale(int256 a, uint256 decimals1, uint256 decimals2) internal pure returns (int256) { int256 scale1 = utoi(10 ** decimals1); int256 scale2 = utoi(10 ** decimals2); int256 b = a * scale2; require(b / scale2 == a, "MixedSafeMathWithUnit: rescale int256 overflow"); int256 c = b / scale1; return c; } /** * @dev Rescales a value from 10**18 base to 10**decimals base */ function rescale(uint256 a, uint256 decimals) internal pure returns (uint256) { return _rescale(a, 18, decimals); } function rescale(int256 a, uint256 decimals) internal pure returns (int256) { return _rescale(a, 18, decimals); } /** * @dev Reformat a value to be a valid 10**decimals base value * The formatted value is still in 10**18 base */ function reformat(uint256 a, uint256 decimals) internal pure returns (uint256) { return _rescale(_rescale(a, 18, decimals), decimals, 18); } function reformat(int256 a, uint256 decimals) internal pure returns (int256) { return _rescale(_rescale(a, 18, decimals), decimals, 18); } //================================================================================ // Addition //================================================================================ /** * @dev Addition: uint256 + uint256 */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "MixedSafeMathWithUnit: uint256 addition overflow"); return c; } /** * @dev Addition: int256 + int256 */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require( (b >= 0 && c >= a) || (b < 0 && c < a), "MixedSafeMathWithUnit: int256 addition overflow" ); return c; } /** * @dev Addition: uint256 + int256 * uint256(-b) will not overflow when b is IMIN */ function add(uint256 a, int256 b) internal pure returns (uint256) { if (b >= 0) { return add(a, uint256(b)); } else { return sub(a, uint256(-b)); } } /** * @dev Addition: int256 + uint256 */ function add(int256 a, uint256 b) internal pure returns (int256) { return add(a, utoi(b)); } //================================================================================ // Subtraction //================================================================================ /** * @dev Subtraction: uint256 - uint256 */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(a >= b, "MixedSafeMathWithUnit: uint256 subtraction overflow"); uint256 c = a - b; return c; } /** * @dev Subtraction: int256 - int256 */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require( (b >= 0 && c <= a) || (b < 0 && c > a), "MixedSafeMathWithUnit: int256 subtraction overflow" ); return c; } /** * @dev Subtraction: uint256 - int256 * uint256(-b) will not overflow when b is IMIN */ function sub(uint256 a, int256 b) internal pure returns (uint256) { if (b >= 0) { return sub(a, uint256(b)); } else { return add(a, uint256(-b)); } } /** * @dev Subtraction: int256 - uint256 */ function sub(int256 a, uint256 b) internal pure returns (int256) { return sub(a, utoi(b)); } //================================================================================ // Multiplication //================================================================================ /** * @dev Multiplication: uint256 * uint256 */ 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, "MixedSafeMathWithUnit: uint256 multiplication overflow"); return c / UONE; } /** * @dev Multiplication: int256 * int256 */ 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 == IMIN), "MixedSafeMathWithUnit: int256 multiplication overflow"); int256 c = a * b; require(c / a == b, "MixedSafeMathWithUnit: int256 multiplication overflow"); return c / IONE; } /** * @dev Multiplication: uint256 * int256 */ function mul(uint256 a, int256 b) internal pure returns (uint256) { return mul(a, itou(b)); } /** * @dev Multiplication: int256 * uint256 */ function mul(int256 a, uint256 b) internal pure returns (int256) { return mul(a, utoi(b)); } //================================================================================ // Division //================================================================================ /** * @dev Division: uint256 / uint256 */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "MixedSafeMathWithUnit: uint256 division by zero"); uint256 c = a * UONE; require( c / UONE == a, "MixedSafeMathWithUnit: uint256 division internal multiplication overflow" ); uint256 d = c / b; return d; } /** * @dev Division: int256 / int256 */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "MixedSafeMathWithUnit: int256 division by zero"); int256 c = a * IONE; require( c / IONE == a, "MixedSafeMathWithUnit: int256 division internal multiplication overflow" ); require(!(c == IMIN && b == -1), "MixedSafeMathWithUnit: int256 division overflow"); int256 d = c / b; return d; } /** * @dev Division: uint256 / int256 */ function div(uint256 a, int256 b) internal pure returns (uint256) { return div(a, itou(b)); } /** * @dev Division: int256 / uint256 */ function div(int256 a, uint256 b) internal pure returns (int256) { return div(a, utoi(b)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../interface/IMigratablePool.sol"; /** * @dev Deri Protocol migratable pool implementation */ abstract contract MigratablePool is IMigratablePool { // Controller address address _controller; // Migration timestamp of this pool, zero means not set // Migration timestamp can only be set with a grace period at least 3 days, and the // `migrationDestination` pool address must be also set when setting migration timestamp, // users can use this grace period to verify the `migrationDestination` pool code uint256 _migrationTimestamp; // The new pool this pool will migrate to after grace period, zero address means not set address _migrationDestination; modifier _controller_() { require(msg.sender == _controller, "can only be called by current controller"); _; } /** * @dev See {IMigratablePool}.{setController} */ function setController(address newController) public override { require(newController != address(0), "MigratablePool: setController to 0 address"); require( _controller == address(0) || msg.sender == _controller, "MigratablePool: setController can only be called by current controller or not set" ); _controller = newController; } /** * @dev See {IMigratablePool}.{controller} */ function controller() public view override returns (address) { return _controller; } /** * @dev See {IMigratablePool}.{migrationTimestamp} */ function migrationTimestamp() public view override returns (uint256) { return _migrationTimestamp; } /** * @dev See {IMigratablePool}.{migrationDestination} */ function migrationDestination() public view override returns (address) { return _migrationDestination; } /** * @dev See {IMigratablePool}.{prepareMigration} */ function prepareMigration(address newPool, uint256 graceDays) public override _controller_ { require(newPool != address(0), "MigratablePool: prepareMigration to 0 address"); require(graceDays >= 3 && graceDays <= 365, "MigratablePool: graceDays must be 3-365 days"); _migrationTimestamp = block.timestamp + graceDays * 1 days; _migrationDestination = newPool; emit PrepareMigration(_migrationTimestamp, address(this), _migrationDestination); } /** * @dev See {IMigratablePool}.{approveMigration} * * This function will be implemented in inheriting contract * This function will change if there is an upgrade to existent pool */ // function approveMigration() public virtual override _controller_ {} /** * @dev See {IMigratablePool}.{executeMigration} * * This function will be implemented in inheriting contract * This function will change if there is an upgrade to existent pool */ // function executeMigration(address source) public virtual override _controller_ {} } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "./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 `operator` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed operator, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables `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); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address); /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address); /** * @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 Gives permission to `operator` 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 operator, uint256 tokenId) external; /** * @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 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 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 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.6.0 <0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @title Unsigned safe math */ library UnsignedSafeMath { /** * @dev Addition of unsigned integers, counterpart to `+` */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "UnsignedSafeMath: addition overflow"); return c; } /** * @dev Subtraction of unsigned integers, counterpart to `-` */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(a >= b, "UnsignedSafeMath: subtraction overflow"); uint256 c = a - b; return c; } /** * @dev Multiplication of unsigned integers, counterpart to `*` */ 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, "UnsignedSafeMath: multiplication overflow"); return c; } /** * @dev Division of unsigned integers, counterpart to `/` */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "UnsignedSafeMath: division by zero"); uint256 c = a / b; return c; } /** * @dev Modulo of unsigned integers, counterpart to `%` */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "UnsignedSafeMath: modulo by zero"); uint256 c = a % b; return c; } } // 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); } } } }
* @dev Subtraction: uint256 - int256 uint256(-b) will not overflow when b is IMIN/
function sub(uint256 a, int256 b) internal pure returns (uint256) { if (b >= 0) { return sub(a, uint256(b)); return add(a, uint256(-b)); } }
582,197
[ 1, 1676, 25693, 30, 2254, 5034, 300, 509, 5034, 2254, 5034, 19236, 70, 13, 903, 486, 9391, 1347, 324, 353, 467, 6236, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 720, 12, 11890, 5034, 279, 16, 509, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 309, 261, 70, 1545, 374, 13, 288, 203, 5411, 327, 720, 12, 69, 16, 2254, 5034, 12, 70, 10019, 203, 5411, 327, 527, 12, 69, 16, 2254, 5034, 19236, 70, 10019, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0x2d3B52Ab8233f29c7F189B6AAbD4AF8de3036cC4/sources/contracts/mixins/MixinPurchase.sol
* Refund the specified gas amount and emit an event @notice this does sth only if `_gasRefundValue` is non-null/
function _refundGas() internal { if (_gasRefundValue != 0) { _transfer(tokenAddress, payable(msg.sender), _gasRefundValue); emit GasRefunded( msg.sender, _gasRefundValue, tokenAddress ); } }
9,435,087
[ 1, 21537, 326, 1269, 16189, 3844, 471, 3626, 392, 871, 225, 333, 1552, 24139, 1338, 309, 1375, 67, 31604, 21537, 620, 68, 353, 1661, 17, 2011, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 389, 1734, 1074, 27998, 1435, 2713, 288, 203, 565, 309, 261, 67, 31604, 21537, 620, 480, 374, 13, 288, 203, 203, 1377, 389, 13866, 12, 2316, 1887, 16, 8843, 429, 12, 3576, 18, 15330, 3631, 389, 31604, 21537, 620, 1769, 203, 203, 1377, 3626, 31849, 1957, 12254, 12, 203, 3639, 1234, 18, 15330, 16, 203, 3639, 389, 31604, 21537, 620, 16, 203, 3639, 1147, 1887, 203, 1377, 11272, 203, 565, 289, 203, 225, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.13; import "@openzeppelin/contracts/access/Roles.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; /** * @title AccessControl * @notice Role-based access control and related functions, function modifiers, and events */ contract AccessControl { using SafeMath for uint256; using Roles for Roles.Role; Roles.Role internal admins; Roles.Role internal franchise; Roles.Role internal shopOwners; /** * @dev constructor. Sets msg.sender as system admin by default */ constructor() public { paused = true; // Start paused. un-paused after full migration admins.add(msg.sender); franchise.add(msg.sender); } /** * @dev event emitted when contract is upgraded */ event ContractUpgrade(address newContract); /** * @dev event emitted when contract is paused */ event ContractPaused(); /** * @dev event emitted when contract is un-npaused */ event ContractUnpaused(); /** * dev state variable indicating whether the contract has been upgraded */ bool public upgraded = false; /** * @dev state variable indicating whether the contract is paused */ bool public paused = false; /** * Set in case the contract is broken and an upgrade is required */ address public newContractAddress; /** * @dev modifier to scope access to system administrator */ modifier onlySysAdmin() { require(admins.has(msg.sender)); _; } /** * @dev modifier to scope access to franchise owner */ modifier onlyFranchiseOwner() { require(franchise.has(msg.sender)); _; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev Modifier to make a function callable only when the contract not upgraded. */ modifier whenNotUpgraded() { require(!upgraded); _; } /** * @dev called by a system administrator to mark the smart contract as upgraded, * in case there is a serious breaking bug. This method stores the new contract * address and emits an event to that effect. Clients of the contract should * update to the new contract address upon receiving this event. * * This contract will remain paused indefinitely after such an upgrade. * * @param _newAddress address of new contract */ function upgradeContract(address _newAddress) external onlySysAdmin whenPaused whenNotUpgraded { upgraded = true; newContractAddress = _newAddress; emit ContractUpgrade(_newAddress); } /** * @dev called by the system administrator to pause, triggers stopped state */ function pause() public onlySysAdmin whenNotPaused { paused = true; emit ContractPaused(); } /** * @dev called by the ystem administrator to un-pause, returns to normal state */ function unpause() public onlySysAdmin whenPaused whenNotUpgraded { paused = false; emit ContractUnpaused(); } }
* dev state variable indicating whether the contract has been upgraded/
bool public upgraded = false;
12,693,211
[ 1, 5206, 919, 2190, 11193, 2856, 326, 6835, 711, 2118, 31049, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1426, 1071, 31049, 273, 629, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; contract EthGods { // imported contracts EthGodsName private eth_gods_name; function set_eth_gods_name_contract_address(address eth_gods_name_contract_address) public returns (bool) { require(msg.sender == admin); eth_gods_name = EthGodsName(eth_gods_name_contract_address); return true; } EthGodsDice private eth_gods_dice; function set_eth_gods_dice_contract_address(address eth_gods_dice_contract_address) public returns (bool) { require(msg.sender == admin); eth_gods_dice = EthGodsDice(eth_gods_dice_contract_address); return true; } // end of imported contracts // start of database //contract information & administration bool private contract_created; // in case constructor logic change in the future address private contract_address; //shown at the top of the home page string private contact_email = "[email protected]"; string private official_url = "swarm-gateways.net/bzz:/ethgods.eth"; address private admin; // public when testing address private controller1 = 0xcA5A9Db0EF9a0Bf5C38Fc86fdE6CB897d9d86adD; // controller can change admin at once; address private controller2 = 0x8396D94046a099113E5fe5CBad7eC95e96c2B796; // controller can change admin at once; address private v_god = 0xfB6916095ca1df60bB79Ce92cE3Ea74c37c5d359; uint private block_hash_duration = 255; // can't get block hash, after 256 blocks, adjustable // god struct god { uint god_id; uint level; uint exp; uint pet_type;// 12 animals or zodiacs uint pet_level; uint listed; // 0 not a god, 1 - ... rank_score in god list uint invite_price; uint blessing_player_id; bool hosted_pray; // auto waitlist, when enlisted. others can invite, once hosted pray uint bid_eth; // bid to host pray uint credit; // gained from the amulet invitation spending of invited fellows uint count_amulets_generated; uint first_amulet_generated; uint count_amulets_at_hand; uint count_amulets_selling; uint amulets_start_id; uint amulets_end_id; uint count_token_orders; uint first_active_token_order; uint allowed_block; // allow another account to use my egst uint block_number; // for pray bytes32 gene; bool gene_created; bytes32 pray_hash; //hash created for each pray uint inviter_id; // who invited this fellow to this world uint count_gods_invited; // gods invited to this game by this god. } uint private count_gods = 0; // Used when generating id for a new player, mapping(address => god) private gods; // everyone is a god mapping(uint => address) private gods_address; // gods' address => god_id uint [] private listed_gods; // id of listed gods uint private max_listed_gods = 10000; // adjustable uint private initial_invite_price = 0.02 ether; // grows with each invitation for this god uint private invite_price_increase = 0.02 ether; // grows by this amount with each invitation uint private max_invite_price = 1000 ether; // adjustable uint private max_extra_eth = 0.001 ether; // adjustable uint private list_level = 10; // start from level 10 uint private max_gas_price = 100000000000; // 100 gwei for invite and pray, adjustable // amulet struct amulet { uint god_id; address owner; uint level; uint bound_start_block;// can't sell, if just got // bool selling; uint start_selling_block; // can't bind & use in pk, if selling uint price; // set to 0, when withdraw from selling or bought // uint order_id; // should be 0, if not selling } uint private count_amulets = 0; mapping(uint => amulet) private amulets; // public when testing uint private bound_duration = 9000; // once bought, wait a while before sell it again, adjustable uint private order_duration = 20000; // valid for about 3 days, then not to show to public in selling amulets/token orders, but still show in my_selling amulets/token orders. adjustable // pray address private pray_host_god; // public when testing bool private pray_reward_top100; // if hosted by new god, reward top 100 gods egst uint private pray_start_block; // public when testing bool private rewarded_pray_winners = false; uint private count_hosted_gods; // gods hosted pray (event started). If less than bidding gods, there are new gods waiting to host pray, mapping (uint => address) private bidding_gods; // every listed god and bid to host pray uint private initializer_reward = 36; // reward the god who burned gas to send pray rewards to community, adjustable mapping(uint => uint) private max_winners; // max winners for each prize uint private min_pray_interval = 2000; // 2000, 36 in CBT, 2 in dev, adjustable uint private min_pray_duration = 6000; // 6000, 600 in CBT, 60 in dev, adjustable uint private max_pray_duration = 9000; // 9000, 900 in CBT, 90 in dev, adjustable uint private count_waiting_prayers; mapping (uint => address) private waiting_prayers; // uint is waiting sequence uint private waiting_prayer_index = 1; // waiting sequence of the prayer ready to draw lot mapping(uint => uint) private pk_positions; // public when testing mapping(uint => uint) private count_listed_winners; // count for 5 prizes, public in testing mapping (uint => mapping(uint => address)) private listed_winners; // winners for 5 prizes bool private reEntrancyMutex = false; // for sendnig eth to msg.sender uint private pray_egses = 0; // 10% from reward pool to top 3 winners in each round of pray events uint private pray_egst = 0; // 10% from reward pool to 3rd & 4th prize winners in each round of pray events mapping(address => uint) egses_balances; // eth_gods_token (EGST) string public name = "EthGodsToken"; string public symbol = "EGST"; uint8 public decimals = 18; //same as ethereum uint private _totalSupply; mapping(address => uint) balances; // bought or gained from pray or revenue share mapping(address => mapping(address => uint)) allowed; uint private allowed_use_CD = 20; // if used allowed amount, have to wait a while before approve new allowed amount again, prevent cheating, adjustable struct token_order { uint id; uint start_selling_block; address seller; uint unit_price; uint egst_amount; } uint private count_token_orders = 0; mapping (uint => token_order) token_orders; uint private first_active_token_order = 0; uint private min_unit_price = 20; // 1 egst min value is 0.0002 ether, adjustable uint private max_unit_price = 200; // 1 egst max value is 0.002 ether, adjustable uint private max_egst_amount = 1000000 ether; // for create_token_order, adjustable uint private min_egst_amount = 0.00001 ether; // for create_token_order, adjustable //logs uint private count_rounds = 0; struct winner_log { // win a prize and if pk uint god_block_number; bytes32 block_hash; address prayer; address previous_winner; uint prize; bool pk_result; } mapping (uint => uint) private count_rounds_winner_logs; mapping(uint => mapping(uint => winner_log)) private winner_logs; struct change_log { uint block_number; uint asset_type; // 1 egst, 2 eth_surplus // egses change reasons: // 1 pray_reward, 2 god_reward for being invited, 3 inviter_reward, // 4 admin_deposit to reward_pool, 5 withdraw egses // 6 sell amulet, 7 sell egst, 8 withdraw bid // egst_change reasons: // 1 pray_reward, 2 top_gods_reward, // 3 create_token_order, 4 withdraw token_order, 5 buy token, // 6 upgrade pet, 7 upgrade amulet, 8 admin_reward uint reason; // > 10 is buy token unit_price uint change_amount; uint after_amount; address _from; address _to; } mapping (uint => uint) private count_rounds_change_logs; mapping(uint => mapping(uint => change_log)) private change_logs; // end of database // start of constructor constructor () public { require (contract_created == false); contract_created = true; contract_address = address(this); admin = msg.sender; create_god(admin, 0); create_god(v_god, 0); gods[v_god].level = 10; enlist_god(v_god); max_winners[1] = 1; // 1 max_winners[2] = 2; // 2 max_winners[3] = 8; // 8 max_winners[4] = 16; // 16 max_winners[5] = 100; // 100 _totalSupply = 6000000 ether; pray_egst = 1000 ether; balances[admin] = sub(_totalSupply, pray_egst); initialize_pray(); } // destruct for testing contracts. can't destruct since round 3 function finalize() public { require(msg.sender == admin && count_rounds <= 3); selfdestruct(admin); } function () public payable { revert (); } // end of constructor //start of contract information & administration function get_controller () public view returns (address, address){ require (msg.sender == admin || msg.sender == controller1 || msg.sender == controller2); return (controller1, controller2); } function set_controller (uint controller_index, address new_controller_address) public returns (bool){ if (controller_index == 1){ require(msg.sender == controller2); controller1 = new_controller_address; } else { require(msg.sender == controller1); controller2 = new_controller_address; } return true; } function set_admin (address new_admin_address) public returns (bool) { require (msg.sender == controller1 || msg.sender == controller2); // admin don't have game attributes, such as level' // no need to transfer egses and egst to new_admin_address delete gods[admin]; admin = new_admin_address; gods_address[0] = admin; gods[admin].god_id = 0; return true; } // update system parameters function set_parameters (uint parameter_type, uint new_parameter) public returns (bool){ require (msg.sender == admin); if (parameter_type == 1) { max_pray_duration = new_parameter; } else if (parameter_type == 2) { min_pray_duration = new_parameter; } else if (parameter_type == 3) { block_hash_duration = new_parameter; } else if (parameter_type == 4) { min_pray_interval = new_parameter; } else if (parameter_type == 5) { order_duration = new_parameter; } else if (parameter_type == 6) { bound_duration = new_parameter; } else if (parameter_type == 7) { initializer_reward = new_parameter; } else if (parameter_type == 8) { allowed_use_CD = new_parameter; } else if (parameter_type == 9) { min_unit_price = new_parameter; } else if (parameter_type == 10) { max_unit_price = new_parameter; } else if (parameter_type == 11) { max_listed_gods = new_parameter; } else if (parameter_type == 12) { max_gas_price = new_parameter; } else if (parameter_type == 13) { max_invite_price = new_parameter; } else if (parameter_type == 14) { min_egst_amount = new_parameter; } else if (parameter_type == 15) { max_egst_amount = new_parameter; } else if (parameter_type == 16) { max_extra_eth = new_parameter; } return true; } function set_strings (uint string_type, string new_string) public returns (bool){ require (msg.sender == admin); if (string_type == 1){ official_url = new_string; } else if (string_type == 2){ name = new_string; // egst name } else if (string_type == 3){ symbol = new_string; // egst symbol } return true; } // for basic information to show to players, and to update parameter in sub-contracts function query_contract () public view returns(uint, uint, address, uint, string, uint, uint){ return (count_gods, listed_gods.length, admin, block_hash_duration, official_url, bound_duration, min_pray_interval ); } function query_uints () public view returns (uint[7] uints){ uints[0] = max_invite_price; uints[1] = list_level; uints[2] = max_pray_duration; uints[3] = min_pray_duration; uints[4] = initializer_reward; uints[5] = min_unit_price; uints[6] = max_unit_price; return uints; } function query_uints2 () public view returns (uint[6] uints){ uints[0] = allowed_use_CD; uints[1] = max_listed_gods; uints[2] = max_gas_price; uints[3] = min_egst_amount; uints[4] = max_egst_amount; uints[5] = max_extra_eth; return uints; } //end of contract information & administration // god related functions: register, create_god, upgrade_pet, add_exp, burn_gas, invite, enlist // if a new player comes when a round just completed, the new player may not want to initialize the next round function register_god (uint inviter_id) public returns (uint) { return create_god(msg.sender, inviter_id); } function create_god (address god_address, uint inviter_id) private returns(uint god_id){ // created by the contract // public when testing // check if the god is already created if (gods[god_address].credit == 0) { // create admin as god[0] gods[god_address].credit = 1; // give 1 credit, so we know this address has a god god_id = count_gods; // 1st god's id is admin 0 count_gods = add(count_gods, 1) ; gods_address[god_id] = god_address; gods[god_address].god_id = god_id; if (god_id > 0){ // not admin add_exp(god_address, 100); set_inviter(inviter_id); } return god_id; } } function set_inviter (uint inviter_id) public returns (bool){ if (inviter_id > 0 && gods_address[inviter_id] != address(0) && gods[msg.sender].inviter_id == 0 && gods[gods_address[inviter_id]].inviter_id != gods[msg.sender].god_id){ gods[msg.sender].inviter_id = inviter_id; address inviter_address = gods_address[inviter_id]; gods[inviter_address].count_gods_invited = add(gods[inviter_address].count_gods_invited, 1); return true; } } function add_exp (address god_address, uint exp_up) private returns(uint new_level, uint new_exp) { // public when testing if (god_address == admin){ return (0,0); } if (gods[god_address].god_id == 0){ uint inviter_id = gods[god_address].inviter_id; create_god(god_address, inviter_id); } new_exp = add(gods[god_address].exp, exp_up); uint current_god_level = gods[god_address].level; uint level_up_exp; new_level = current_god_level; for (uint i=0;i<10;i++){ // if still have extra exp, level up next time if (current_god_level < 99){ level_up_exp = mul(10, add(new_level, 1)); } else { level_up_exp = 1000; } if (new_exp >= level_up_exp){ new_exp = sub(new_exp, level_up_exp); new_level = add(new_level, 1); } else { break; } } gods[god_address].exp = new_exp; if(new_level > current_god_level) { gods[god_address].level = new_level; if (gods[god_address].listed > 0) { if (listed_gods.length > 1) { sort_gods(gods[god_address].god_id); } } else if (new_level >= list_level && listed_gods.length < max_listed_gods) { enlist_god(god_address); } } return (new_level, new_exp); } function enlist_god (address god_address) private returns (uint) { // public when testing require(gods[god_address].level >= list_level && god_address != admin); // if the god is not listed yet, enlist and add level requirement for the next enlist if (gods[god_address].listed == 0) { uint god_id = gods[god_address].god_id; if (god_id == 0){ god_id = create_god(god_address, 0); // get a god_id and set inviter as v god } gods[god_address].listed = listed_gods.push(god_id); // start from 1, 0 is not listed gods[god_address].invite_price = initial_invite_price; list_level = add(list_level, 1); bidding_gods[listed_gods.length] = god_address; } return list_level; } function sort_gods_admin(uint god_id) public returns (bool){ require (msg.sender == admin); sort_gods(god_id); return true; } // when a listed god level up and is not top 1 of the list, compare power with higher god, if higher than the higher god, swap position function sort_gods (uint god_id) private returns (uint){ require (god_id > 0); uint list_length = listed_gods.length; if (list_length > 1) { address god_address = gods_address[god_id]; uint this_god_listed = gods[god_address].listed; if (this_god_listed < list_length) { uint higher_god_listed = add(this_god_listed, 1); uint higher_god_id = listed_gods[sub(higher_god_listed, 1)]; address higher_god = gods_address[higher_god_id]; if(gods[god_address].level > gods[higher_god].level || (gods[god_address].level == gods[higher_god].level && gods[god_address].exp > gods[higher_god].exp)){ listed_gods[sub(this_god_listed, 1)] = higher_god_id; listed_gods[sub(higher_god_listed, 1)] = god_id; gods[higher_god].listed = this_god_listed; gods[god_address].listed = higher_god_listed; } } } return gods[god_address].listed; } function burn_gas (uint god_id) public returns (uint god_new_level, uint god_new_exp) { address god_address = gods_address[god_id]; require(god_id > 0 && god_id <= count_gods && gods[god_address].listed > 0); add_exp(god_address, 1); add_exp(msg.sender, 1); return (gods[god_address].level, gods[god_address].exp); // return bool, if out of gas } function invite (uint god_id) public payable returns (uint new_invite_price) { address god_address = gods_address[god_id]; require(god_id > 0 && god_id <= count_gods && gods[god_address].hosted_pray == true && tx.gasprice <= max_gas_price ); uint invite_price = gods[god_address].invite_price; require(msg.value >= invite_price); if (gods[god_address].invite_price < max_invite_price) { gods[god_address].invite_price = add(invite_price, invite_price_increase); } uint exp_up = div(invite_price, (10 ** 15)); // 1000 exp for each eth add_exp(god_address, exp_up); add_exp(msg.sender, exp_up); //generate a new amulet of this god for the inviter count_amulets ++; amulets[count_amulets].god_id = god_id; amulets[count_amulets].owner = msg.sender; gods[god_address].count_amulets_generated = add(gods[god_address].count_amulets_generated, 1); if (gods[god_address].count_amulets_generated == 1){ gods[god_address].first_amulet_generated = count_amulets; } gods[msg.sender].count_amulets_at_hand = add(gods[msg.sender].count_amulets_at_hand, 1); update_amulets_count(msg.sender, count_amulets, true); // invite_price to egses: 60% to pray_egses, 20% to god, changed // pray_egses = add(pray_egses, div(mul(60, invite_price), 100)); // egses_from_contract(gods_address[god_id], div(mul(20, invite_price), 100), 2); //2 reward god for being invited // reduce reward pool share from 60 to 50%, reduce god reward from 20% to 10% // add 20% share to blessing player (the last player invited this god) pray_egses = add(pray_egses, div(mul(50, invite_price), 100)); egses_from_contract(god_address, div(mul(10, invite_price), 100), 2); //2 reward god for being invited egses_from_contract(gods_address[gods[god_address].blessing_player_id], div(mul(20, invite_price), 100), 2); //2 reward god for being invited, no need to check if blessing player id is > 0 gods[god_address].blessing_player_id = gods[msg.sender].god_id; reward_inviter(msg.sender, invite_price); emit invited_god (msg.sender, god_id); return gods[god_address].invite_price; } event invited_god (address msg_sender, uint god_id); function reward_inviter (address inviter_address, uint invite_price) private returns (bool){ // the fellow spending eth also get credit and share uint previous_share = 0; uint inviter_share = 0; uint share_diff; // uint invite_credit = div(invite_price, 10 ** 15); for (uint i = 0; i < 9; i++){ // max trace 9 layers of inviter if (inviter_address != address(0) && inviter_address != admin){ // admin doesn't get reward or credit share_diff = 0; // gods[inviter_address].credit = add(gods[inviter_address].credit, invite_credit); gods[inviter_address].credit = add(gods[inviter_address].credit, invite_price); inviter_share = get_vip_level(inviter_address); if (inviter_share > previous_share) { share_diff = sub(inviter_share, previous_share); if (share_diff > 18) { share_diff = 18; } previous_share = inviter_share; } if (share_diff > 0) { egses_from_contract(inviter_address, div(mul(share_diff, invite_price), 100), 3); // 3 inviter_reward } inviter_address = gods_address[gods[inviter_address].inviter_id]; // get the address of inviter's inviter' } else{ break; } } // invite_price to egses: sub(20%, previous_share) to admin share_diff = sub(20, inviter_share); egses_from_contract(admin, div(mul(share_diff, invite_price), 100), 2); // remaining goes to admin, 2 god_reward for being invited return true; } function upgrade_pet () public returns(bool){ //use egst to level up pet; uint egst_cost = mul(add(gods[msg.sender].pet_level, 1), 10 ether); egst_to_contract(msg.sender, egst_cost, 6);// 6 upgrade_pet gods[msg.sender].pet_level = add(gods[msg.sender].pet_level, 1); add_exp(msg.sender, div(egst_cost, 1 ether)); pray_egst = add(pray_egst, egst_cost); // pray_egst = add(pray_egst, div(egst_cost, 2)); // egst_from_contract(admin, div(egst_cost, 2), 8); // 8 admin reward emit upgradeAmulet(msg.sender, 0, gods[msg.sender].pet_level); return true; } event upgradeAmulet (address owner, uint amulet_id, uint new_level); function set_pet_type (uint new_type) public returns (bool){ if (gods[msg.sender].pet_type != new_type) { gods[msg.sender].pet_type = new_type; return true; } } function get_vip_level (address god_address) public view returns (uint vip_level){ uint inviter_credit = gods[god_address].credit; if (inviter_credit > 500 ether){ vip_level = 18; } else if (inviter_credit > 200 ether){ vip_level = 15; } else if (inviter_credit > 100 ether){ vip_level = 12; } else if (inviter_credit > 50 ether){ vip_level = 10; } else if (inviter_credit > 20 ether){ vip_level = 8; } else if (inviter_credit > 10 ether){ vip_level = 6; } else if (inviter_credit > 5 ether){ vip_level = 5; } else if (inviter_credit > 2 ether){ vip_level = 4; } else if (inviter_credit > 1 ether){ vip_level = 3; } else if (inviter_credit > 0.5 ether){ vip_level = 2; } else { vip_level = 1; } return vip_level; } // view god's information function get_god_id (address god_address) public view returns (uint god_id){ return gods[god_address].god_id; } function get_god_address(uint god_id) public view returns (address){ return gods_address[god_id]; } function get_god (uint god_id) public view returns(uint, string, uint, uint, uint, uint, uint) { address god_address = gods_address[god_id]; string memory god_name; god_name = eth_gods_name.get_god_name(god_address); if (bytes(god_name).length == 0){ god_name = "Unknown"; } return (gods[god_address].god_id, god_name, gods[god_address].level, gods[god_address].exp, gods[god_address].invite_price, gods[god_address].listed, gods[god_address].blessing_player_id ); } function get_god_info (address god_address) public view returns (uint, bytes32, bool, uint, uint, uint, bytes32){ return (gods[god_address].block_number, gods[god_address].gene, gods[god_address].gene_created, gods[god_address].pet_type, gods[god_address].pet_level, gods[god_address].bid_eth, gods[god_address].pray_hash ); } function get_god_hosted_pray (uint god_id) public view returns (bool){ return gods[gods_address[god_id]].hosted_pray; } function get_my_info () public view returns(uint, uint, uint, uint, uint, uint, uint) { //private information return (gods[msg.sender].god_id, egses_balances[msg.sender], //egses balances[msg.sender], //egst get_vip_level(msg.sender), gods[msg.sender].credit, // inviter_credit gods[msg.sender].inviter_id, gods[msg.sender].count_gods_invited ); } function get_listed_gods (uint page_number) public view returns (uint[]){ uint count_listed_gods = listed_gods.length; require(count_listed_gods <= mul(page_number, 20)); uint[] memory tempArray = new uint[] (20); if (page_number < 1) { page_number = 1; } for (uint i = 0; i < 20; i++){ if(count_listed_gods > add(i, mul(20, sub(page_number, 1)))) { tempArray[i] = listed_gods[sub(sub(sub(count_listed_gods, i), 1), mul(20, sub(page_number, 1)))]; } else { break; } } return tempArray; } // amulets function upgrade_amulet (uint amulet_id) public returns(uint){ require(amulets[amulet_id].owner == msg.sender); uint egst_cost = mul(add(amulets[amulet_id].level, 1), 10 ether); egst_to_contract(msg.sender, egst_cost, 7);// reason 7, upgrade_amulet pray_egst = add(pray_egst, egst_cost); // pray_egst = add(pray_egst, div(egst_cost, 2)); // egst_from_contract(admin, div(egst_cost, 2), 8); // 8 admin reward amulets[amulet_id].level = add(amulets[amulet_id].level, 1); add_exp(msg.sender, div(egst_cost, 1 ether)); emit upgradeAmulet(msg.sender, amulet_id, amulets[amulet_id].level); return amulets[amulet_id].level; } function create_amulet_order (uint amulet_id, uint price) public returns (uint) { require(msg.sender == amulets[amulet_id].owner && amulet_id >= 1 && amulet_id <= count_amulets && amulets[amulet_id].start_selling_block == 0 && add(amulets[amulet_id].bound_start_block, bound_duration) < block.number && price > 0); amulets[amulet_id].start_selling_block = block.number; amulets[amulet_id].price = price; gods[msg.sender].count_amulets_at_hand = sub(gods[msg.sender].count_amulets_at_hand, 1); gods[msg.sender].count_amulets_selling = add(gods[msg.sender].count_amulets_selling, 1); return gods[msg.sender].count_amulets_selling; } function buy_amulet (uint amulet_id) public payable returns (bool) { uint price = amulets[amulet_id].price; require(msg.value >= price && msg.value < add(price, max_extra_eth) && amulets[amulet_id].start_selling_block > 0 && amulets[amulet_id].owner != msg.sender && price > 0); address seller = amulets[amulet_id].owner; amulets[amulet_id].owner = msg.sender; amulets[amulet_id].bound_start_block = block.number; amulets[amulet_id].start_selling_block = 0; gods[msg.sender].count_amulets_at_hand++; update_amulets_count(msg.sender, amulet_id, true); gods[seller].count_amulets_selling--; update_amulets_count(seller, amulet_id, false); egses_from_contract(seller, price, 6); // 6 sell amulet return true; } function withdraw_amulet_order (uint amulet_id) public returns (uint){ // an amulet can only have one order_id, so withdraw amulet_id instead of withdraw order_id, since only amulet_id is shown in amulets_at_hand require(msg.sender == amulets[amulet_id].owner && amulet_id >= 1 && amulet_id <= count_amulets && amulets[amulet_id].start_selling_block > 0); amulets[amulet_id].start_selling_block = 0; gods[msg.sender].count_amulets_at_hand++; gods[msg.sender].count_amulets_selling--; return gods[msg.sender].count_amulets_selling; } function update_amulets_count (address god_address, uint amulet_id, bool obtained) private returns (uint){ if (obtained == true){ if (amulet_id < gods[god_address].amulets_start_id) { gods[god_address].amulets_start_id = amulet_id; } } else { if (amulet_id == gods[god_address].amulets_start_id){ for (uint i = amulet_id; i <= count_amulets; i++){ if (amulets[i].owner == god_address && i > amulet_id){ gods[god_address].amulets_start_id = i; break; } } } } return gods[god_address].amulets_start_id; } function get_amulets_generated (uint god_id) public view returns (uint[]) { address god_address = gods_address[god_id]; uint count_amulets_generated = gods[god_address].count_amulets_generated; uint [] memory temp_list = new uint[](count_amulets_generated); uint count_elements = 0; for (uint i = gods[god_address].first_amulet_generated; i <= count_amulets; i++){ if (amulets[i].god_id == god_id){ temp_list [count_elements] = i; count_elements++; if (count_elements >= count_amulets_generated){ break; } } } return temp_list; } function get_amulets_at_hand (address god_address) public view returns (uint[]) { uint count_amulets_at_hand = gods[god_address].count_amulets_at_hand; uint [] memory temp_list = new uint[] (count_amulets_at_hand); uint count_elements = 0; for (uint i = gods[god_address].amulets_start_id; i <= count_amulets; i++){ if (amulets[i].owner == god_address && amulets[i].start_selling_block == 0){ temp_list[count_elements] = i; count_elements++; if (count_elements >= count_amulets_at_hand){ break; } } } return temp_list; } function get_my_amulets_selling () public view returns (uint[]){ uint count_amulets_selling = gods[msg.sender].count_amulets_selling; uint [] memory temp_list = new uint[] (count_amulets_selling); uint count_elements = 0; for (uint i = gods[msg.sender].amulets_start_id; i <= count_amulets; i++){ if (amulets[i].owner == msg.sender && amulets[i].start_selling_block > 0){ temp_list[count_elements] = i; count_elements++; if (count_elements >= count_amulets_selling){ break; } } } return temp_list; } // to calculate how many pages function get_amulet_orders_overview () public view returns(uint){ uint count_amulets_selling = 0; for (uint i = 1; i <= count_amulets; i++){ if (add(amulets[i].start_selling_block, order_duration) > block.number && amulets[i].owner != msg.sender){ count_amulets_selling ++; } } return count_amulets_selling; // to show page numbers when getting amulet_orders } function get_amulet_orders (uint page_number) public view returns (uint[]){ uint[] memory temp_list = new uint[] (20); uint count_amulets_selling = 0; uint count_list_elements = 0; if ((page_number < 1) || count_amulets <= 20) { page_number = 1; // chose a page out of range } uint start_amulets_count = mul(sub(page_number, 1), 20); for (uint i = 1; i <= count_amulets; i++){ if (add(amulets[i].start_selling_block, order_duration) > block.number && amulets[i].owner != msg.sender){ if (count_amulets_selling <= start_amulets_count) { count_amulets_selling ++; } if (count_amulets_selling > start_amulets_count){ temp_list[count_list_elements] = i; count_list_elements ++; if (count_list_elements >= 20){ break; } } } } return temp_list; } function get_amulet (uint amulet_id) public view returns(address, string, uint, uint, uint, uint, uint){ uint god_id = amulets[amulet_id].god_id; // address god_address = gods_address[god_id]; string memory god_name = eth_gods_name.get_god_name(gods_address[god_id]); uint god_level = gods[gods_address[god_id]].level; uint amulet_level = amulets[amulet_id].level; uint start_selling_block = amulets[amulet_id].start_selling_block; uint price = amulets[amulet_id].price; return(amulets[amulet_id].owner, god_name, god_id, god_level, amulet_level, start_selling_block, price ); } function get_amulet2 (uint amulet_id) public view returns(uint){ return amulets[amulet_id].bound_start_block; } // end of amulet // start of pray function admin_deposit (uint egst_amount) public payable returns (bool) { require (msg.sender == admin); if (msg.value > 0){ pray_egses = add(pray_egses, msg.value); egses_from_contract(admin, msg.value, 4); // 4 admin_deposit to reward_pool } if (egst_amount > 0){ pray_egst = add(pray_egst, egst_amount); egst_to_contract(admin, egst_amount, 4); // 4 admin_deposit to reward_pool } return true; } function initialize_pray () private returns (bool){ if (pray_start_block > 0) { require (check_event_completed() == true && rewarded_pray_winners == true); } count_rounds = add(count_rounds, 1); count_rounds_winner_logs[count_rounds] = 0; pray_start_block = block.number; rewarded_pray_winners = false; for (uint i = 1; i <= 5; i++){ pk_positions[i] = max_winners[i]; // pk start from the last slot count_listed_winners[i] = 0; } if (listed_gods.length > count_hosted_gods) { // a new god's turn count_hosted_gods = add(count_hosted_gods, 1); pray_host_god = bidding_gods[count_hosted_gods]; gods[pray_host_god].hosted_pray = true; pray_reward_top100 = true; } else { //choose highest bidder (uint highest_bid, address highest_bidder) = compare_bid_eth(); gods[highest_bidder].bid_eth = 0; pray_host_god = highest_bidder; pray_egses = add(pray_egses, highest_bid); pray_reward_top100 = false; } return true; } function bid_host () public payable returns (bool) { require (msg.value > 0 && gods[msg.sender].listed > 0); gods[msg.sender].bid_eth = add (gods[msg.sender].bid_eth, msg.value); return true; } function withdraw_bid () public returns (bool) { require(gods[msg.sender].bid_eth > 0); gods[msg.sender].bid_eth = 0; egses_from_contract(msg.sender, gods[msg.sender].bid_eth, 8); // 8 withdraw bid return true; } // if browser web3 didn't get god's credit, use pray_create in the pray button to create god_id first function pray_create (uint inviter_id) public returns (bool) { // when create a new god, set credit as 1, so credit <= 0 means god_id not created yet create_god(msg.sender, inviter_id); pray(); } // if browser web3 got god's credit, use pray in the pray button function pray () public returns (bool){ require (add(gods[msg.sender].block_number, min_pray_interval) < block.number && tx.gasprice <= max_gas_price && check_event_completed() == false); if (waiting_prayer_index <= count_waiting_prayers) { address waiting_prayer = waiting_prayers[waiting_prayer_index]; uint god_block_number = gods[waiting_prayer].block_number; bytes32 block_hash; if ((add(god_block_number, 1)) < block.number) {// can only get previous block hash if (add(god_block_number, block_hash_duration) < block.number) {// make sure this god has a valid block_number to generate block hash gods[waiting_prayer].block_number = block.number; // refresh this god's expired block_id // delete waiting_prayers[waiting_prayer_index]; count_waiting_prayers = add(count_waiting_prayers, 1); waiting_prayers[count_waiting_prayers] = waiting_prayer; } else {// draw lottery and/or create gene for the waiting prayer block_hash = keccak256(abi.encodePacked(blockhash(add(god_block_number, 1)))); if(gods[waiting_prayer].gene_created == false){ gods[waiting_prayer].gene = block_hash; gods[waiting_prayer].gene_created = true; } gods[waiting_prayer].pray_hash = block_hash; uint dice_result = eth_gods_dice.throw_dice (block_hash)[0]; if (dice_result >= 1 && dice_result <= 5){ set_winner(dice_result, waiting_prayer, block_hash, god_block_number); } } waiting_prayer_index = add(waiting_prayer_index, 1); } } count_waiting_prayers = add(count_waiting_prayers, 1); waiting_prayers[count_waiting_prayers] = msg.sender; gods[msg.sender].block_number = block.number; add_exp(msg.sender, 1); add_exp(pray_host_god, 1); return true; } function set_winner (uint prize, address waiting_prayer, bytes32 block_hash, uint god_block_number) private returns (uint){ count_rounds_winner_logs[count_rounds] = add(count_rounds_winner_logs[count_rounds], 1); winner_logs[count_rounds][count_rounds_winner_logs[count_rounds]].god_block_number = god_block_number; winner_logs[count_rounds][count_rounds_winner_logs[count_rounds]].block_hash = block_hash; winner_logs[count_rounds][count_rounds_winner_logs[count_rounds]].prayer = waiting_prayer; winner_logs[count_rounds][count_rounds_winner_logs[count_rounds]].prize = prize; if (count_listed_winners[prize] >= max_winners[prize]){ // winner_list maxed, so the new prayer challenge previous winners uint pk_position = pk_positions[prize]; address previous_winner = listed_winners[prize][pk_position]; bool pk_result = pk(waiting_prayer, previous_winner, block_hash); winner_logs[count_rounds][count_rounds_winner_logs[count_rounds]].pk_result = pk_result; winner_logs[count_rounds][count_rounds_winner_logs[count_rounds]].previous_winner = previous_winner; if (pk_result == true) { listed_winners[prize][pk_position] = waiting_prayer; // attacker defeat defender } if (prize > 1) { // no need to change pk_pos for champion if (pk_positions[prize] > 1){ pk_positions[prize] = sub(pk_positions[prize], 1); } else { pk_positions[prize] = max_winners[prize]; } } } else { count_listed_winners[prize] = add(count_listed_winners[prize], 1); listed_winners[prize][count_listed_winners[prize]] = waiting_prayer; } return count_listed_winners[prize]; } function reward_pray_winners () public returns (bool){ require (check_event_completed() == true); uint this_reward_egses; uint reward_pool_egses = div(pray_egses, 10); pray_egses = sub(pray_egses, reward_pool_egses); uint this_reward_egst; uint reward_pool_egst = div(pray_egst, 10); pray_egst = sub(pray_egst, reward_pool_egst); // reduce sum for less calculation egst_from_contract(pray_host_god, mul(div(reward_pool_egst, 100), 60), 1); // 1 pray_reward for hosting event for (uint i = 1; i<=5; i++){ this_reward_egses = 0; this_reward_egst = 0; if (i == 1) { this_reward_egses = mul(div(reward_pool_egses, 100), 60); } else if (i == 2){ this_reward_egses = mul(div(reward_pool_egses, 100), 20); } else if (i == 3){ this_reward_egst = mul(div(reward_pool_egst, 100), 3); } else if (i == 4){ this_reward_egst = div(reward_pool_egst, 100); } for (uint reward_i = 1; reward_i <= count_listed_winners[i]; reward_i++){ address rewarding_winner = listed_winners[i][reward_i]; if (this_reward_egses > 0 ) { egses_from_contract(rewarding_winner, this_reward_egses, 1); // 1 pray_reward } else if (this_reward_egst > 0) { egst_from_contract(rewarding_winner, this_reward_egst, 1); // 1 pray_reward } add_exp(rewarding_winner, 6); } } if(pray_reward_top100 == true) { reward_top_gods(); } // a small gift of exp & egst to the god who burned gas to send rewards to the community egst_from_contract(msg.sender, mul(initializer_reward, 1 ether), 1); // 1 pray_reward _totalSupply = add(_totalSupply, mul(initializer_reward, 1 ether)); add_exp(msg.sender, initializer_reward); rewarded_pray_winners = true; initialize_pray(); return true; } // more listed gods, more reward to the top gods, highest reward 600 egst function reward_top_gods () private returns (bool){ // public when testing uint count_listed_gods = listed_gods.length; uint last_god_index; if (count_listed_gods > 100) { last_god_index = sub(count_listed_gods, 100); } else { last_god_index = 0; } uint reward_egst = 0; uint base_reward = 6 ether; if (count_rounds == 6){ base_reward = mul(base_reward, 6); } for (uint i = last_god_index; i < count_listed_gods; i++) { reward_egst = mul(base_reward, sub(add(i, 1), last_god_index)); egst_from_contract(gods_address[listed_gods[i]], reward_egst, 2);// 2 top_gods_reward _totalSupply = add(_totalSupply, reward_egst); if (gods[gods_address[listed_gods[i]]].blessing_player_id > 0){ egst_from_contract(gods_address[gods[gods_address[listed_gods[i]]].blessing_player_id], reward_egst, 2);// 2 top_gods_reward _totalSupply = add(_totalSupply, reward_egst); } } return true; } function compare_bid_eth () private view returns (uint, address) { uint highest_bid = 0; address highest_bidder = v_god; // if no one bid, v god host this event for (uint j = 1; j <= listed_gods.length; j++){ if (gods[bidding_gods[j]].bid_eth > highest_bid){ highest_bid = gods[bidding_gods[j]].bid_eth; highest_bidder = bidding_gods[j]; } } return (highest_bid, highest_bidder); } function check_event_completed () public view returns (bool){ // check min and max pray_event duration if (add(pray_start_block, max_pray_duration) > block.number){ if (add(pray_start_block, min_pray_duration) < block.number){ for (uint i = 1; i <= 5; i++){ if(count_listed_winners[i] < max_winners[i]){ return false; } } return true; } else { return false; } } else { return true; } } function pk (address attacker, address defender, bytes32 block_hash) public view returns (bool pk_result){// make it public, view only, other contract may use it (uint attacker_sum_god_levels, uint attacker_sum_amulet_levels) = get_sum_levels_pk(attacker); (uint defender_sum_god_levels, uint defender_sum_amulet_levels) = get_sum_levels_pk(defender); pk_result = eth_gods_dice.pk(block_hash, attacker_sum_god_levels, attacker_sum_amulet_levels, defender_sum_god_levels, defender_sum_amulet_levels); return pk_result; } function get_sum_levels_pk (address god_address) public view returns (uint sum_gods_level, uint sum_amulets_level){ sum_gods_level = gods[god_address].level; sum_amulets_level = gods[god_address].pet_level; // add pet level to the sum uint amulet_god_id; uint amulet_god_level; for (uint i = 1; i <= count_amulets; i++){ if (amulets[i].owner == god_address && amulets[i].start_selling_block == 0){ amulet_god_id = amulets[i].god_id; amulet_god_level = gods[gods_address[amulet_god_id]].level; sum_gods_level = add(sum_gods_level, amulet_god_level); sum_amulets_level = add(sum_amulets_level, amulets[i].level); } } return (sum_gods_level, sum_amulets_level); } //admin need this function function get_listed_winners (uint prize) public view returns (address[]){ address [] memory temp_list = new address[] (count_listed_winners[prize]); for (uint i = 0; i < count_listed_winners[prize]; i++){ temp_list[i] = listed_winners[prize][add(i,1)]; } return temp_list; } function query_pray () public view returns (uint, uint, uint, address, address, uint, bool){ (uint highest_bid, address highest_bidder) = compare_bid_eth(); return (highest_bid, pray_egses, pray_egst, pray_host_god, highest_bidder, count_rounds, pray_reward_top100); } // end of pray // start of egses function egses_from_contract (address to, uint tokens, uint reason) private returns (bool) { // public when testing if (reason == 1) { require (pray_egses > tokens); pray_egses = sub(pray_egses, tokens); } egses_balances[to] = add(egses_balances[to], tokens); create_change_log(1, reason, tokens, egses_balances[to], contract_address, to); return true; } function egses_withdraw () public returns (uint tokens){ tokens = egses_balances[msg.sender]; require (tokens > 0 && contract_address.balance >= tokens && reEntrancyMutex == false); reEntrancyMutex = true; // if met problem, it will use up gas from msg.sender and roll back to false egses_balances[msg.sender] = 0; msg.sender.transfer(tokens); reEntrancyMutex = false; emit withdraw_egses(msg.sender, tokens); create_change_log(1, 5, tokens, 0, contract_address, msg.sender); // 5 withdraw egses return tokens; } event withdraw_egses (address receiver, uint tokens); // end of egses // start of erc20 for egst function totalSupply () public view returns (uint){ return _totalSupply; } function balanceOf (address tokenOwner) public view returns (uint){ return balances[tokenOwner]; // will return 0 if doesn't exist } function allowance (address tokenOwner, address spender) public view returns (uint) { return allowed[tokenOwner][spender]; } function transfer (address to, uint tokens) public returns (bool success){ require (balances[msg.sender] >= tokens); balances[msg.sender] = sub(balances[msg.sender], tokens); balances[to] = add(balances[to], tokens); emit Transfer(msg.sender, to, tokens); create_change_log(2, 9, tokens, balances[to], msg.sender, to); return true; } event Transfer (address indexed from, address indexed to, uint tokens); function approve (address spender, uint tokens) public returns (bool success) { // if allowed amount used and owner tries to reset allowed amount within a short time, // the allowed account might be cheating the owner require (balances[msg.sender] >= tokens); if (tokens > 0){ require (add(gods[msg.sender].allowed_block, allowed_use_CD) < block.number); } allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } event Approval (address indexed tokenOwner, address indexed spender, uint tokens); function transferFrom (address from, address to, uint tokens) public returns (bool success) { require (balances[from] >= tokens); allowed[from][msg.sender] = sub(allowed[from][msg.sender], tokens); balances[from] = sub(balances[from], tokens); balances[to] = add(balances[to], tokens); gods[from].allowed_block = block.number; emit Transfer(from, to, tokens); create_change_log(2, 10, tokens, balances[to], from, to); return true; } // end of erc20 for egst // egst function egst_from_contract (address to, uint tokens, uint reason) private returns (bool) { // public when testing balances[to] = add(balances[to], tokens); create_change_log(2, reason, tokens, balances[to], contract_address, to); return true; } function egst_to_contract (address from, uint tokens, uint reason) private returns (bool) { // public when testing require (balances[from] >= tokens); balances[from] = sub(balances[from], tokens); emit spend_egst(from, tokens, reason); create_change_log(2, reason, tokens, balances[from], from, contract_address); return true; } event spend_egst (address from, uint tokens, uint reason); function create_token_order (uint unit_price, uint egst_amount) public returns (uint) { require(unit_price >= min_unit_price && unit_price <= max_unit_price && balances[msg.sender] >= egst_amount && egst_amount <= max_egst_amount && egst_amount >= min_egst_amount); count_token_orders = add(count_token_orders, 1); egst_to_contract(msg.sender, egst_amount, 3); // 3 create_token_order token_orders[count_token_orders].start_selling_block = block.number; token_orders[count_token_orders].seller = msg.sender; token_orders[count_token_orders].unit_price = unit_price; token_orders[count_token_orders].egst_amount = egst_amount; gods[msg.sender].count_token_orders++; update_first_active_token_order(msg.sender); return gods[msg.sender].count_token_orders++; } function withdraw_token_order (uint order_id) public returns (bool) { require (msg.sender == token_orders[order_id].seller && token_orders[order_id].egst_amount > 0); uint egst_amount = token_orders[order_id].egst_amount; token_orders[order_id].start_selling_block = 0; token_orders[order_id].egst_amount = 0; // balances[msg.sender] = add(balances[msg.sender], tokens); egst_from_contract(msg.sender, egst_amount, 4); // 4 withdraw token_order gods[msg.sender].count_token_orders = sub(gods[msg.sender].count_token_orders, 1); update_first_active_token_order(msg.sender); emit WithdrawTokenOrder(msg.sender, order_id); return true; } event WithdrawTokenOrder (address seller, uint order_id); function buy_token (uint order_id, uint egst_amount) public payable returns (uint) { require(order_id >= first_active_token_order && order_id <= count_token_orders && egst_amount <= token_orders[order_id].egst_amount && token_orders[order_id].egst_amount > 0); // unit_price 100 means 1 egst = 0.001 ether uint eth_cost = div(mul(token_orders[order_id].unit_price, egst_amount), 100000); require(msg.value >= eth_cost && msg.value < add(eth_cost, max_extra_eth) ); token_orders[order_id].egst_amount = sub(token_orders[order_id].egst_amount, egst_amount); egst_from_contract(msg.sender, egst_amount, token_orders[order_id].unit_price); // uint price (> 10) will be recorded as reason in change log and translated by front end as buy token & unit_price // balances[msg.sender] = add(balances[msg.sender], egst_amount); address seller = token_orders[order_id].seller; egses_from_contract(seller, eth_cost, 7); // 7 sell egst if (token_orders[order_id].egst_amount <= 0){ token_orders[order_id].start_selling_block = 0; gods[seller].count_token_orders = sub(gods[seller].count_token_orders, 1); update_first_active_token_order(seller); } emit BuyToken(msg.sender, order_id, egst_amount); return token_orders[order_id].egst_amount; } event BuyToken (address buyer, uint order_id, uint egst_amount); function update_first_active_token_order (address god_address) private returns (uint, uint){ // public when testing if (count_token_orders > 0 && first_active_token_order == 0){ first_active_token_order = 1; } else { for (uint i = first_active_token_order; i <= count_token_orders; i++) { if (add(token_orders[i].start_selling_block, order_duration) > block.number){ // find the first active order and compare with the currect index if (i > first_active_token_order){ first_active_token_order = i; } break; } } } if (gods[god_address].count_token_orders > 0 && gods[god_address].first_active_token_order == 0){ gods[god_address].first_active_token_order = 1; // may not be 1, but it will correct next time } else { for (uint j = gods[god_address].first_active_token_order; j < count_token_orders; j++){ if (token_orders[j].seller == god_address && token_orders[j].start_selling_block > 0){ // don't check duration, show it to selling, even if expired // find the first active order and compare with the currect index if(j > gods[god_address].first_active_token_order){ gods[god_address].first_active_token_order = j; } break; } } } return (first_active_token_order, gods[msg.sender].first_active_token_order); } function get_token_order (uint order_id) public view returns(uint, address, uint, uint){ require(order_id >= 1 && order_id <= count_token_orders); return(token_orders[order_id].start_selling_block, token_orders[order_id].seller, token_orders[order_id].unit_price, token_orders[order_id].egst_amount); } // return total orders and lowest price to browser, browser query each active order and show at most three orders of lowest price function get_token_orders () public view returns(uint, uint, uint, uint, uint) { uint lowest_price = max_unit_price; for (uint i = first_active_token_order; i <= count_token_orders; i++){ if (token_orders[i].unit_price < lowest_price && token_orders[i].egst_amount > 0 && add(token_orders[i].start_selling_block, order_duration) > block.number){ lowest_price = token_orders[i].unit_price; } } return (count_token_orders, first_active_token_order, order_duration, max_unit_price, lowest_price); } function get_my_token_orders () public view returns(uint []) { uint my_count_token_orders = gods[msg.sender].count_token_orders; uint [] memory temp_list = new uint[] (my_count_token_orders); uint count_list_elements = 0; for (uint i = gods[msg.sender].first_active_token_order; i <= count_token_orders; i++){ if (token_orders[i].seller == msg.sender && token_orders[i].start_selling_block > 0){ temp_list[count_list_elements] = i; count_list_elements++; if (count_list_elements >= my_count_token_orders){ break; } } } return temp_list; } // end of egst // logs function get_winner_log (uint pray_round, uint log_id) public view returns (uint, bytes32, address, address, uint, bool){ require(log_id >= 1 && log_id <= count_rounds_winner_logs[pray_round]); winner_log storage this_winner_log = winner_logs[pray_round][log_id]; return (this_winner_log.god_block_number, this_winner_log.block_hash, this_winner_log.prayer, this_winner_log.previous_winner, this_winner_log.prize, this_winner_log.pk_result); } function get_count_rounds_winner_logs (uint pray_round) public view returns (uint){ return count_rounds_winner_logs[pray_round]; } // egses change reasons: // 1 pray_reward, 2 god_reward for being invited, 3 inviter_reward, // 4 admin_deposit to reward_pool, 5 withdraw egses // 6 sell amulet, 7 sell egst, 8 withdraw bid // egst_change reasons: // 1 pray_reward, 2 top_gods_reward, // 3 create_token_order, 4 withdraw token_order, 5 buy token (> 10), // 6 upgrade pet, 7 upgrade amulet, 8 admin_reward, // 9 transfer, 10 transferFrom(owner & receiver) function create_change_log (uint asset_type, uint reason, uint change_amount, uint after_amount, address _from, address _to) private returns (uint) { count_rounds_change_logs[count_rounds] = add(count_rounds_change_logs[count_rounds], 1); uint log_id = count_rounds_change_logs[count_rounds]; change_logs[count_rounds][log_id].block_number = block.number; change_logs[count_rounds][log_id].asset_type = asset_type; change_logs[count_rounds][log_id].reason = reason; change_logs[count_rounds][log_id].change_amount = change_amount; change_logs[count_rounds][log_id].after_amount = after_amount; change_logs[count_rounds][log_id]._from = _from; change_logs[count_rounds][log_id]._to = _to; return log_id; } function get_change_log (uint pray_round, uint log_id) public view returns (uint, uint, uint, uint, uint, address, address){ // public change_log storage this_log = change_logs[pray_round][log_id]; return (this_log.block_number, this_log.asset_type, this_log.reason, // reason > 10 is buy_token unit_price this_log.change_amount, this_log.after_amount, // god's after amount. transfer or transferFrom doesn't record log this_log._from, this_log._to); } function get_count_rounds_change_logs (uint pray_round) public view returns(uint){ return count_rounds_change_logs[pray_round]; } // end of logs // common functions function add (uint a, uint b) internal pure returns (uint c) { c = a + b; require(c >= a); } function sub (uint a, uint b) internal pure returns (uint c) { require(b <= a); c = a - b; } function mul (uint a, uint b) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function div (uint a, uint b) internal pure returns (uint c) { require(b > 0); c = a / b; } } contract EthGodsDice { // ethgods EthGods private eth_gods; address private ethgods_contract_address = address(0);// publish ethgods first, then use that address in constructor function set_eth_gods_contract_address(address eth_gods_contract_address) public returns (bool){ require (msg.sender == admin); ethgods_contract_address = eth_gods_contract_address; eth_gods = EthGods(ethgods_contract_address); return true; } address private admin; // manually update to ethgods' admin uint private block_hash_duration; function update_admin () public returns (bool){ (,,address new_admin, uint new_block_hash_duration,,,) = eth_gods.query_contract(); require (msg.sender == new_admin); admin = new_admin; block_hash_duration = new_block_hash_duration; return true; } //contract information & administration bool private contract_created; // in case constructor logic change in the future address private contract_address; //shown at the top of the home page // start of constructor and destructor constructor () public { require (contract_created == false); contract_created = true; contract_address = address(this); admin = msg.sender; } function finalize () public { require (msg.sender == admin); selfdestruct(msg.sender); } function () public payable { revert(); // if received eth for no reason, reject } // end of constructor and destructor function tell_fortune_blockhash () public view returns (bytes32){ bytes32 block_hash; (uint god_block_number,,,,,,) = eth_gods.get_god_info(msg.sender); if (god_block_number > 0 && add(god_block_number, 1) < block.number && add(god_block_number, block_hash_duration) > block.number) { block_hash = keccak256(abi.encodePacked(blockhash(god_block_number + 1))); } else { block_hash = keccak256(abi.encodePacked(blockhash(block.number - 1))); } return block_hash; } function tell_fortune () public view returns (uint[]){ bytes32 block_hash; (uint god_block_number,,,,,,) = eth_gods.get_god_info(msg.sender); if (god_block_number > 0 && add(god_block_number, 1) < block.number && add(god_block_number, block_hash_duration) > block.number) { block_hash = keccak256(abi.encodePacked(blockhash(god_block_number + 1))); } else { block_hash = keccak256(abi.encodePacked(blockhash(block.number - 1))); } return throw_dice (block_hash); } function throw_dice (bytes32 block_hash) public pure returns (uint[]) {// 0 for prize, 1-6 for 6 numbers should be pure uint[] memory dice_numbers = new uint[](7); //uint [7] memory dice_numbers; uint hash_number; uint[] memory count_dice_numbers = new uint[](7); //uint [7] memory count_dice_numbers; // how many times for each dice number uint i; // for loop for (i = 1; i <= 6; i++) { hash_number = uint(block_hash[i]); // hash_number=1; if (hash_number >= 214) { // 214 dice_numbers[i] = 6; } else if (hash_number >= 172) { // 172 dice_numbers[i] = 5; } else if (hash_number >= 129) { // 129 dice_numbers[i] = 4; } else if (hash_number >= 86) { // 86 dice_numbers[i] = 3; } else if (hash_number >= 43) { // 43 dice_numbers[i] = 2; } else { dice_numbers[i] = 1; } count_dice_numbers[dice_numbers[i]] ++; } bool won_super_prize = false; uint count_super_eth = 0; for (i = 1; i <= 6; i++) { if (count_dice_numbers[i] >= 5) { dice_numbers[0] = 1; //champion_eth won_super_prize = true; break; }else if (count_dice_numbers[i] == 4) { dice_numbers[0] = 3; // super_egst won_super_prize = true; break; }else if (count_dice_numbers[i] == 1) { count_super_eth ++; if (count_super_eth == 6) { dice_numbers[0] = 2; // super_eth won_super_prize = true; } } } if (won_super_prize == false) { if (count_dice_numbers[6] >= 2){ dice_numbers[0] = 4; // primary_egst } else if (count_dice_numbers[6] == 1){ dice_numbers[0] = 5; // lucky_star } } return dice_numbers; } function pk (bytes32 block_hash, uint attacker_sum_god_levels, uint attacker_sum_amulet_levels, uint defender_sum_god_levels, uint defender_sum_amulet_levels) public pure returns (bool){ uint god_win_chance; attacker_sum_god_levels = add(attacker_sum_god_levels, 10); if (attacker_sum_god_levels < defender_sum_god_levels){ god_win_chance = 0; } else { god_win_chance = sub(attacker_sum_god_levels, defender_sum_god_levels); if (god_win_chance > 20) { god_win_chance = 100; } else { // equal level, 50% chance to win god_win_chance = mul(god_win_chance, 5); } } uint amulet_win_chance; attacker_sum_amulet_levels = add(attacker_sum_amulet_levels, 10); if (attacker_sum_amulet_levels < defender_sum_amulet_levels){ amulet_win_chance = 0; } else { amulet_win_chance = sub(attacker_sum_amulet_levels, defender_sum_amulet_levels); if (amulet_win_chance > 20) { amulet_win_chance = 100; } else { // equal level, 50% chance to win amulet_win_chance = mul(amulet_win_chance, 5); } } uint attacker_win_chance = div(add(god_win_chance, amulet_win_chance), 2); if (attacker_win_chance >= div(mul(uint(block_hash[3]),2),5)){ return true; } else { return false; } } // common functions function add (uint a, uint b) internal pure returns (uint c) { c = a + b; require(c >= a); } function sub (uint a, uint b) internal pure returns (uint c) { require(b <= a); c = a - b; } function mul (uint a, uint b) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function div (uint a, uint b) internal pure returns (uint c) { require(b > 0); c = a / b; } } contract EthGodsName { // EthGods EthGods private eth_gods; address private ethgods_contract_address; function set_eth_gods_contract_address (address eth_gods_contract_address) public returns (bool){ require (msg.sender == admin); ethgods_contract_address = eth_gods_contract_address; eth_gods = EthGods(ethgods_contract_address); return true; } address private admin; // manually update to ethgods' admin function update_admin () public returns (bool){ (,,address new_admin,,,,) = eth_gods.query_contract(); require (msg.sender == new_admin); admin = new_admin; return true; } //contract information & administration bool private contract_created; // in case constructor logic change in the future address private contract_address; //shown at the top of the home page string private invalid_chars = "\\\""; bytes private invalid_bytes = bytes(invalid_chars); function set_invalid_chars (string new_invalid_chars) public returns (bool) { require(msg.sender == admin); invalid_chars = new_invalid_chars; invalid_bytes = bytes(invalid_chars); return true; } uint private valid_length = 16; function set_valid_length (uint new_valid_length) public returns (bool) { require(msg.sender == admin); valid_length = new_valid_length; return true; } struct god_name { string god_name; uint block_number; uint block_duration; } mapping (address => god_name) private gods_name; // start of constructor and destructor constructor () public { require (contract_created == false); contract_created = true; contract_address = address(this); admin = msg.sender; address v_god = 0xfB6916095ca1df60bB79Ce92cE3Ea74c37c5d359; gods_name[v_god].god_name = "V"; } function () public payable { revert(); // if received eth for no reason, reject } function finalize() public { require (msg.sender == admin); selfdestruct(msg.sender); } // end of constructor and destructor function set_god_name (string new_name) public returns (bool){ address god_address = msg.sender; require (add(gods_name[god_address].block_number, gods_name[god_address].block_duration) < block.number ); bytes memory bs = bytes(new_name); require (bs.length <= valid_length); for (uint i = 0; i < bs.length; i++){ for (uint j = 0; j < invalid_bytes.length; j++) { if (bs[i] == invalid_bytes[j]){ return false; } } } gods_name[god_address].god_name = new_name; emit set_name(god_address, new_name); return true; } event set_name (address indexed god_address, string new_name); function get_god_name (address god_address) public view returns (string) { return gods_name[god_address].god_name; } function block_god_name (address god_address, uint block_duration) public { require (msg.sender == admin); gods_name[god_address].god_name = "Unkown"; gods_name[god_address].block_number = block.number; gods_name[god_address].block_duration = block_duration; } function add (uint a, uint b) internal pure returns (uint c) { c = a + b; require(c >= a); } }
2000, 36 in CBT, 2 in dev, adjustable
uint private min_pray_interval = 2000;
997,167
[ 1, 17172, 16, 6580, 316, 21262, 56, 16, 576, 316, 4461, 16, 5765, 429, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 3238, 1131, 67, 84, 435, 67, 6624, 273, 16291, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: UNLICENSED pragma solidity =0.7.6; pragma experimental ABIEncoderV2; import "../openzeppelin/access/AccessControl.sol"; import "../openzeppelin/utils/math/SafeMath.sol"; import "../openzeppelin/token/ERC20/SafeERC20.sol"; import "../openzeppelin/token/ERC20/IERC20.sol"; import "../sablierhq/Sablier.sol"; import "./ITokenVesting.sol"; /** * @title TokenVesting contract for linearly vesting tokens to the respective vesting beneficiary * @dev This contract receives accepted proposals from the Manager contract, and pass it to sablier contract * @dev all the tokens to be vested by the vesting beneficiary. It releases these tokens when called * @dev upon in a continuous-like linear fashion. * @notice This contract use https://github.com/sablierhq/sablier-smooth-contracts/blob/master/contracts/Sablier.sol */ contract TokenVesting is ITokenVesting, AccessControl { using SafeMath for uint256; using SafeERC20 for IERC20; address sablier; uint256 constant CREATOR_IX = 0; uint256 constant ROLL_IX = 1; uint256 constant REFERRAL_IX = 2; uint256 public constant DAYS_IN_SECONDS = 24 * 60 * 60; mapping(address => VestingInfo) public vestingInfo; mapping(address => mapping(uint256 => Beneficiary)) public beneficiaries; mapping(address => address[]) public beneficiaryTokens; /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require( hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Ownable: caller is not the owner" ); _; } function transferOwnership(address newOwner) public virtual onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); grantRole(DEFAULT_ADMIN_ROLE, newOwner); revokeRole(DEFAULT_ADMIN_ROLE, msg.sender); } constructor(address newOwner) { _setupRole(DEFAULT_ADMIN_ROLE, newOwner); } function setSablier(address _sablier) external onlyOwner { sablier = _sablier; } /** * @dev Method to add a token into TokenVesting * @param _token address Address of token * @param _beneficiaries address[3] memory Address of vesting beneficiary * @param _proportions uint256[3] memory Proportions of vesting beneficiary * @param _vestingPeriodInDays uint256 Period of vesting, in units of Days, to be converted * @notice This emits an Event LogTokenAdded which is indexed by the token address */ function addToken( address _token, address[3] calldata _beneficiaries, uint256[3] calldata _proportions, uint256 _vestingPeriodInDays ) external override onlyOwner { uint256 duration = uint256(_vestingPeriodInDays).mul(DAYS_IN_SECONDS); require(duration > 0, "VESTING: period can't be zero"); uint256 stopTime = block.timestamp.add(duration); uint256 initial = IERC20(_token).balanceOf(address(this)); vestingInfo[_token] = VestingInfo({ vestingBeneficiary: _beneficiaries[0], totalBalance: initial, beneficiariesCount: 3, // this is to create a struct compatible with any number but for now is always 3 start: block.timestamp, stop: stopTime }); IERC20(_token).approve(sablier, 2**256 - 1); IERC20(_token).approve(address(this), 2**256 - 1); for (uint256 i = 0; i < vestingInfo[_token].beneficiariesCount; i++) { if (_beneficiaries[i] == address(0)) { continue; } beneficiaries[_token][i].beneficiary = _beneficiaries[i]; beneficiaries[_token][i].proportion = _proportions[i]; uint256 deposit = _proportions[i]; if (deposit == 0) { continue; } // we store the remaing to guarantee deposit be multiple of period. We send that remining at the end of period. uint256 remaining = deposit % duration; uint256 streamId = Sablier(sablier).createStream( _beneficiaries[i], deposit.sub(remaining), _token, block.timestamp, stopTime ); beneficiaries[_token][i].streamId = streamId; beneficiaries[_token][i].remaining = remaining; beneficiaryTokens[_beneficiaries[i]].push(_token); } emit LogTokenAdded(_token, _beneficiaries[0], _vestingPeriodInDays); } function getBeneficiaryId(address _token, address _beneficiary) internal view returns (uint256) { for (uint256 i = 0; i < vestingInfo[_token].beneficiariesCount; i++) { if (beneficiaries[_token][i].beneficiary == _beneficiary) { return i; } } revert("VESTING: invalid vesting address"); } function release(address _token, address _beneficiary) external override { uint256 ix = getBeneficiaryId(_token, _beneficiary); uint256 streamId = beneficiaries[_token][ix].streamId; if (!Sablier(sablier).isEntity(streamId)) { return; } uint256 balance = Sablier(sablier).balanceOf(streamId, _beneficiary); bool withdrawResult = Sablier(sablier).withdrawFromStream(streamId, balance); require(withdrawResult, "VESTING: Error calling withdrawFromStream"); // if vesting duration already finish then release the final dust if ( vestingInfo[_token].stop < block.timestamp && beneficiaries[_token][ix].remaining > 0 ) { IERC20(_token).safeTransferFrom( address(this), _beneficiary, beneficiaries[_token][ix].remaining ); } } function releaseableAmount(address _token) public view override returns (uint256) { uint256 total = 0; for (uint256 i = 0; i < vestingInfo[_token].beneficiariesCount; i++) { if (Sablier(sablier).isEntity(beneficiaries[_token][i].streamId)) { total = total + Sablier(sablier).balanceOf( beneficiaries[_token][i].streamId, beneficiaries[_token][i].beneficiary ); } } return total; } function releaseableAmountByAddress(address _token, address _beneficiary) public view override returns (uint256) { uint256 ix = getBeneficiaryId(_token, _beneficiary); uint256 streamId = beneficiaries[_token][ix].streamId; return Sablier(sablier).balanceOf(streamId, _beneficiary); } function vestedAmount(address _token) public view override returns (uint256) { VestingInfo memory info = vestingInfo[_token]; if (block.timestamp >= info.stop) { return info.totalBalance; } else { uint256 duration = info.stop.sub(info.start); return info.totalBalance.mul(block.timestamp.sub(info.start)).div( duration ); } } function getVestingInfo(address _token) external view override returns (VestingInfo memory) { return vestingInfo[_token]; } function updateVestingAddress( address _token, uint256 ix, address _vestingBeneficiary ) internal { if ( vestingInfo[_token].vestingBeneficiary == beneficiaries[_token][ix].beneficiary ) { vestingInfo[_token].vestingBeneficiary = _vestingBeneficiary; } beneficiaries[_token][ix].beneficiary = _vestingBeneficiary; uint256 deposit = 0; uint256 remaining = 0; { uint256 streamId = beneficiaries[_token][ix].streamId; // if there's no pending this will revert and it's ok because has no sense to update the address uint256 pending = Sablier(sablier).balanceOf(streamId, address(this)); uint256 duration = vestingInfo[_token].stop.sub(block.timestamp); deposit = pending.add(beneficiaries[_token][ix].remaining); remaining = deposit % duration; bool cancelResult = Sablier(sablier).cancelStream( beneficiaries[_token][ix].streamId ); require(cancelResult, "VESTING: Error calling cancelStream"); } uint256 streamId = Sablier(sablier).createStream( _vestingBeneficiary, deposit.sub(remaining), _token, block.timestamp, vestingInfo[_token].stop ); beneficiaries[_token][ix].streamId = streamId; beneficiaries[_token][ix].remaining = remaining; emit LogBeneficiaryUpdated(_token, _vestingBeneficiary); } function setVestingAddress( address _vestingBeneficiary, address _token, address _newVestingBeneficiary ) external override onlyOwner { uint256 ix = getBeneficiaryId(_token, _vestingBeneficiary); updateVestingAddress(_token, ix, _newVestingBeneficiary); } function setVestingReferral( address _vestingBeneficiary, address _token, address _vestingReferral ) external override onlyOwner { require( _vestingBeneficiary == vestingInfo[_token].vestingBeneficiary, "VESTING: Only creator" ); updateVestingAddress(_token, REFERRAL_IX, _vestingReferral); } function getAllTokensByBeneficiary(address _beneficiary) public view override returns (address[] memory) { return beneficiaryTokens[_beneficiary]; } function releaseAll(address _beneficiary) public override { address[] memory array = beneficiaryTokens[_beneficiary]; for (uint256 i = 0; i < array.length; i++) { this.release(array[i], _beneficiary); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/EnumerableSet.sol"; import "../utils/Address.sol"; import "../utils/Context.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 AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.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()); } } } // 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; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../utils/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.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 ); } pragma solidity =0.7.6; import "../openzeppelin/utils/Pausable.sol"; import "../openzeppelin/access/Ownable.sol"; import "../openzeppelin/token/ERC20/IERC20.sol"; import "../openzeppelin/utils/ReentrancyGuard.sol"; import "./compound/Exponential.sol"; import "./interfaces/IERC1620.sol"; import "./Types.sol"; /** * @title Sablier's Money Streaming * @author Sablier */ contract Sablier is IERC1620, Exponential, ReentrancyGuard { /*** Storage Properties ***/ /** * @dev The amount of interest has been accrued per token address. */ mapping(address => uint256) private earnings; /** * @notice The percentage fee charged by the contract on the accrued interest. */ Exp public fee; /** * @notice Counter for new stream ids. */ uint256 public nextStreamId; /** * @dev The stream objects identifiable by their unsigned integer ids. */ mapping(uint256 => Types.Stream) private streams; /*** Modifiers ***/ /** * @dev Throws if the caller is not the sender of the recipient of the stream. */ modifier onlySenderOrRecipient(uint256 streamId) { require( msg.sender == streams[streamId].sender || msg.sender == streams[streamId].recipient, "caller is not the sender or the recipient of the stream" ); _; } /** * @dev Throws if the provided id does not point to a valid stream. */ modifier streamExists(uint256 streamId) { require(streams[streamId].isEntity, "stream does not exist"); _; } /*** Contract Logic Starts Here */ constructor() public { nextStreamId = 1; } /*** View Functions ***/ function isEntity(uint256 streamId) external view returns (bool) { return streams[streamId].isEntity; } /** * @dev Returns the compounding stream with all its properties. * @dev Throws if the id does not point to a valid stream. * @param streamId The id of the stream to query. * @dev The stream object. */ function getStream(uint256 streamId) external view override streamExists(streamId) returns ( address sender, address recipient, uint256 deposit, address tokenAddress, uint256 startTime, uint256 stopTime, uint256 remainingBalance, uint256 ratePerSecond ) { sender = streams[streamId].sender; recipient = streams[streamId].recipient; deposit = streams[streamId].deposit; tokenAddress = streams[streamId].tokenAddress; startTime = streams[streamId].startTime; stopTime = streams[streamId].stopTime; remainingBalance = streams[streamId].remainingBalance; ratePerSecond = streams[streamId].ratePerSecond; } /** * @dev Returns either the delta in seconds between `block.timestamp` and `startTime` or * between `stopTime` and `startTime, whichever is smaller. If `block.timestamp` is before * `startTime`, it returns 0. * @dev Throws if the id does not point to a valid stream. * @param streamId The id of the stream for which to query the delta. * @dev The time delta in seconds. */ function deltaOf(uint256 streamId) public view streamExists(streamId) returns (uint256 delta) { Types.Stream memory stream = streams[streamId]; if (block.timestamp <= stream.startTime) return 0; if (block.timestamp < stream.stopTime) return block.timestamp - stream.startTime; return stream.stopTime - stream.startTime; } struct BalanceOfLocalVars { MathError mathErr; uint256 recipientBalance; uint256 withdrawalAmount; uint256 senderBalance; } /** * @dev Returns the available funds for the given stream id and address. * @dev Throws if the id does not point to a valid stream. * @param streamId The id of the stream for which to query the balance. * @param who The address for which to query the balance. * @dev @balance uint256 The total funds allocated to `who` as uint256. */ function balanceOf(uint256 streamId, address who) public view override streamExists(streamId) returns (uint256 balance) { Types.Stream memory stream = streams[streamId]; BalanceOfLocalVars memory vars; uint256 delta = deltaOf(streamId); (vars.mathErr, vars.recipientBalance) = mulUInt( delta, stream.ratePerSecond ); require( vars.mathErr == MathError.NO_ERROR, "recipient balance calculation error" ); /* * If the stream `balance` does not equal `deposit`, it means there have been withdrawals. * We have to subtract the total amount withdrawn from the amount of money that has been * streamed until now. */ if (stream.deposit > stream.remainingBalance) { (vars.mathErr, vars.withdrawalAmount) = subUInt( stream.deposit, stream.remainingBalance ); assert(vars.mathErr == MathError.NO_ERROR); (vars.mathErr, vars.recipientBalance) = subUInt( vars.recipientBalance, vars.withdrawalAmount ); /* `withdrawalAmount` cannot and should not be bigger than `recipientBalance`. */ assert(vars.mathErr == MathError.NO_ERROR); } if (who == stream.recipient) return vars.recipientBalance; if (who == stream.sender) { (vars.mathErr, vars.senderBalance) = subUInt( stream.remainingBalance, vars.recipientBalance ); /* `recipientBalance` cannot and should not be bigger than `remainingBalance`. */ assert(vars.mathErr == MathError.NO_ERROR); return vars.senderBalance; } return 0; } /*** Public Effects & Interactions Functions ***/ struct CreateStreamLocalVars { MathError mathErr; uint256 duration; uint256 ratePerSecond; } /** * @notice Creates a new stream funded by `msg.sender` and paid towards `recipient`. * @dev Throws if paused. * Throws if the recipient is the zero address, the contract itself or the caller. * Throws if the deposit is 0. * Throws if the start time is before `block.timestamp`. * Throws if the stop time is before the start time. * Throws if the duration calculation has a math error. * Throws if the deposit is smaller than the duration. * Throws if the deposit is not a multiple of the duration. * Throws if the rate calculation has a math error. * Throws if the next stream id calculation has a math error. * Throws if the contract is not allowed to transfer enough tokens. * Throws if there is a token transfer failure. * @param recipient The address towards which the money is streamed. * @param deposit The amount of money to be streamed. * @param tokenAddress The ERC20 token to use as streaming currency. * @param startTime The unix timestamp for when the stream starts. * @param stopTime The unix timestamp for when the stream stops. * @return The uint256 id of the newly created stream. */ function createStream( address recipient, uint256 deposit, address tokenAddress, uint256 startTime, uint256 stopTime ) public override returns (uint256) { require(recipient != address(0x00), "stream to the zero address"); require(recipient != address(this), "stream to the contract itself"); require(recipient != msg.sender, "stream to the caller"); require(deposit > 0, "deposit is zero"); require( startTime >= block.timestamp, "start time before block.timestamp" ); require(stopTime > startTime, "stop time before the start time"); CreateStreamLocalVars memory vars; (vars.mathErr, vars.duration) = subUInt(stopTime, startTime); /* `subUInt` can only return MathError.INTEGER_UNDERFLOW but we know `stopTime` is higher than `startTime`. */ assert(vars.mathErr == MathError.NO_ERROR); /* Without this, the rate per second would be zero. */ require(deposit >= vars.duration, "deposit smaller than time delta"); require( deposit % vars.duration == 0, "deposit not multiple of time delta" ); (vars.mathErr, vars.ratePerSecond) = divUInt(deposit, vars.duration); /* `divUInt` can only return MathError.DIVISION_BY_ZERO but we know `duration` is not zero. */ assert(vars.mathErr == MathError.NO_ERROR); /* Create and store the stream object. */ uint256 streamId = nextStreamId; streams[streamId] = Types.Stream({ remainingBalance: deposit, deposit: deposit, isEntity: true, ratePerSecond: vars.ratePerSecond, recipient: recipient, sender: msg.sender, startTime: startTime, stopTime: stopTime, tokenAddress: tokenAddress }); /* Increment the next stream id. */ (vars.mathErr, nextStreamId) = addUInt(nextStreamId, uint256(1)); require( vars.mathErr == MathError.NO_ERROR, "next stream id calculation error" ); require( IERC20(tokenAddress).transferFrom( msg.sender, address(this), deposit ), "token transfer failure" ); emit CreateStream( streamId, msg.sender, recipient, deposit, tokenAddress, startTime, stopTime ); return streamId; } struct WithdrawFromStreamLocalVars { MathError mathErr; } /** * @notice Withdraws from the contract to the recipient's account. * @dev Throws if the id does not point to a valid stream. * Throws if the caller is not the sender or the recipient of the stream. * Throws if the amount exceeds the available balance. * Throws if there is a token transfer failure. * @param streamId The id of the stream to withdraw tokens from. * @param amount The amount of tokens to withdraw. * @return bool true=success, otherwise false. */ function withdrawFromStream(uint256 streamId, uint256 amount) external override nonReentrant streamExists(streamId) onlySenderOrRecipient(streamId) returns (bool) { require(amount > 0, "amount is zero"); Types.Stream memory stream = streams[streamId]; WithdrawFromStreamLocalVars memory vars; uint256 balance = balanceOf(streamId, stream.recipient); require(balance >= amount, "amount exceeds the available balance"); (vars.mathErr, streams[streamId].remainingBalance) = subUInt( stream.remainingBalance, amount ); /** * `subUInt` can only return MathError.INTEGER_UNDERFLOW but we know that `remainingBalance` is at least * as big as `amount`. */ assert(vars.mathErr == MathError.NO_ERROR); if (streams[streamId].remainingBalance == 0) delete streams[streamId]; require( IERC20(stream.tokenAddress).transfer(stream.recipient, amount), "token transfer failure" ); emit WithdrawFromStream(streamId, stream.recipient, amount); return true; } /** * @notice Cancels the stream and transfers the tokens back on a pro rata basis. * @dev Throws if the id does not point to a valid stream. * Throws if the caller is not the sender or the recipient of the stream. * Throws if there is a token transfer failure. * @param streamId The id of the stream to cancel. * @return bool true=success, otherwise false. */ function cancelStream(uint256 streamId) external override nonReentrant streamExists(streamId) onlySenderOrRecipient(streamId) returns (bool) { Types.Stream memory stream = streams[streamId]; uint256 senderBalance = balanceOf(streamId, stream.sender); uint256 recipientBalance = balanceOf(streamId, stream.recipient); delete streams[streamId]; IERC20 token = IERC20(stream.tokenAddress); if (recipientBalance > 0) require( token.transfer(stream.recipient, recipientBalance), "recipient token transfer failure" ); if (senderBalance > 0) require( token.transfer(stream.sender, senderBalance), "sender token transfer failure" ); emit CancelStream( streamId, stream.sender, stream.recipient, senderBalance, recipientBalance ); return true; } } // SPDX-License-Identifier: UNLICENSED pragma solidity =0.7.6; pragma experimental ABIEncoderV2; interface ITokenVesting { event Released( address indexed token, address vestingBeneficiary, uint256 amount ); event LogTokenAdded( address indexed token, address vestingBeneficiary, uint256 vestingPeriodInDays ); event LogBeneficiaryUpdated( address indexed token, address vestingBeneficiary ); struct VestingInfo { address vestingBeneficiary; uint256 totalBalance; uint256 beneficiariesCount; uint256 start; uint256 stop; } struct Beneficiary { address beneficiary; uint256 proportion; uint256 streamId; uint256 remaining; } function addToken( address _token, address[3] calldata _beneficiaries, uint256[3] calldata _proportions, uint256 _vestingPeriodInDays ) external; function release(address _token, address _beneficiary) external; function releaseableAmount(address _token) external view returns (uint256); function releaseableAmountByAddress(address _token, address _beneficiary) external view returns (uint256); function vestedAmount(address _token) external view returns (uint256); function getVestingInfo(address _token) external view returns (VestingInfo memory); function setVestingAddress( address _vestingBeneficiary, address _token, address _newVestingBeneficiary ) external; function setVestingReferral( address _vestingBeneficiary, address _token, address _vestingReferral ) external; function getAllTokensByBeneficiary(address _beneficiary) external view returns (address[] memory); function releaseAll(address _beneficiary) external; } // 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 EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // 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.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; import "./Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity >=0.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; } } pragma solidity =0.7.6; import "./CarefulMath.sol"; /** * @title Exponential module for storing fixed-decision decimals * @author Compound * @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places. * Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is: * `Exp({mantissa: 5100000000000000000})`. */ contract Exponential is CarefulMath { uint256 constant expScale = 1e18; uint256 constant halfExpScale = expScale / 2; uint256 constant mantissaOne = expScale; struct Exp { uint256 mantissa; } /** * @dev Creates an exponential from numerator and denominator values. * Note: Returns an error if (`num` * 10e18) > MAX_INT, * or if `denom` is zero. */ function getExp(uint256 num, uint256 denom) internal pure returns (MathError, Exp memory) { (MathError err0, uint256 scaledNumerator) = mulUInt(num, expScale); if (err0 != MathError.NO_ERROR) { return (err0, Exp({ mantissa: 0 })); } (MathError err1, uint256 rational) = divUInt(scaledNumerator, denom); if (err1 != MathError.NO_ERROR) { return (err1, Exp({ mantissa: 0 })); } return (MathError.NO_ERROR, Exp({ mantissa: rational })); } /** * @dev Adds two exponentials, returning a new exponential. */ function addExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) { (MathError error, uint256 result) = addUInt(a.mantissa, b.mantissa); return (error, Exp({ mantissa: result })); } /** * @dev Subtracts two exponentials, returning a new exponential. */ function subExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) { (MathError error, uint256 result) = subUInt(a.mantissa, b.mantissa); return (error, Exp({ mantissa: result })); } /** * @dev Multiply an Exp by a scalar, returning a new Exp. */ function mulScalar(Exp memory a, uint256 scalar) internal pure returns (MathError, Exp memory) { (MathError err0, uint256 scaledMantissa) = mulUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({ mantissa: 0 })); } return (MathError.NO_ERROR, Exp({ mantissa: scaledMantissa })); } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mulScalarTruncate(Exp memory a, uint256 scalar) internal pure returns (MathError, uint256) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(product)); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mulScalarTruncateAddUInt( Exp memory a, uint256 scalar, uint256 addend ) internal pure returns (MathError, uint256) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return addUInt(truncate(product), addend); } /** * @dev Divide an Exp by a scalar, returning a new Exp. */ function divScalar(Exp memory a, uint256 scalar) internal pure returns (MathError, Exp memory) { (MathError err0, uint256 descaledMantissa) = divUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({ mantissa: 0 })); } return (MathError.NO_ERROR, Exp({ mantissa: descaledMantissa })); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function divScalarByExp(uint256 scalar, Exp memory divisor) internal pure returns (MathError, Exp memory) { /* We are doing this as: getExp(mulUInt(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ (MathError err0, uint256 numerator) = mulUInt(expScale, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({ mantissa: 0 })); } return getExp(numerator, divisor.mantissa); } /** * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer. */ function divScalarByExpTruncate(uint256 scalar, Exp memory divisor) internal pure returns (MathError, uint256) { (MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(fraction)); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) { (MathError err0, uint256 doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa); if (err0 != MathError.NO_ERROR) { return (err0, Exp({ mantissa: 0 })); } // We add half the scale before dividing so that we get rounding instead of truncation. // See "Listing 6" and text above it at https://accu.org/index.php/journals/1717 // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. (MathError err1, uint256 doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct); if (err1 != MathError.NO_ERROR) { return (err1, Exp({ mantissa: 0 })); } (MathError err2, uint256 product) = divUInt(doubleScaledProductWithHalfScale, expScale); // The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == MathError.NO_ERROR); return (MathError.NO_ERROR, Exp({ mantissa: product })); } /** * @dev Multiplies two exponentials given their mantissas, returning a new exponential. */ function mulExp(uint256 a, uint256 b) internal pure returns (MathError, Exp memory) { return mulExp(Exp({ mantissa: a }), Exp({ mantissa: b })); } /** * @dev Multiplies three exponentials, returning a new exponential. */ function mulExp3( Exp memory a, Exp memory b, Exp memory c ) internal pure returns (MathError, Exp memory) { (MathError err, Exp memory ab) = mulExp(a, b); if (err != MathError.NO_ERROR) { return (err, ab); } return mulExp(ab, c); } /** * @dev Divides two exponentials, returning a new exponential. * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b, * which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa) */ function divExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) { return getExp(a.mantissa, b.mantissa); } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * expScale}) = 15 */ function truncate(Exp memory exp) internal pure returns (uint256) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; } /** * @dev Checks if first Exp is less than second Exp. */ function lessThanExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa < right.mantissa; //TODO: Add some simple tests and this in another PR yo. } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev Checks if left Exp > right Exp. */ function greaterThanExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa > right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) internal pure returns (bool) { return value.mantissa == 0; } } pragma solidity =0.7.6; /** * @title ERC-1620 Money Streaming Standard * @author Sablier * @dev See https://eips.ethereum.org/EIPS/eip-1620 */ interface IERC1620 { /** * @notice Emits when a stream is successfully created. */ event CreateStream( uint256 indexed streamId, address indexed sender, address indexed recipient, uint256 deposit, address tokenAddress, uint256 startTime, uint256 stopTime ); /** * @notice Emits when the recipient of a stream withdraws a portion or all their pro rata share of the stream. */ event WithdrawFromStream( uint256 indexed streamId, address indexed recipient, uint256 amount ); /** * @notice Emits when a stream is successfully cancelled and tokens are transferred back on a pro rata basis. */ event CancelStream( uint256 indexed streamId, address indexed sender, address indexed recipient, uint256 senderBalance, uint256 recipientBalance ); function balanceOf(uint256 streamId, address who) external view returns (uint256 balance); function getStream(uint256 streamId) external view returns ( address sender, address recipient, uint256 deposit, address token, uint256 startTime, uint256 stopTime, uint256 remainingBalance, uint256 ratePerSecond ); function createStream( address recipient, uint256 deposit, address tokenAddress, uint256 startTime, uint256 stopTime ) external returns (uint256 streamId); function withdrawFromStream(uint256 streamId, uint256 funds) external returns (bool); function cancelStream(uint256 streamId) external returns (bool); } pragma solidity =0.7.6; /** * @title Sablier Types * @author Sablier */ library Types { struct Stream { uint256 deposit; uint256 ratePerSecond; uint256 remainingBalance; uint256 startTime; uint256 stopTime; address recipient; address sender; address tokenAddress; bool isEntity; } } pragma solidity =0.7.6; /** * @title Careful Math * @author Compound * @notice Derived from OpenZeppelin's SafeMath library * https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol */ contract CarefulMath { /** * @dev Possible error codes that we can return */ enum MathError { NO_ERROR, DIVISION_BY_ZERO, INTEGER_OVERFLOW, INTEGER_UNDERFLOW } /** * @dev Multiplies two numbers, returns an error on overflow. */ function mulUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { if (a == 0) { return (MathError.NO_ERROR, 0); } uint256 c = a * b; if (c / a != b) { return (MathError.INTEGER_OVERFLOW, 0); } else { return (MathError.NO_ERROR, c); } } /** * @dev Integer division of two numbers, truncating the quotient. */ function divUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { if (b == 0) { return (MathError.DIVISION_BY_ZERO, 0); } return (MathError.NO_ERROR, a / b); } /** * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function subUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { if (b <= a) { return (MathError.NO_ERROR, a - b); } else { return (MathError.INTEGER_UNDERFLOW, 0); } } /** * @dev Adds two numbers, returns an error on overflow. */ function addUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { uint256 c = a + b; if (c >= a) { return (MathError.NO_ERROR, c); } else { return (MathError.INTEGER_OVERFLOW, 0); } } /** * @dev add a and b and then subtract c */ function addThenSubUInt( uint256 a, uint256 b, uint256 c ) internal pure returns (MathError, uint256) { (MathError err0, uint256 sum) = addUInt(a, b); if (err0 != MathError.NO_ERROR) { return (err0, 0); } return subUInt(sum, c); } }
* @dev Returns either the delta in seconds between `block.timestamp` and `startTime` or between `stopTime` and `startTime, whichever is smaller. If `block.timestamp` is before `startTime`, it returns 0. @dev Throws if the id does not point to a valid stream. @param streamId The id of the stream for which to query the delta. @dev The time delta in seconds./
function deltaOf(uint256 streamId) public view streamExists(streamId) returns (uint256 delta) { Types.Stream memory stream = streams[streamId]; if (block.timestamp <= stream.startTime) return 0; if (block.timestamp < stream.stopTime) return block.timestamp - stream.startTime; return stream.stopTime - stream.startTime; }
12,569,771
[ 1, 1356, 3344, 326, 3622, 316, 3974, 3086, 1375, 2629, 18, 5508, 68, 471, 1375, 1937, 950, 68, 578, 225, 3086, 1375, 5681, 950, 68, 471, 1375, 1937, 950, 16, 600, 335, 580, 502, 353, 10648, 18, 971, 1375, 2629, 18, 5508, 68, 353, 1865, 225, 1375, 1937, 950, 9191, 518, 1135, 374, 18, 225, 22435, 309, 326, 612, 1552, 486, 1634, 358, 279, 923, 1407, 18, 225, 21035, 1021, 612, 434, 326, 1407, 364, 1492, 358, 843, 326, 3622, 18, 225, 1021, 813, 3622, 316, 3974, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 3622, 951, 12, 11890, 5034, 21035, 13, 203, 202, 202, 482, 203, 202, 202, 1945, 203, 202, 202, 3256, 4002, 12, 3256, 548, 13, 203, 202, 202, 6154, 261, 11890, 5034, 3622, 13, 203, 202, 95, 203, 202, 202, 2016, 18, 1228, 3778, 1407, 273, 8205, 63, 3256, 548, 15533, 203, 202, 202, 430, 261, 2629, 18, 5508, 1648, 1407, 18, 1937, 950, 13, 327, 374, 31, 203, 202, 202, 430, 261, 2629, 18, 5508, 411, 1407, 18, 5681, 950, 13, 203, 1082, 202, 2463, 1203, 18, 5508, 300, 1407, 18, 1937, 950, 31, 203, 202, 202, 2463, 1407, 18, 5681, 950, 300, 1407, 18, 1937, 950, 31, 203, 202, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // Global Enums and Structs struct StrategyParams { uint256 performanceFee; uint256 activation; uint256 debtRatio; uint256 minDebtPerHarvest; uint256 maxDebtPerHarvest; uint256 lastReport; uint256 totalDebt; uint256 totalGain; uint256 totalLoss; } // Part: Account library Account { enum Status {Normal, Liquid, Vapor} struct Info { address owner; // The address that owns the account uint256 number; // A nonce that allows a single address to control many accounts } struct Storage { mapping(uint256 => Types.Par) balances; // Mapping from marketId to principal Status status; } } // Part: Actions library Actions { enum ActionType { Deposit, // supply tokens Withdraw, // borrow tokens Transfer, // transfer balance between accounts Buy, // buy an amount of some token (publicly) Sell, // sell an amount of some token (publicly) Trade, // trade tokens against another account Liquidate, // liquidate an undercollateralized or expiring account Vaporize, // use excess tokens to zero-out a completely negative account Call // send arbitrary data to an address } enum AccountLayout {OnePrimary, TwoPrimary, PrimaryAndSecondary} enum MarketLayout {ZeroMarkets, OneMarket, TwoMarkets} struct ActionArgs { ActionType actionType; uint256 accountId; Types.AssetAmount amount; uint256 primaryMarketId; uint256 secondaryMarketId; address otherAddress; uint256 otherAccountId; bytes data; } struct DepositArgs { Types.AssetAmount amount; Account.Info account; uint256 market; address from; } struct WithdrawArgs { Types.AssetAmount amount; Account.Info account; uint256 market; address to; } struct TransferArgs { Types.AssetAmount amount; Account.Info accountOne; Account.Info accountTwo; uint256 market; } struct BuyArgs { Types.AssetAmount amount; Account.Info account; uint256 makerMarket; uint256 takerMarket; address exchangeWrapper; bytes orderData; } struct SellArgs { Types.AssetAmount amount; Account.Info account; uint256 takerMarket; uint256 makerMarket; address exchangeWrapper; bytes orderData; } struct TradeArgs { Types.AssetAmount amount; Account.Info takerAccount; Account.Info makerAccount; uint256 inputMarket; uint256 outputMarket; address autoTrader; bytes tradeData; } struct LiquidateArgs { Types.AssetAmount amount; Account.Info solidAccount; Account.Info liquidAccount; uint256 owedMarket; uint256 heldMarket; } struct VaporizeArgs { Types.AssetAmount amount; Account.Info solidAccount; Account.Info vaporAccount; uint256 owedMarket; uint256 heldMarket; } struct CallArgs { Account.Info account; address callee; bytes data; } } // Part: IAaveIncentivesController interface IAaveIncentivesController { /** * @dev Returns the total of rewards of an user, already accrued + not yet accrued * @param user The address of the user * @return The rewards **/ function getRewardsBalance(address[] calldata assets, address user) external view returns (uint256); /** * @dev Claims reward for an user, on all the assets of the lending pool, accumulating the pending rewards * @param amount Amount of rewards to claim * @param to Address that will be receiving the rewards * @return Rewards claimed **/ function claimRewards( address[] calldata assets, uint256 amount, address to ) external returns (uint256); /** * @dev Claims reward for an user on behalf, on all the assets of the lending pool, accumulating the pending rewards. The caller must * be whitelisted via "allowClaimOnBehalf" function by the RewardsAdmin role manager * @param amount Amount of rewards to claim * @param user Address to check and claim rewards * @param to Address that will be receiving the rewards * @return Rewards claimed **/ function claimRewardsOnBehalf( address[] calldata assets, uint256 amount, address user, address to ) external returns (uint256); /** * @dev returns the unclaimed rewards of the user * @param user the address of the user * @return the unclaimed user rewards */ function getUserUnclaimedRewards(address user) external view returns (uint256); /** * @dev for backward compatibility with previous implementation of the Incentives controller */ function REWARD_TOKEN() external view returns (address); function getDistributionEnd() external view returns (uint256); function getAssetData(address asset) external view returns ( uint256, uint256, uint256 ); } // Part: ICallee /** * @title ICallee * @author dYdX * * Interface that Callees for Solo must implement in order to ingest data. */ interface ICallee { // ============ Public Functions ============ /** * Allows users to send this contract arbitrary data. * * @param sender The msg.sender to Solo * @param accountInfo The account from which the data is being sent * @param data Arbitrary data given by the sender */ function callFunction( address sender, Account.Info memory accountInfo, bytes memory data ) external; } // Part: ILendingPoolAddressesProvider /** * @title LendingPoolAddressesProvider contract * @dev Main registry of addresses part of or connected to the protocol, including permissioned roles * - Acting also as factory of proxies and admin of those, so with right to change its implementations * - Owned by the Aave Governance * @author Aave **/ interface ILendingPoolAddressesProvider { event MarketIdSet(string newMarketId); event LendingPoolUpdated(address indexed newAddress); event ConfigurationAdminUpdated(address indexed newAddress); event EmergencyAdminUpdated(address indexed newAddress); event LendingPoolConfiguratorUpdated(address indexed newAddress); event LendingPoolCollateralManagerUpdated(address indexed newAddress); event PriceOracleUpdated(address indexed newAddress); event LendingRateOracleUpdated(address indexed newAddress); event ProxyCreated(bytes32 id, address indexed newAddress); event AddressSet(bytes32 id, address indexed newAddress, bool hasProxy); function getMarketId() external view returns (string memory); function setMarketId(string calldata marketId) external; function setAddress(bytes32 id, address newAddress) external; function setAddressAsProxy(bytes32 id, address impl) external; function getAddress(bytes32 id) external view returns (address); function getLendingPool() external view returns (address); function setLendingPoolImpl(address pool) external; function getLendingPoolConfigurator() external view returns (address); function setLendingPoolConfiguratorImpl(address configurator) external; function getLendingPoolCollateralManager() external view returns (address); function setLendingPoolCollateralManager(address manager) external; function getPoolAdmin() external view returns (address); function setPoolAdmin(address admin) external; function getEmergencyAdmin() external view returns (address); function setEmergencyAdmin(address admin) external; function getPriceOracle() external view returns (address); function setPriceOracle(address priceOracle) external; function getLendingRateOracle() external view returns (address); function setLendingRateOracle(address lendingRateOracle) external; } // Part: IOptionalERC20 interface IOptionalERC20 { function decimals() external view returns (uint8); } // Part: IPriceOracle interface IPriceOracle { function getAssetPrice(address _asset) external view returns (uint256); function getAssetsPrices(address[] calldata _assets) external view returns (uint256[] memory); function getSourceOfAsset(address _asset) external view returns (address); function getFallbackOracle() external view returns (address); } // Part: IScaledBalanceToken interface IScaledBalanceToken { /** * @dev Returns the scaled balance of the user. The scaled balance is the sum of all the * updated stored balance divided by the reserve's liquidity index at the moment of the update * @param user The user whose balance is calculated * @return The scaled balance of the user **/ function scaledBalanceOf(address user) external view returns (uint256); /** * @dev Returns the scaled balance of the user and the scaled total supply. * @param user The address of the user * @return The scaled balance of the user * @return The scaled balance and the scaled total supply **/ function getScaledUserBalanceAndSupply(address user) external view returns (uint256, uint256); /** * @dev Returns the scaled total supply of the variable debt token. Represents sum(debt/index) * @return The scaled total supply **/ function scaledTotalSupply() external view returns (uint256); } // Part: ISoloMargin library Decimal { struct D256 { uint256 value; } } library Interest { struct Rate { uint256 value; } struct Index { uint96 borrow; uint96 supply; uint32 lastUpdate; } } library Monetary { struct Price { uint256 value; } struct Value { uint256 value; } } library Storage { // All information necessary for tracking a market struct Market { // Contract address of the associated ERC20 token address token; // Total aggregated supply and borrow amount of the entire market Types.TotalPar totalPar; // Interest index of the market Interest.Index index; // Contract address of the price oracle for this market address priceOracle; // Contract address of the interest setter for this market address interestSetter; // Multiplier on the marginRatio for this market Decimal.D256 marginPremium; // Multiplier on the liquidationSpread for this market Decimal.D256 spreadPremium; // Whether additional borrows are allowed for this market bool isClosing; } // The global risk parameters that govern the health and security of the system struct RiskParams { // Required ratio of over-collateralization Decimal.D256 marginRatio; // Percentage penalty incurred by liquidated accounts Decimal.D256 liquidationSpread; // Percentage of the borrower's interest fee that gets passed to the suppliers Decimal.D256 earningsRate; // The minimum absolute borrow value of an account // There must be sufficient incentivize to liquidate undercollateralized accounts Monetary.Value minBorrowedValue; } // The maximum RiskParam values that can be set struct RiskLimits { uint64 marginRatioMax; uint64 liquidationSpreadMax; uint64 earningsRateMax; uint64 marginPremiumMax; uint64 spreadPremiumMax; uint128 minBorrowedValueMax; } // The entire storage state of Solo struct State { // number of markets uint256 numMarkets; // marketId => Market mapping(uint256 => Market) markets; // owner => account number => Account mapping(address => mapping(uint256 => Account.Storage)) accounts; // Addresses that can control other users accounts mapping(address => mapping(address => bool)) operators; // Addresses that can control all users accounts mapping(address => bool) globalOperators; // mutable risk parameters of the system RiskParams riskParams; // immutable risk limits of the system RiskLimits riskLimits; } } interface ISoloMargin { struct OperatorArg { address operator1; bool trusted; } function ownerSetSpreadPremium( uint256 marketId, Decimal.D256 memory spreadPremium ) external; function getIsGlobalOperator(address operator1) external view returns (bool); function getMarketTokenAddress(uint256 marketId) external view returns (address); function ownerSetInterestSetter(uint256 marketId, address interestSetter) external; function getAccountValues(Account.Info memory account) external view returns (Monetary.Value memory, Monetary.Value memory); function getMarketPriceOracle(uint256 marketId) external view returns (address); function getMarketInterestSetter(uint256 marketId) external view returns (address); function getMarketSpreadPremium(uint256 marketId) external view returns (Decimal.D256 memory); function getNumMarkets() external view returns (uint256); function ownerWithdrawUnsupportedTokens(address token, address recipient) external returns (uint256); function ownerSetMinBorrowedValue(Monetary.Value memory minBorrowedValue) external; function ownerSetLiquidationSpread(Decimal.D256 memory spread) external; function ownerSetEarningsRate(Decimal.D256 memory earningsRate) external; function getIsLocalOperator(address owner, address operator1) external view returns (bool); function getAccountPar(Account.Info memory account, uint256 marketId) external view returns (Types.Par memory); function ownerSetMarginPremium( uint256 marketId, Decimal.D256 memory marginPremium ) external; function getMarginRatio() external view returns (Decimal.D256 memory); function getMarketCurrentIndex(uint256 marketId) external view returns (Interest.Index memory); function getMarketIsClosing(uint256 marketId) external view returns (bool); function getRiskParams() external view returns (Storage.RiskParams memory); function getAccountBalances(Account.Info memory account) external view returns ( address[] memory, Types.Par[] memory, Types.Wei[] memory ); function renounceOwnership() external; function getMinBorrowedValue() external view returns (Monetary.Value memory); function setOperators(OperatorArg[] memory args) external; function getMarketPrice(uint256 marketId) external view returns (address); function owner() external view returns (address); function isOwner() external view returns (bool); function ownerWithdrawExcessTokens(uint256 marketId, address recipient) external returns (uint256); function ownerAddMarket( address token, address priceOracle, address interestSetter, Decimal.D256 memory marginPremium, Decimal.D256 memory spreadPremium ) external; function operate( Account.Info[] memory accounts, Actions.ActionArgs[] memory actions ) external; function getMarketWithInfo(uint256 marketId) external view returns ( Storage.Market memory, Interest.Index memory, Monetary.Price memory, Interest.Rate memory ); function ownerSetMarginRatio(Decimal.D256 memory ratio) external; function getLiquidationSpread() external view returns (Decimal.D256 memory); function getAccountWei(Account.Info memory account, uint256 marketId) external view returns (Types.Wei memory); function getMarketTotalPar(uint256 marketId) external view returns (Types.TotalPar memory); function getLiquidationSpreadForPair( uint256 heldMarketId, uint256 owedMarketId ) external view returns (Decimal.D256 memory); function getNumExcessTokens(uint256 marketId) external view returns (Types.Wei memory); function getMarketCachedIndex(uint256 marketId) external view returns (Interest.Index memory); function getAccountStatus(Account.Info memory account) external view returns (uint8); function getEarningsRate() external view returns (Decimal.D256 memory); function ownerSetPriceOracle(uint256 marketId, address priceOracle) external; function getRiskLimits() external view returns (Storage.RiskLimits memory); function getMarket(uint256 marketId) external view returns (Storage.Market memory); function ownerSetIsClosing(uint256 marketId, bool isClosing) external; function ownerSetGlobalOperator(address operator1, bool approved) external; function transferOwnership(address newOwner) external; function getAdjustedAccountValues(Account.Info memory account) external view returns (Monetary.Value memory, Monetary.Value memory); function getMarketMarginPremium(uint256 marketId) external view returns (Decimal.D256 memory); function getMarketInterestRate(uint256 marketId) external view returns (Interest.Rate memory); } // Part: IStakedAave interface IStakedAave { function stake(address to, uint256 amount) external; function redeem(address to, uint256 amount) external; function cooldown() external; function claimRewards(address to, uint256 amount) external; function getTotalRewardsBalance(address) external view returns (uint256); function COOLDOWN_SECONDS() external view returns (uint256); function stakersCooldowns(address) external view returns (uint256); function UNSTAKE_WINDOW() external view returns (uint256); } // Part: IUni interface IUni{ function getAmountsOut( uint256 amountIn, address[] calldata path ) external view returns (uint256[] memory amounts); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); } // Part: IUniswapV3SwapCallback /// @title Callback for IUniswapV3PoolActions#swap /// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface interface IUniswapV3SwapCallback { /// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap. /// @dev In the implementation you must pay the pool tokens owed for the swap. /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory. /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped. /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token0 to the pool. /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token1 to the pool. /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call function uniswapV3SwapCallback( int256 amount0Delta, int256 amount1Delta, bytes calldata data ) external; } // Part: OpenZeppelin/[email protected]/Address /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // 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"); } /** * @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); } } } } // Part: OpenZeppelin/[email protected]/IERC20 /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // Part: OpenZeppelin/[email protected]/Math /** * @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); } } // Part: OpenZeppelin/[email protected]/SafeMath /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, 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; } } // Part: Types library Types { enum AssetDenomination { Wei, // the amount is denominated in wei Par // the amount is denominated in par } enum AssetReference { Delta, // the amount is given as a delta from the current value Target // the amount is given as an exact number to end up at } struct AssetAmount { bool sign; // true if positive AssetDenomination denomination; AssetReference ref; uint256 value; } struct TotalPar { uint128 borrow; uint128 supply; } struct Par { bool sign; // true if positive uint128 value; } struct Wei { bool sign; // true if positive uint256 value; } } // Part: yearn/[email protected]/HealthCheck interface HealthCheck { function check( uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding, uint256 totalDebt ) external view returns (bool); } // Part: ILendingPool library DataTypes { // refer to the whitepaper, section 1.1 basic concepts for a formal description of these properties. struct ReserveData { //stores the reserve configuration ReserveConfigurationMap configuration; //the liquidity index. Expressed in ray uint128 liquidityIndex; //variable borrow index. Expressed in ray uint128 variableBorrowIndex; //the current supply rate. Expressed in ray uint128 currentLiquidityRate; //the current variable borrow rate. Expressed in ray uint128 currentVariableBorrowRate; //the current stable borrow rate. Expressed in ray uint128 currentStableBorrowRate; uint40 lastUpdateTimestamp; //tokens addresses address aTokenAddress; address stableDebtTokenAddress; address variableDebtTokenAddress; //address of the interest rate strategy address interestRateStrategyAddress; //the id of the reserve. Represents the position in the list of the active reserves uint8 id; } struct ReserveConfigurationMap { //bit 0-15: LTV //bit 16-31: Liq. threshold //bit 32-47: Liq. bonus //bit 48-55: Decimals //bit 56: Reserve is active //bit 57: reserve is frozen //bit 58: borrowing is enabled //bit 59: stable rate borrowing enabled //bit 60-63: reserved //bit 64-79: reserve factor uint256 data; } struct UserConfigurationMap { uint256 data; } enum InterestRateMode {NONE, STABLE, VARIABLE} } interface ILendingPool { /** * @dev Emitted on deposit() * @param reserve The address of the underlying asset of the reserve * @param user The address initiating the deposit * @param onBehalfOf The beneficiary of the deposit, receiving the aTokens * @param amount The amount deposited * @param referral The referral code used **/ event Deposit( address indexed reserve, address user, address indexed onBehalfOf, uint256 amount, uint16 indexed referral ); /** * @dev Emitted on withdraw() * @param reserve The address of the underlyng asset being withdrawn * @param user The address initiating the withdrawal, owner of aTokens * @param to Address that will receive the underlying * @param amount The amount to be withdrawn **/ event Withdraw( address indexed reserve, address indexed user, address indexed to, uint256 amount ); /** * @dev Emitted on borrow() and flashLoan() when debt needs to be opened * @param reserve The address of the underlying asset being borrowed * @param user The address of the user initiating the borrow(), receiving the funds on borrow() or just * initiator of the transaction on flashLoan() * @param onBehalfOf The address that will be getting the debt * @param amount The amount borrowed out * @param borrowRateMode The rate mode: 1 for Stable, 2 for Variable * @param borrowRate The numeric rate at which the user has borrowed * @param referral The referral code used **/ event Borrow( address indexed reserve, address user, address indexed onBehalfOf, uint256 amount, uint256 borrowRateMode, uint256 borrowRate, uint16 indexed referral ); /** * @dev Emitted on repay() * @param reserve The address of the underlying asset of the reserve * @param user The beneficiary of the repayment, getting his debt reduced * @param repayer The address of the user initiating the repay(), providing the funds * @param amount The amount repaid **/ event Repay( address indexed reserve, address indexed user, address indexed repayer, uint256 amount ); /** * @dev Emitted on swapBorrowRateMode() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user swapping his rate mode * @param rateMode The rate mode that the user wants to swap to **/ event Swap(address indexed reserve, address indexed user, uint256 rateMode); /** * @dev Emitted on setUserUseReserveAsCollateral() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user enabling the usage as collateral **/ event ReserveUsedAsCollateralEnabled( address indexed reserve, address indexed user ); /** * @dev Emitted on setUserUseReserveAsCollateral() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user enabling the usage as collateral **/ event ReserveUsedAsCollateralDisabled( address indexed reserve, address indexed user ); /** * @dev Emitted on rebalanceStableBorrowRate() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user for which the rebalance has been executed **/ event RebalanceStableBorrowRate( address indexed reserve, address indexed user ); /** * @dev Emitted on flashLoan() * @param target The address of the flash loan receiver contract * @param initiator The address initiating the flash loan * @param asset The address of the asset being flash borrowed * @param amount The amount flash borrowed * @param premium The fee flash borrowed * @param referralCode The referral code used **/ event FlashLoan( address indexed target, address indexed initiator, address indexed asset, uint256 amount, uint256 premium, uint16 referralCode ); /** * @dev Emitted when the pause is triggered. */ event Paused(); /** * @dev Emitted when the pause is lifted. */ event Unpaused(); /** * @dev Emitted when a borrower is liquidated. This event is emitted by the LendingPool via * LendingPoolCollateral manager using a DELEGATECALL * This allows to have the events in the generated ABI for LendingPool. * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param user The address of the borrower getting liquidated * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param liquidatedCollateralAmount The amount of collateral received by the liiquidator * @param liquidator The address of the liquidator * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants * to receive the underlying collateral asset directly **/ event LiquidationCall( address indexed collateralAsset, address indexed debtAsset, address indexed user, uint256 debtToCover, uint256 liquidatedCollateralAmount, address liquidator, bool receiveAToken ); /** * @dev Emitted when the state of a reserve is updated. NOTE: This event is actually declared * in the ReserveLogic library and emitted in the updateInterestRates() function. Since the function is internal, * the event will actually be fired by the LendingPool contract. The event is therefore replicated here so it * gets added to the LendingPool ABI * @param reserve The address of the underlying asset of the reserve * @param liquidityRate The new liquidity rate * @param stableBorrowRate The new stable borrow rate * @param variableBorrowRate The new variable borrow rate * @param liquidityIndex The new liquidity index * @param variableBorrowIndex The new variable borrow index **/ event ReserveDataUpdated( address indexed reserve, uint256 liquidityRate, uint256 stableBorrowRate, uint256 variableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex ); /** * @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens. * - E.g. User deposits 100 USDC and gets in return 100 aUSDC * @param asset The address of the underlying asset to deposit * @param amount The amount to be deposited * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens * is a different wallet * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function deposit( address asset, uint256 amount, address onBehalfOf, uint16 referralCode ) external; /** * @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC * @param asset The address of the underlying asset to withdraw * @param amount The underlying amount to be withdrawn * - Send the value type(uint256).max in order to withdraw the whole aToken balance * @param to Address that will receive the underlying, same as msg.sender if the user * wants to receive it on his own wallet, or a different address if the beneficiary is a * different wallet * @return The final amount withdrawn **/ function withdraw( address asset, uint256 amount, address to ) external returns (uint256); /** * @dev Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower * already deposited enough collateral, or he was given enough allowance by a credit delegator on the * corresponding debt token (StableDebtToken or VariableDebtToken) * - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet * and 100 stable/variable debt tokens, depending on the `interestRateMode` * @param asset The address of the underlying asset to borrow * @param amount The amount to be borrowed * @param interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man * @param onBehalfOf Address of the user who will receive the debt. Should be the address of the borrower itself * calling the function if he wants to borrow against his own collateral, or the address of the credit delegator * if he has been given credit delegation allowance **/ function borrow( address asset, uint256 amount, uint256 interestRateMode, uint16 referralCode, address onBehalfOf ) external; /** * @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned * - E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address * @param asset The address of the borrowed underlying asset previously borrowed * @param amount The amount to repay * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode` * @param rateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable * @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the * user calling the function if he wants to reduce/remove his own debt, or the address of any other * other borrower whose debt should be removed * @return The final amount repaid **/ function repay( address asset, uint256 amount, uint256 rateMode, address onBehalfOf ) external returns (uint256); /** * @dev Allows a borrower to swap his debt between stable and variable mode, or viceversa * @param asset The address of the underlying asset borrowed * @param rateMode The rate mode that the user wants to swap to **/ function swapBorrowRateMode(address asset, uint256 rateMode) external; /** * @dev Rebalances the stable interest rate of a user to the current stable rate defined on the reserve. * - Users can be rebalanced if the following conditions are satisfied: * 1. Usage ratio is above 95% * 2. the current deposit APY is below REBALANCE_UP_THRESHOLD * maxVariableBorrowRate, which means that too much has been * borrowed at a stable rate and depositors are not earning enough * @param asset The address of the underlying asset borrowed * @param user The address of the user to be rebalanced **/ function rebalanceStableBorrowRate(address asset, address user) external; /** * @dev Allows depositors to enable/disable a specific deposited asset as collateral * @param asset The address of the underlying asset deposited * @param useAsCollateral `true` if the user wants to use the deposit as collateral, `false` otherwise **/ function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external; /** * @dev Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1 * - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives * a proportionally amount of the `collateralAsset` plus a bonus to cover market risk * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param user The address of the borrower getting liquidated * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants * to receive the underlying collateral asset directly **/ function liquidationCall( address collateralAsset, address debtAsset, address user, uint256 debtToCover, bool receiveAToken ) external; /** * @dev Allows smartcontracts to access the liquidity of the pool within one transaction, * as long as the amount taken plus a fee is returned. * IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept into consideration. * For further details please visit https://developers.aave.com * @param receiverAddress The address of the contract receiving the funds, implementing the IFlashLoanReceiver interface * @param assets The addresses of the assets being flash-borrowed * @param amounts The amounts amounts being flash-borrowed * @param modes Types of the debt to open if the flash loan is not returned: * 0 -> Don't open any debt, just revert if funds can't be transferred from the receiver * 1 -> Open debt at stable rate for the value of the amount flash-borrowed to the `onBehalfOf` address * 2 -> Open debt at variable rate for the value of the amount flash-borrowed to the `onBehalfOf` address * @param onBehalfOf The address that will receive the debt in the case of using on `modes` 1 or 2 * @param params Variadic packed params to pass to the receiver as extra information * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function flashLoan( address receiverAddress, address[] calldata assets, uint256[] calldata amounts, uint256[] calldata modes, address onBehalfOf, bytes calldata params, uint16 referralCode ) external; /** * @dev Returns the user account data across all the reserves * @param user The address of the user * @return totalCollateralETH the total collateral in ETH of the user * @return totalDebtETH the total debt in ETH of the user * @return availableBorrowsETH the borrowing power left of the user * @return currentLiquidationThreshold the liquidation threshold of the user * @return ltv the loan to value of the user * @return healthFactor the current health factor of the user **/ function getUserAccountData(address user) external view returns ( uint256 totalCollateralETH, uint256 totalDebtETH, uint256 availableBorrowsETH, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor ); function initReserve( address reserve, address aTokenAddress, address stableDebtAddress, address variableDebtAddress, address interestRateStrategyAddress ) external; function setReserveInterestRateStrategyAddress( address reserve, address rateStrategyAddress ) external; function setConfiguration(address reserve, uint256 configuration) external; /** * @dev Returns the configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The configuration of the reserve **/ function getConfiguration(address asset) external view returns (DataTypes.ReserveConfigurationMap memory); /** * @dev Returns the configuration of the user across all the reserves * @param user The user address * @return The configuration of the user **/ function getUserConfiguration(address user) external view returns (DataTypes.UserConfigurationMap memory); /** * @dev Returns the normalized income normalized income of the reserve * @param asset The address of the underlying asset of the reserve * @return The reserve's normalized income */ function getReserveNormalizedIncome(address asset) external view returns (uint256); /** * @dev Returns the normalized variable debt per unit of asset * @param asset The address of the underlying asset of the reserve * @return The reserve normalized variable debt */ function getReserveNormalizedVariableDebt(address asset) external view returns (uint256); /** * @dev Returns the state and configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The state of the reserve **/ function getReserveData(address asset) external view returns (DataTypes.ReserveData memory); function finalizeTransfer( address asset, address from, address to, uint256 amount, uint256 balanceFromAfter, uint256 balanceToBefore ) external; function getReservesList() external view returns (address[] memory); function getAddressesProvider() external view returns (ILendingPoolAddressesProvider); function setPause(bool val) external; function paused() external view returns (bool); } // Part: IProtocolDataProvider interface IProtocolDataProvider { struct TokenData { string symbol; address tokenAddress; } function ADDRESSES_PROVIDER() external view returns (ILendingPoolAddressesProvider); function getAllReservesTokens() external view returns (TokenData[] memory); function getAllATokens() external view returns (TokenData[] memory); function getReserveConfigurationData(address asset) external view returns ( uint256 decimals, uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus, uint256 reserveFactor, bool usageAsCollateralEnabled, bool borrowingEnabled, bool stableBorrowRateEnabled, bool isActive, bool isFrozen ); function getReserveData(address asset) external view returns ( uint256 availableLiquidity, uint256 totalStableDebt, uint256 totalVariableDebt, uint256 liquidityRate, uint256 variableBorrowRate, uint256 stableBorrowRate, uint256 averageStableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex, uint40 lastUpdateTimestamp ); function getUserReserveData(address asset, address user) external view returns ( uint256 currentATokenBalance, uint256 currentStableDebt, uint256 currentVariableDebt, uint256 principalStableDebt, uint256 scaledVariableDebt, uint256 stableBorrowRate, uint256 liquidityRate, uint40 stableRateLastUpdated, bool usageAsCollateralEnabled ); function getReserveTokensAddresses(address asset) external view returns ( address aTokenAddress, address stableDebtTokenAddress, address variableDebtTokenAddress ); } // Part: ISwapRouter /// @title Router token swapping functionality /// @notice Functions for swapping tokens via Uniswap V3 interface ISwapRouter is IUniswapV3SwapCallback { struct ExactInputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; uint160 sqrtPriceLimitX96; } /// @notice Swaps `amountIn` of one token for as much as possible of another token /// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata /// @return amountOut The amount of the received token function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut); struct ExactInputParams { bytes path; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; } /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata /// @return amountOut The amount of the received token function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut); struct ExactOutputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; uint160 sqrtPriceLimitX96; } /// @notice Swaps as little as possible of one token for `amountOut` of another token /// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata /// @return amountIn The amount of the input token function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn); struct ExactOutputParams { bytes path; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; } /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed) /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata /// @return amountIn The amount of the input token function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn); } // Part: IVariableDebtToken /** * @title IVariableDebtToken * @author Aave * @notice Defines the basic interface for a variable debt token. **/ interface IVariableDebtToken is IERC20, IScaledBalanceToken { /** * @dev Emitted after the mint action * @param from The address performing the mint * @param onBehalfOf The address of the user on which behalf minting has been performed * @param value The amount to be minted * @param index The last index of the reserve **/ event Mint( address indexed from, address indexed onBehalfOf, uint256 value, uint256 index ); /** * @dev Mints debt token to the `onBehalfOf` address * @param user The address receiving the borrowed underlying, being the delegatee in case * of credit delegate, or same as `onBehalfOf` otherwise * @param onBehalfOf The address receiving the debt tokens * @param amount The amount of debt being minted * @param index The variable debt index of the reserve * @return `true` if the the previous balance of the user is 0 **/ function mint( address user, address onBehalfOf, uint256 amount, uint256 index ) external returns (bool); /** * @dev Emitted when variable debt is burnt * @param user The user which debt has been burned * @param amount The amount of debt being burned * @param index The index of the user **/ event Burn(address indexed user, uint256 amount, uint256 index); /** * @dev Burns user variable debt * @param user The user which debt is burnt * @param index The variable debt index of the reserve **/ function burn( address user, uint256 amount, uint256 index ) external; /** * @dev Returns the address of the incentives controller contract **/ function getIncentivesController() external view returns (IAaveIncentivesController); } // Part: OpenZeppelin/[email protected]/SafeERC20 /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // Part: yearn/[email protected]/VaultAPI interface VaultAPI is IERC20 { function name() external view returns (string calldata); function symbol() external view returns (string calldata); function decimals() external view returns (uint256); function apiVersion() external pure returns (string memory); function permit( address owner, address spender, uint256 amount, uint256 expiry, bytes calldata signature ) external returns (bool); // NOTE: Vyper produces multiple signatures for a given function with "default" args function deposit() external returns (uint256); function deposit(uint256 amount) external returns (uint256); function deposit(uint256 amount, address recipient) external returns (uint256); // NOTE: Vyper produces multiple signatures for a given function with "default" args function withdraw() external returns (uint256); function withdraw(uint256 maxShares) external returns (uint256); function withdraw(uint256 maxShares, address recipient) external returns (uint256); function token() external view returns (address); function strategies(address _strategy) external view returns (StrategyParams memory); function pricePerShare() external view returns (uint256); function totalAssets() external view returns (uint256); function depositLimit() external view returns (uint256); function maxAvailableShares() external view returns (uint256); /** * View how much the Vault would increase this Strategy's borrow limit, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function creditAvailable() external view returns (uint256); /** * View how much the Vault would like to pull back from the Strategy, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function debtOutstanding() external view returns (uint256); /** * View how much the Vault expect this Strategy to return at the current * block, based on its present performance (since its last report). Can be * used to determine expectedReturn in your Strategy. */ function expectedReturn() external view returns (uint256); /** * This is the main contact point where the Strategy interacts with the * Vault. It is critical that this call is handled as intended by the * Strategy. Therefore, this function will be called by BaseStrategy to * make sure the integration is correct. */ function report( uint256 _gain, uint256 _loss, uint256 _debtPayment ) external returns (uint256); /** * This function should only be used in the scenario where the Strategy is * being retired but no migration of the positions are possible, or in the * extreme scenario that the Strategy needs to be put into "Emergency Exit" * mode in order for it to exit as quickly as possible. The latter scenario * could be for any reason that is considered "critical" that the Strategy * exits its position as fast as possible, such as a sudden change in * market conditions leading to losses, or an imminent failure in an * external dependency. */ function revokeStrategy() external; /** * View the governance address of the Vault to assert privileged functions * can only be called by governance. The Strategy serves the Vault, so it * is subject to governance defined by the Vault. */ function governance() external view returns (address); /** * View the management address of the Vault to assert privileged functions * can only be called by management. The Strategy serves the Vault, so it * is subject to management defined by the Vault. */ function management() external view returns (address); /** * View the guardian address of the Vault to assert privileged functions * can only be called by guardian. The Strategy serves the Vault, so it * is subject to guardian defined by the Vault. */ function guardian() external view returns (address); } // Part: IInitializableAToken /** * @title IInitializableAToken * @notice Interface for the initialize function on AToken * @author Aave **/ interface IInitializableAToken { /** * @dev Emitted when an aToken is initialized * @param underlyingAsset The address of the underlying asset * @param pool The address of the associated lending pool * @param treasury The address of the treasury * @param incentivesController The address of the incentives controller for this aToken * @param aTokenDecimals the decimals of the underlying * @param aTokenName the name of the aToken * @param aTokenSymbol the symbol of the aToken * @param params A set of encoded parameters for additional initialization **/ event Initialized( address indexed underlyingAsset, address indexed pool, address treasury, address incentivesController, uint8 aTokenDecimals, string aTokenName, string aTokenSymbol, bytes params ); /** * @dev Initializes the aToken * @param pool The address of the lending pool where this aToken will be used * @param treasury The address of the Aave treasury, receiving the fees on this aToken * @param underlyingAsset The address of the underlying asset of this aToken (E.g. WETH for aWETH) * @param incentivesController The smart contract managing potential incentives distribution * @param aTokenDecimals The decimals of the aToken, same as the underlying asset's * @param aTokenName The name of the aToken * @param aTokenSymbol The symbol of the aToken */ function initialize( ILendingPool pool, address treasury, address underlyingAsset, IAaveIncentivesController incentivesController, uint8 aTokenDecimals, string calldata aTokenName, string calldata aTokenSymbol, bytes calldata params ) external; } // Part: yearn/[email protected]/BaseStrategy /** * @title Yearn Base Strategy * @author yearn.finance * @notice * BaseStrategy implements all of the required functionality to interoperate * closely with the Vault contract. This contract should be inherited and the * abstract methods implemented to adapt the Strategy to the particular needs * it has to create a return. * * Of special interest is the relationship between `harvest()` and * `vault.report()'. `harvest()` may be called simply because enough time has * elapsed since the last report, and not because any funds need to be moved * or positions adjusted. This is critical so that the Vault may maintain an * accurate picture of the Strategy's performance. See `vault.report()`, * `harvest()`, and `harvestTrigger()` for further details. */ abstract contract BaseStrategy { using SafeMath for uint256; using SafeERC20 for IERC20; string public metadataURI; // health checks bool public doHealthCheck; address public healthCheck; /** * @notice * Used to track which version of `StrategyAPI` this Strategy * implements. * @dev The Strategy's version must match the Vault's `API_VERSION`. * @return A string which holds the current API version of this contract. */ function apiVersion() public pure returns (string memory) { return "0.4.3"; } /** * @notice This Strategy's name. * @dev * You can use this field to manage the "version" of this Strategy, e.g. * `StrategySomethingOrOtherV1`. However, "API Version" is managed by * `apiVersion()` function above. * @return This Strategy's name. */ function name() external view virtual returns (string memory); /** * @notice * The amount (priced in want) of the total assets managed by this strategy should not count * towards Yearn's TVL calculations. * @dev * You can override this field to set it to a non-zero value if some of the assets of this * Strategy is somehow delegated inside another part of of Yearn's ecosystem e.g. another Vault. * Note that this value must be strictly less than or equal to the amount provided by * `estimatedTotalAssets()` below, as the TVL calc will be total assets minus delegated assets. * Also note that this value is used to determine the total assets under management by this * strategy, for the purposes of computing the management fee in `Vault` * @return * The amount of assets this strategy manages that should not be included in Yearn's Total Value * Locked (TVL) calculation across it's ecosystem. */ function delegatedAssets() external view virtual returns (uint256) { return 0; } VaultAPI public vault; address public strategist; address public rewards; address public keeper; IERC20 public want; // So indexers can keep track of this event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding); event UpdatedStrategist(address newStrategist); event UpdatedKeeper(address newKeeper); event UpdatedRewards(address rewards); event UpdatedMinReportDelay(uint256 delay); event UpdatedMaxReportDelay(uint256 delay); event UpdatedProfitFactor(uint256 profitFactor); event UpdatedDebtThreshold(uint256 debtThreshold); event EmergencyExitEnabled(); event UpdatedMetadataURI(string metadataURI); // The minimum number of seconds between harvest calls. See // `setMinReportDelay()` for more details. uint256 public minReportDelay; // The maximum number of seconds between harvest calls. See // `setMaxReportDelay()` for more details. uint256 public maxReportDelay; // The minimum multiple that `callCost` must be above the credit/profit to // be "justifiable". See `setProfitFactor()` for more details. uint256 public profitFactor; // Use this to adjust the threshold at which running a debt causes a // harvest trigger. See `setDebtThreshold()` for more details. uint256 public debtThreshold; // See note on `setEmergencyExit()`. bool public emergencyExit; // modifiers modifier onlyAuthorized() { require(msg.sender == strategist || msg.sender == governance(), "!authorized"); _; } modifier onlyEmergencyAuthorized() { require( msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management(), "!authorized" ); _; } modifier onlyStrategist() { require(msg.sender == strategist, "!strategist"); _; } modifier onlyGovernance() { require(msg.sender == governance(), "!authorized"); _; } modifier onlyKeepers() { require( msg.sender == keeper || msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management(), "!authorized" ); _; } modifier onlyVaultManagers() { require(msg.sender == vault.management() || msg.sender == governance(), "!authorized"); _; } constructor(address _vault) public { _initialize(_vault, msg.sender, msg.sender, msg.sender); } /** * @notice * Initializes the Strategy, this is called only once, when the * contract is deployed. * @dev `_vault` should implement `VaultAPI`. * @param _vault The address of the Vault responsible for this Strategy. * @param _strategist The address to assign as `strategist`. * The strategist is able to change the reward address * @param _rewards The address to use for pulling rewards. * @param _keeper The adddress of the _keeper. _keeper * can harvest and tend a strategy. */ function _initialize( address _vault, address _strategist, address _rewards, address _keeper ) internal { require(address(want) == address(0), "Strategy already initialized"); vault = VaultAPI(_vault); want = IERC20(vault.token()); want.safeApprove(_vault, uint256(-1)); // Give Vault unlimited access (might save gas) strategist = _strategist; rewards = _rewards; keeper = _keeper; // initialize variables minReportDelay = 0; maxReportDelay = 86400; profitFactor = 100; debtThreshold = 0; vault.approve(rewards, uint256(-1)); // Allow rewards to be pulled } function setHealthCheck(address _healthCheck) external onlyVaultManagers { healthCheck = _healthCheck; } function setDoHealthCheck(bool _doHealthCheck) external onlyVaultManagers { doHealthCheck = _doHealthCheck; } /** * @notice * Used to change `strategist`. * * This may only be called by governance or the existing strategist. * @param _strategist The new address to assign as `strategist`. */ function setStrategist(address _strategist) external onlyAuthorized { require(_strategist != address(0)); strategist = _strategist; emit UpdatedStrategist(_strategist); } /** * @notice * Used to change `keeper`. * * `keeper` is the only address that may call `tend()` or `harvest()`, * other than `governance()` or `strategist`. However, unlike * `governance()` or `strategist`, `keeper` may *only* call `tend()` * and `harvest()`, and no other authorized functions, following the * principle of least privilege. * * This may only be called by governance or the strategist. * @param _keeper The new address to assign as `keeper`. */ function setKeeper(address _keeper) external onlyAuthorized { require(_keeper != address(0)); keeper = _keeper; emit UpdatedKeeper(_keeper); } /** * @notice * Used to change `rewards`. EOA or smart contract which has the permission * to pull rewards from the vault. * * This may only be called by the strategist. * @param _rewards The address to use for pulling rewards. */ function setRewards(address _rewards) external onlyStrategist { require(_rewards != address(0)); vault.approve(rewards, 0); rewards = _rewards; vault.approve(rewards, uint256(-1)); emit UpdatedRewards(_rewards); } /** * @notice * Used to change `minReportDelay`. `minReportDelay` is the minimum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the minimum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _delay The minimum number of seconds to wait between harvests. */ function setMinReportDelay(uint256 _delay) external onlyAuthorized { minReportDelay = _delay; emit UpdatedMinReportDelay(_delay); } /** * @notice * Used to change `maxReportDelay`. `maxReportDelay` is the maximum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the maximum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _delay The maximum number of seconds to wait between harvests. */ function setMaxReportDelay(uint256 _delay) external onlyAuthorized { maxReportDelay = _delay; emit UpdatedMaxReportDelay(_delay); } /** * @notice * Used to change `profitFactor`. `profitFactor` is used to determine * if it's worthwhile to harvest, given gas costs. (See `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _profitFactor A ratio to multiply anticipated * `harvest()` gas cost against. */ function setProfitFactor(uint256 _profitFactor) external onlyAuthorized { profitFactor = _profitFactor; emit UpdatedProfitFactor(_profitFactor); } /** * @notice * Sets how far the Strategy can go into loss without a harvest and report * being required. * * By default this is 0, meaning any losses would cause a harvest which * will subsequently report the loss to the Vault for tracking. (See * `harvestTrigger()` for more details.) * * This may only be called by governance or the strategist. * @param _debtThreshold How big of a loss this Strategy may carry without * being required to report to the Vault. */ function setDebtThreshold(uint256 _debtThreshold) external onlyAuthorized { debtThreshold = _debtThreshold; emit UpdatedDebtThreshold(_debtThreshold); } /** * @notice * Used to change `metadataURI`. `metadataURI` is used to store the URI * of the file describing the strategy. * * This may only be called by governance or the strategist. * @param _metadataURI The URI that describe the strategy. */ function setMetadataURI(string calldata _metadataURI) external onlyAuthorized { metadataURI = _metadataURI; emit UpdatedMetadataURI(_metadataURI); } /** * Resolve governance address from Vault contract, used to make assertions * on protected functions in the Strategy. */ function governance() internal view returns (address) { return vault.governance(); } /** * @notice * Provide an accurate conversion from `_amtInWei` (denominated in wei) * to `want` (using the native decimal characteristics of `want`). * @dev * Care must be taken when working with decimals to assure that the conversion * is compatible. As an example: * * given 1e17 wei (0.1 ETH) as input, and want is USDC (6 decimals), * with USDC/ETH = 1800, this should give back 1800000000 (180 USDC) * * @param _amtInWei The amount (in wei/1e-18 ETH) to convert to `want` * @return The amount in `want` of `_amtInEth` converted to `want` **/ function ethToWant(uint256 _amtInWei) public view virtual returns (uint256); /** * @notice * Provide an accurate estimate for the total amount of assets * (principle + return) that this Strategy is currently managing, * denominated in terms of `want` tokens. * * This total should be "realizable" e.g. the total value that could * *actually* be obtained from this Strategy if it were to divest its * entire position based on current on-chain conditions. * @dev * Care must be taken in using this function, since it relies on external * systems, which could be manipulated by the attacker to give an inflated * (or reduced) value produced by this function, based on current on-chain * conditions (e.g. this function is possible to influence through * flashloan attacks, oracle manipulations, or other DeFi attack * mechanisms). * * It is up to governance to use this function to correctly order this * Strategy relative to its peers in the withdrawal queue to minimize * losses for the Vault based on sudden withdrawals. This value should be * higher than the total debt of the Strategy and higher than its expected * value to be "safe". * @return The estimated total assets in this Strategy. */ function estimatedTotalAssets() public view virtual returns (uint256); /* * @notice * Provide an indication of whether this strategy is currently "active" * in that it is managing an active position, or will manage a position in * the future. This should correlate to `harvest()` activity, so that Harvest * events can be tracked externally by indexing agents. * @return True if the strategy is actively managing a position. */ function isActive() public view returns (bool) { return vault.strategies(address(this)).debtRatio > 0 || estimatedTotalAssets() > 0; } /** * Perform any Strategy unwinding or other calls necessary to capture the * "free return" this Strategy has generated since the last time its core * position(s) were adjusted. Examples include unwrapping extra rewards. * This call is only used during "normal operation" of a Strategy, and * should be optimized to minimize losses as much as possible. * * This method returns any realized profits and/or realized losses * incurred, and should return the total amounts of profits/losses/debt * payments (in `want` tokens) for the Vault's accounting (e.g. * `want.balanceOf(this) >= _debtPayment + _profit`). * * `_debtOutstanding` will be 0 if the Strategy is not past the configured * debt limit, otherwise its value will be how far past the debt limit * the Strategy is. The Strategy's debt limit is configured in the Vault. * * NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`. * It is okay for it to be less than `_debtOutstanding`, as that * should only used as a guide for how much is left to pay back. * Payments should be made to minimize loss from slippage, debt, * withdrawal fees, etc. * * See `vault.debtOutstanding()`. */ function prepareReturn(uint256 _debtOutstanding) internal virtual returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ); /** * Perform any adjustments to the core position(s) of this Strategy given * what change the Vault made in the "investable capital" available to the * Strategy. Note that all "free capital" in the Strategy after the report * was made is available for reinvestment. Also note that this number * could be 0, and you should handle that scenario accordingly. * * See comments regarding `_debtOutstanding` on `prepareReturn()`. */ function adjustPosition(uint256 _debtOutstanding) internal virtual; /** * Liquidate up to `_amountNeeded` of `want` of this strategy's positions, * irregardless of slippage. Any excess will be re-invested with `adjustPosition()`. * This function should return the amount of `want` tokens made available by the * liquidation. If there is a difference between them, `_loss` indicates whether the * difference is due to a realized loss, or if there is some other sitution at play * (e.g. locked funds) where the amount made available is less than what is needed. * * NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained */ function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss); /** * Liquidate everything and returns the amount that got freed. * This function is used during emergency exit instead of `prepareReturn()` to * liquidate all of the Strategy's positions back to the Vault. */ function liquidateAllPositions() internal virtual returns (uint256 _amountFreed); /** * @notice * Provide a signal to the keeper that `tend()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `tend()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `tend()` is not called * shortly, then this can return `true` even if the keeper might be * "at a loss" (keepers are always reimbursed by Yearn). * @dev * `callCostInWei` must be priced in terms of `wei` (1e-18 ETH). * * This call and `harvestTrigger()` should never return `true` at the same * time. * @param callCostInWei The keeper's estimated gas cost to call `tend()` (in wei). * @return `true` if `tend()` should be called, `false` otherwise. */ function tendTrigger(uint256 callCostInWei) public view virtual returns (bool) { // We usually don't need tend, but if there are positions that need // active maintainence, overriding this function is how you would // signal for that. // If your implementation uses the cost of the call in want, you can // use uint256 callCost = ethToWant(callCostInWei); return false; } /** * @notice * Adjust the Strategy's position. The purpose of tending isn't to * realize gains, but to maximize yield by reinvesting any returns. * * See comments on `adjustPosition()`. * * This may only be called by governance, the strategist, or the keeper. */ function tend() external onlyKeepers { // Don't take profits with this call, but adjust for better gains adjustPosition(vault.debtOutstanding()); } /** * @notice * Provide a signal to the keeper that `harvest()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `harvest()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `harvest()` is not called * shortly, then this can return `true` even if the keeper might be "at a * loss" (keepers are always reimbursed by Yearn). * @dev * `callCostInWei` must be priced in terms of `wei` (1e-18 ETH). * * This call and `tendTrigger` should never return `true` at the * same time. * * See `min/maxReportDelay`, `profitFactor`, `debtThreshold` to adjust the * strategist-controlled parameters that will influence whether this call * returns `true` or not. These parameters will be used in conjunction * with the parameters reported to the Vault (see `params`) to determine * if calling `harvest()` is merited. * * It is expected that an external system will check `harvestTrigger()`. * This could be a script run off a desktop or cloud bot (e.g. * https://github.com/iearn-finance/yearn-vaults/blob/main/scripts/keep.py), * or via an integration with the Keep3r network (e.g. * https://github.com/Macarse/GenericKeep3rV2/blob/master/contracts/keep3r/GenericKeep3rV2.sol). * @param callCostInWei The keeper's estimated gas cost to call `harvest()` (in wei). * @return `true` if `harvest()` should be called, `false` otherwise. */ function harvestTrigger(uint256 callCostInWei) public view virtual returns (bool) { uint256 callCost = ethToWant(callCostInWei); StrategyParams memory params = vault.strategies(address(this)); // Should not trigger if Strategy is not activated if (params.activation == 0) return false; // Should not trigger if we haven't waited long enough since previous harvest if (block.timestamp.sub(params.lastReport) < minReportDelay) return false; // Should trigger if hasn't been called in a while if (block.timestamp.sub(params.lastReport) >= maxReportDelay) return true; // If some amount is owed, pay it back // NOTE: Since debt is based on deposits, it makes sense to guard against large // changes to the value from triggering a harvest directly through user // behavior. This should ensure reasonable resistance to manipulation // from user-initiated withdrawals as the outstanding debt fluctuates. uint256 outstanding = vault.debtOutstanding(); if (outstanding > debtThreshold) return true; // Check for profits and losses uint256 total = estimatedTotalAssets(); // Trigger if we have a loss to report if (total.add(debtThreshold) < params.totalDebt) return true; uint256 profit = 0; if (total > params.totalDebt) profit = total.sub(params.totalDebt); // We've earned a profit! // Otherwise, only trigger if it "makes sense" economically (gas cost // is <N% of value moved) uint256 credit = vault.creditAvailable(); return (profitFactor.mul(callCost) < credit.add(profit)); } /** * @notice * Harvests the Strategy, recognizing any profits or losses and adjusting * the Strategy's position. * * In the rare case the Strategy is in emergency shutdown, this will exit * the Strategy's position. * * This may only be called by governance, the strategist, or the keeper. * @dev * When `harvest()` is called, the Strategy reports to the Vault (via * `vault.report()`), so in some cases `harvest()` must be called in order * to take in profits, to borrow newly available funds from the Vault, or * otherwise adjust its position. In other cases `harvest()` must be * called to report to the Vault on the Strategy's position, especially if * any losses have occurred. */ function harvest() external onlyKeepers { uint256 profit = 0; uint256 loss = 0; uint256 debtOutstanding = vault.debtOutstanding(); uint256 debtPayment = 0; if (emergencyExit) { // Free up as much capital as possible uint256 amountFreed = liquidateAllPositions(); if (amountFreed < debtOutstanding) { loss = debtOutstanding.sub(amountFreed); } else if (amountFreed > debtOutstanding) { profit = amountFreed.sub(debtOutstanding); } debtPayment = debtOutstanding.sub(loss); } else { // Free up returns for Vault to pull (profit, loss, debtPayment) = prepareReturn(debtOutstanding); } // Allow Vault to take up to the "harvested" balance of this contract, // which is the amount it has earned since the last time it reported to // the Vault. uint256 totalDebt = vault.strategies(address(this)).totalDebt; debtOutstanding = vault.report(profit, loss, debtPayment); // Check if free returns are left, and re-invest them adjustPosition(debtOutstanding); // call healthCheck contract if (doHealthCheck && healthCheck != address(0)) { require(HealthCheck(healthCheck).check(profit, loss, debtPayment, debtOutstanding, totalDebt), "!healthcheck"); } else { doHealthCheck = true; } emit Harvested(profit, loss, debtPayment, debtOutstanding); } /** * @notice * Withdraws `_amountNeeded` to `vault`. * * This may only be called by the Vault. * @param _amountNeeded How much `want` to withdraw. * @return _loss Any realized losses */ function withdraw(uint256 _amountNeeded) external returns (uint256 _loss) { require(msg.sender == address(vault), "!vault"); // Liquidate as much as possible to `want`, up to `_amountNeeded` uint256 amountFreed; (amountFreed, _loss) = liquidatePosition(_amountNeeded); // Send it directly back (NOTE: Using `msg.sender` saves some gas here) want.safeTransfer(msg.sender, amountFreed); // NOTE: Reinvest anything leftover on next `tend`/`harvest` } /** * Do anything necessary to prepare this Strategy for migration, such as * transferring any reserve or LP tokens, CDPs, or other tokens or stores of * value. */ function prepareMigration(address _newStrategy) internal virtual; /** * @notice * Transfers all `want` from this Strategy to `_newStrategy`. * * This may only be called by the Vault. * @dev * The new Strategy's Vault must be the same as this Strategy's Vault. * The migration process should be carefully performed to make sure all * the assets are migrated to the new address, which should have never * interacted with the vault before. * @param _newStrategy The Strategy to migrate to. */ function migrate(address _newStrategy) external { require(msg.sender == address(vault)); require(BaseStrategy(_newStrategy).vault() == vault); prepareMigration(_newStrategy); want.safeTransfer(_newStrategy, want.balanceOf(address(this))); } /** * @notice * Activates emergency exit. Once activated, the Strategy will exit its * position upon the next harvest, depositing all funds into the Vault as * quickly as is reasonable given on-chain conditions. * * This may only be called by governance or the strategist. * @dev * See `vault.setEmergencyShutdown()` and `harvest()` for further details. */ function setEmergencyExit() external onlyEmergencyAuthorized { emergencyExit = true; vault.revokeStrategy(); emit EmergencyExitEnabled(); } /** * Override this to add all tokens/tokenized positions this contract * manages on a *persistent* basis (e.g. not just for swapping back to * want ephemerally). * * NOTE: Do *not* include `want`, already included in `sweep` below. * * Example: * ``` * function protectedTokens() internal override view returns (address[] memory) { * address[] memory protected = new address[](3); * protected[0] = tokenA; * protected[1] = tokenB; * protected[2] = tokenC; * return protected; * } * ``` */ function protectedTokens() internal view virtual returns (address[] memory); /** * @notice * Removes tokens from this Strategy that are not the type of tokens * managed by this Strategy. This may be used in case of accidentally * sending the wrong kind of token to this Strategy. * * Tokens will be sent to `governance()`. * * This will fail if an attempt is made to sweep `want`, or any tokens * that are protected by this Strategy. * * This may only be called by governance. * @dev * Implement `protectedTokens()` to specify any additional tokens that * should be protected from sweeping in addition to `want`. * @param _token The token to transfer out of this vault. */ function sweep(address _token) external onlyGovernance { require(_token != address(want), "!want"); require(_token != address(vault), "!shares"); address[] memory _protectedTokens = protectedTokens(); for (uint256 i; i < _protectedTokens.length; i++) require(_token != _protectedTokens[i], "!protected"); IERC20(_token).safeTransfer(governance(), IERC20(_token).balanceOf(address(this))); } } // Part: IAToken interface IAToken is IERC20, IScaledBalanceToken, IInitializableAToken { /** * @dev Emitted after the mint action * @param from The address performing the mint * @param value The amount being * @param index The new liquidity index of the reserve **/ event Mint(address indexed from, uint256 value, uint256 index); /** * @dev Mints `amount` aTokens to `user` * @param user The address receiving the minted tokens * @param amount The amount of tokens getting minted * @param index The new liquidity index of the reserve * @return `true` if the the previous balance of the user was 0 */ function mint( address user, uint256 amount, uint256 index ) external returns (bool); /** * @dev Emitted after aTokens are burned * @param from The owner of the aTokens, getting them burned * @param target The address that will receive the underlying * @param value The amount being burned * @param index The new liquidity index of the reserve **/ event Burn( address indexed from, address indexed target, uint256 value, uint256 index ); /** * @dev Emitted during the transfer action * @param from The user whose tokens are being transferred * @param to The recipient * @param value The amount being transferred * @param index The new liquidity index of the reserve **/ event BalanceTransfer( address indexed from, address indexed to, uint256 value, uint256 index ); /** * @dev Burns aTokens from `user` and sends the equivalent amount of underlying to `receiverOfUnderlying` * @param user The owner of the aTokens, getting them burned * @param receiverOfUnderlying The address that will receive the underlying * @param amount The amount being burned * @param index The new liquidity index of the reserve **/ function burn( address user, address receiverOfUnderlying, uint256 amount, uint256 index ) external; /** * @dev Mints aTokens to the reserve treasury * @param amount The amount of tokens getting minted * @param index The new liquidity index of the reserve */ function mintToTreasury(uint256 amount, uint256 index) external; /** * @dev Transfers aTokens in the event of a borrow being liquidated, in case the liquidators reclaims the aToken * @param from The address getting liquidated, current owner of the aTokens * @param to The recipient * @param value The amount of tokens getting transferred **/ function transferOnLiquidation( address from, address to, uint256 value ) external; /** * @dev Transfers the underlying asset to `target`. Used by the LendingPool to transfer * assets in borrow(), withdraw() and flashLoan() * @param user The recipient of the underlying * @param amount The amount getting transferred * @return The amount transferred **/ function transferUnderlyingTo(address user, uint256 amount) external returns (uint256); /** * @dev Invoked to execute actions on the aToken side after a repayment. * @param user The user executing the repayment * @param amount The amount getting repaid **/ function handleRepayment(address user, uint256 amount) external; /** * @dev Returns the address of the incentives controller contract **/ function getIncentivesController() external view returns (IAaveIncentivesController); /** * @dev Returns the address of the underlying asset of this aToken (E.g. WETH for aWETH) **/ function UNDERLYING_ASSET_ADDRESS() external view returns (address); } // Part: yearn/[email protected]/BaseStrategyInitializable abstract contract BaseStrategyInitializable is BaseStrategy { bool public isOriginal = true; event Cloned(address indexed clone); constructor(address _vault) public BaseStrategy(_vault) {} function initialize( address _vault, address _strategist, address _rewards, address _keeper ) external virtual { _initialize(_vault, _strategist, _rewards, _keeper); } function clone(address _vault) external returns (address) { require(isOriginal, "!clone"); return this.clone(_vault, msg.sender, msg.sender, msg.sender); } function clone( address _vault, address _strategist, address _rewards, address _keeper ) external returns (address newStrategy) { // Copied from https://github.com/optionality/clone-factory/blob/master/contracts/CloneFactory.sol bytes20 addressBytes = bytes20(address(this)); assembly { // EIP-1167 bytecode let clone_code := mload(0x40) mstore(clone_code, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(clone_code, 0x14), addressBytes) mstore(add(clone_code, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) newStrategy := create(0, clone_code, 0x37) } BaseStrategyInitializable(newStrategy).initialize(_vault, _strategist, _rewards, _keeper); emit Cloned(newStrategy); } } // Part: FlashLoanLib library FlashLoanLib { using SafeMath for uint256; event Leverage( uint256 amountRequested, uint256 amountGiven, bool deficit, address flashLoan ); address public constant SOLO = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; uint256 private constant collatRatioETH = 0.79 ether; uint256 private constant COLLAT_RATIO_PRECISION = 1 ether; address private constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; IAToken public constant aWeth = IAToken(0x030bA81f1c18d280636F32af80b9AAd02Cf0854e); IProtocolDataProvider private constant protocolDataProvider = IProtocolDataProvider(0x057835Ad21a177dbdd3090bB1CAE03EaCF78Fc6d); ILendingPool private constant lendingPool = ILendingPool(0x7d2768dE32b0b80b7a3454c06BdAc94A69DDc7A9); // Aave's referral code uint16 private constant referral = 0; function doDyDxFlashLoan( bool deficit, uint256 amountDesired, address token ) public returns (uint256 amount) { if (amountDesired == 0) { return 0; } amount = amountDesired; ISoloMargin solo = ISoloMargin(SOLO); // calculate amount of ETH we need uint256 requiredETH; { requiredETH = _toETH(amount, token).mul(COLLAT_RATIO_PRECISION).div( collatRatioETH ); uint256 dxdyLiquidity = IERC20(weth).balanceOf(address(solo)); if (requiredETH > dxdyLiquidity) { requiredETH = dxdyLiquidity; // NOTE: if we cap amountETH, we reduce amountToken we are taking too amount = _fromETH(requiredETH, token).mul(collatRatioETH).div( 1 ether ); } } // Array of actions to be done during FlashLoan Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); // 1. Take FlashLoan operations[0] = _getWithdrawAction(0, requiredETH); // hardcoded market ID to 0 (ETH) // 2. Encode arguments of functions and create action for calling it bytes memory data = abi.encode(deficit, amount); // This call will: // supply ETH to Aave // borrow desired Token from Aave // do stuff with Token // repay desired Token to Aave // withdraw ETH from Aave operations[1] = _getCallAction(data); // 3. Repay FlashLoan operations[2] = _getDepositAction(0, requiredETH.add(2)); // Create Account Info Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = _getAccountInfo(); solo.operate(accountInfos, operations); emit Leverage(amountDesired, requiredETH, deficit, address(solo)); return amount; // we need to return the amount of Token we have changed our position in } function loanLogic( bool deficit, uint256 amount, address want ) public { uint256 wethBal = IERC20(weth).balanceOf(address(this)); ILendingPool lp = lendingPool; // 1. Deposit WETH in Aave as collateral lp.deposit(weth, wethBal, address(this), referral); if (deficit) { // 2a. if in deficit withdraw amount and repay it lp.withdraw(want, amount, address(this)); lp.repay(want, amount, 2, address(this)); } else { // 2b. if levering up borrow and deposit lp.borrow(want, amount, 2, 0, address(this)); lp.deposit( want, IERC20(want).balanceOf(address(this)), address(this), referral ); } // 3. Withdraw WETH lp.withdraw(weth, wethBal, address(this)); } function _getAccountInfo() internal view returns (Account.Info memory) { return Account.Info({owner: address(this), number: 1}); } function _getWithdrawAction(uint256 marketId, uint256 amount) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Withdraw, accountId: 0, amount: Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: amount }), primaryMarketId: marketId, secondaryMarketId: 0, otherAddress: address(this), otherAccountId: 0, data: "" }); } function _getCallAction(bytes memory data) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Call, accountId: 0, amount: Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: 0 }), primaryMarketId: 0, secondaryMarketId: 0, otherAddress: address(this), otherAccountId: 0, data: data }); } function _getDepositAction(uint256 marketId, uint256 amount) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Deposit, accountId: 0, amount: Types.AssetAmount({ sign: true, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: amount }), primaryMarketId: marketId, secondaryMarketId: 0, otherAddress: address(this), otherAccountId: 0, data: "" }); } function _priceOracle() internal view returns (IPriceOracle) { return IPriceOracle( protocolDataProvider.ADDRESSES_PROVIDER().getPriceOracle() ); } function _toETH(uint256 _amount, address asset) internal view returns (uint256) { if ( _amount == 0 || _amount == type(uint256).max || address(asset) == address(weth) // 1:1 change ) { return _amount; } return _amount.mul(_priceOracle().getAssetPrice(asset)).div( uint256(10)**uint256(IOptionalERC20(asset).decimals()) ); } function _fromETH(uint256 _amount, address asset) internal view returns (uint256) { if ( _amount == 0 || _amount == type(uint256).max || address(asset) == address(weth) // 1:1 change ) { return _amount; } return _amount .mul(uint256(10)**uint256(IOptionalERC20(asset).decimals())) .div(_priceOracle().getAssetPrice(asset)); } } // File: Strategy.sol contract Strategy is BaseStrategyInitializable, ICallee { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; // AAVE protocol address IProtocolDataProvider private constant protocolDataProvider = IProtocolDataProvider(0x057835Ad21a177dbdd3090bB1CAE03EaCF78Fc6d); IAaveIncentivesController private constant incentivesController = IAaveIncentivesController(0xd784927Ff2f95ba542BfC824c8a8a98F3495f6b5); ILendingPool private constant lendingPool = ILendingPool(0x7d2768dE32b0b80b7a3454c06BdAc94A69DDc7A9); // Token addresses address private constant aave = 0x7Fc66500c84A76Ad7e9c93437bFc5Ac33E2DDaE9; IStakedAave private constant stkAave = IStakedAave(0x4da27a545c0c5B758a6BA100e3a049001de870f5); address private constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // Supply and borrow tokens IAToken public aToken; IVariableDebtToken public debtToken; // SWAP routers IUni private constant V2ROUTER = IUni(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); ISwapRouter private constant V3ROUTER = ISwapRouter(0xE592427A0AEce92De3Edee1F18E0157C05861564); // OPS State Variables uint256 private constant DEFAULT_COLLAT_TARGET_MARGIN = 0.02 ether; uint256 private constant DEFAULT_COLLAT_MAX_MARGIN = 0.005 ether; uint256 private constant LIQUIDATION_WARNING_THRESHOLD = 0.01 ether; uint256 public maxBorrowCollatRatio; // The maximum the aave protocol will let us borrow uint256 public targetCollatRatio; // The LTV we are levering up to uint256 public maxCollatRatio; // Closest to liquidation we'll risk uint8 public maxIterations = 6; bool public isDyDxActive = true; uint256 public minWant = 100; uint256 public minRatio = 0.005 ether; uint256 public minRewardToSell = 1e15; bool public sellStkAave = true; bool public cooldownStkAave = false; bool public useUniV3 = false; // only applied to aave => want, stkAave => aave always uses v3 uint256 public maxStkAavePriceImpactBps = 1000; uint24 public stkAaveToAaveSwapFee = 10000; uint24 public aaveToWethSwapFee = 3000; uint24 public wethToWantSwapFee = 3000; uint16 private constant referral = 0; // Aave's referral code bool private alreadyAdjusted = false; // Signal whether a position adjust was done in prepareReturn uint256 private constant MAX_BPS = 1e4; uint256 private constant BPS_WAD_RATIO = 1e14; uint256 private constant COLLATERAL_RATIO_PRECISION = 1 ether; uint256 private constant PESSIMISM_FACTOR = 1000; uint256 private DECIMALS; constructor(address _vault) public BaseStrategyInitializable(_vault) { _initializeThis(); } function initialize( address _vault, address _strategist, address _rewards, address _keeper ) external override { _initialize(_vault, _strategist, _rewards, _keeper); _initializeThis(); } function _initializeThis() internal { require(address(aToken) == address(0)); // initialize operational state maxIterations = 6; isDyDxActive = true; // mins minWant = 100; minRatio = 0.005 ether; minRewardToSell = 1e15; // reward params sellStkAave = true; cooldownStkAave = false; useUniV3 = false; maxStkAavePriceImpactBps = 1000; stkAaveToAaveSwapFee = 10000; aaveToWethSwapFee = 3000; wethToWantSwapFee = 3000; // Set aave tokens (address _aToken, , address _debtToken) = protocolDataProvider.getReserveTokensAddresses(address(want)); aToken = IAToken(_aToken); debtToken = IVariableDebtToken(_debtToken); // Let collateral targets (, uint256 ltv, uint256 liquidationThreshold, , , , , , , ) = protocolDataProvider.getReserveConfigurationData(address(want)); liquidationThreshold = liquidationThreshold.mul(BPS_WAD_RATIO); // convert bps to wad targetCollatRatio = liquidationThreshold.sub( DEFAULT_COLLAT_TARGET_MARGIN ); maxCollatRatio = liquidationThreshold.sub(DEFAULT_COLLAT_MAX_MARGIN); maxBorrowCollatRatio = ltv.mul(BPS_WAD_RATIO).sub( DEFAULT_COLLAT_MAX_MARGIN ); DECIMALS = 10**vault.decimals(); // approve spend aave spend approveMaxSpend(address(want), address(lendingPool)); approveMaxSpend(address(aToken), address(lendingPool)); // approve flashloan spend approveMaxSpend(weth, address(lendingPool)); approveMaxSpend(weth, FlashLoanLib.SOLO); // approve swap router spend approveMaxSpend(address(stkAave), address(V3ROUTER)); approveMaxSpend(aave, address(V2ROUTER)); approveMaxSpend(aave, address(V3ROUTER)); } // SETTERS function setCollateralTargets( uint256 _targetCollatRatio, uint256 _maxCollatRatio, uint256 _maxBorrowCollatRatio ) external onlyVaultManagers { (, uint256 ltv, uint256 liquidationThreshold, , , , , , , ) = protocolDataProvider.getReserveConfigurationData(address(want)); // convert bps to wad ltv = ltv.mul(BPS_WAD_RATIO); liquidationThreshold = liquidationThreshold.mul(BPS_WAD_RATIO); require(_targetCollatRatio < liquidationThreshold); require(_maxCollatRatio < liquidationThreshold); require(_targetCollatRatio < _maxCollatRatio); require(_maxBorrowCollatRatio < ltv); targetCollatRatio = _targetCollatRatio; maxCollatRatio = _maxCollatRatio; maxBorrowCollatRatio = _maxBorrowCollatRatio; } function setIsDyDxActive(bool _isDyDxActive) external onlyVaultManagers { isDyDxActive = _isDyDxActive; } function setMinsAndMaxs( uint256 _minWant, uint256 _minRatio, uint8 _maxIterations ) external onlyVaultManagers { require(_minRatio < maxBorrowCollatRatio); require(_maxIterations > 0 && _maxIterations < 16); minWant = _minWant; minRatio = _minRatio; maxIterations = _maxIterations; } function setRewardBehavior( bool _sellStkAave, bool _cooldownStkAave, bool _useUniV3, uint256 _minRewardToSell, uint256 _maxStkAavePriceImpactBps, uint24 _stkAaveToAaveSwapFee, uint24 _aaveToWethSwapFee, uint24 _wethToWantSwapFee ) external onlyVaultManagers { require(_maxStkAavePriceImpactBps <= MAX_BPS); sellStkAave = _sellStkAave; cooldownStkAave = _cooldownStkAave; useUniV3 = _useUniV3; minRewardToSell = _minRewardToSell; maxStkAavePriceImpactBps = _maxStkAavePriceImpactBps; stkAaveToAaveSwapFee = _stkAaveToAaveSwapFee; aaveToWethSwapFee = _aaveToWethSwapFee; wethToWantSwapFee = _wethToWantSwapFee; } function name() external view override returns (string memory) { return "StrategyGenLevAAVE"; } function estimatedTotalAssets() public view override returns (uint256) { uint256 balanceExcludingRewards = balanceOfWant().add(getCurrentSupply()); // if we don't have a position, don't worry about rewards if (balanceExcludingRewards < minWant) { return balanceExcludingRewards; } uint256 rewards = estimatedRewardsInWant().mul(MAX_BPS.sub(PESSIMISM_FACTOR)).div( MAX_BPS ); return balanceExcludingRewards.add(rewards); } function estimatedRewardsInWant() public view returns (uint256) { uint256 aaveBalance = balanceOfAave(); uint256 stkAaveBalance = balanceOfStkAave(); uint256 pendingRewards = incentivesController.getRewardsBalance( getAaveAssets(), address(this) ); uint256 stkAaveDiscountFactor = MAX_BPS.sub(maxStkAavePriceImpactBps); uint256 combinedStkAave = pendingRewards.add(stkAaveBalance).mul(stkAaveDiscountFactor).div( MAX_BPS ); return tokenToWant(aave, aaveBalance.add(combinedStkAave)); } function prepareReturn(uint256 _debtOutstanding) internal override returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ) { // claim & sell rewards _claimAndSellRewards(); // account for profit / losses uint256 totalDebt = vault.strategies(address(this)).totalDebt; // Assets immediately convertable to want only uint256 supply = getCurrentSupply(); uint256 totalAssets = balanceOfWant().add(supply); if (totalDebt > totalAssets) { // we have losses _loss = totalDebt.sub(totalAssets); } else { // we have profit _profit = totalAssets.sub(totalDebt); } // free funds to repay debt + profit to the strategy uint256 amountAvailable = balanceOfWant(); uint256 amountRequired = _debtOutstanding.add(_profit); if (amountRequired > amountAvailable) { // we need to free funds // we dismiss losses here, they cannot be generated from withdrawal // but it is possible for the strategy to unwind full position (amountAvailable, ) = liquidatePosition(amountRequired); // Don't do a redundant adjustment in adjustPosition alreadyAdjusted = true; if (amountAvailable >= amountRequired) { _debtPayment = _debtOutstanding; // profit remains unchanged unless there is not enough to pay it if (amountRequired.sub(_debtPayment) < _profit) { _profit = amountRequired.sub(_debtPayment); } } else { // we were not able to free enough funds if (amountAvailable < _debtOutstanding) { // available funds are lower than the repayment that we need to do _profit = 0; _debtPayment = amountAvailable; // we dont report losses here as the strategy might not be able to return in this harvest // but it will still be there for the next harvest } else { // NOTE: amountRequired is always equal or greater than _debtOutstanding // important to use amountRequired just in case amountAvailable is > amountAvailable _debtPayment = _debtOutstanding; _profit = amountAvailable.sub(_debtPayment); } } } else { _debtPayment = _debtOutstanding; // profit remains unchanged unless there is not enough to pay it if (amountRequired.sub(_debtPayment) < _profit) { _profit = amountRequired.sub(_debtPayment); } } } function adjustPosition(uint256 _debtOutstanding) internal override { if (alreadyAdjusted) { alreadyAdjusted = false; // reset for next time return; } uint256 wantBalance = balanceOfWant(); // deposit available want as collateral if ( wantBalance > _debtOutstanding && wantBalance.sub(_debtOutstanding) > minWant ) { _depositCollateral(wantBalance.sub(_debtOutstanding)); // we update the value wantBalance = balanceOfWant(); } // check current position uint256 currentCollatRatio = getCurrentCollatRatio(); // Either we need to free some funds OR we want to be max levered if (_debtOutstanding > wantBalance) { // we should free funds uint256 amountRequired = _debtOutstanding.sub(wantBalance); // NOTE: vault will take free funds during the next harvest _freeFunds(amountRequired); } else if (currentCollatRatio < targetCollatRatio) { // we should lever up if (targetCollatRatio.sub(currentCollatRatio) > minRatio) { // we only act on relevant differences _leverMax(); } } else if (currentCollatRatio > targetCollatRatio) { if (currentCollatRatio.sub(targetCollatRatio) > minRatio) { (uint256 deposits, uint256 borrows) = getCurrentPosition(); uint256 newBorrow = getBorrowFromSupply( deposits.sub(borrows), targetCollatRatio ); _leverDownTo(newBorrow, borrows); } } } function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _liquidatedAmount, uint256 _loss) { // NOTE: Maintain invariant `want.balanceOf(this) >= _liquidatedAmount` // NOTE: Maintain invariant `_liquidatedAmount + _loss <= _amountNeeded` uint256 wantBalance = balanceOfWant(); if (wantBalance > _amountNeeded) { // if there is enough free want, let's use it return (_amountNeeded, 0); } // we need to free funds uint256 amountRequired = _amountNeeded.sub(wantBalance); _freeFunds(amountRequired); uint256 freeAssets = balanceOfWant(); if (_amountNeeded > freeAssets) { _liquidatedAmount = freeAssets; _loss = _amountNeeded.sub(freeAssets); } else { _liquidatedAmount = _amountNeeded; } } function tendTrigger(uint256 gasCost) public view override returns (bool) { if (harvestTrigger(gasCost)) { //harvest takes priority return false; } // pull the liquidation liquidationThreshold from aave to be extra safu (, , uint256 liquidationThreshold, , , , , , , ) = protocolDataProvider.getReserveConfigurationData(address(want)); // convert bps to wad liquidationThreshold = liquidationThreshold.mul(BPS_WAD_RATIO); uint256 currentCollatRatio = getCurrentCollatRatio(); if (currentCollatRatio >= liquidationThreshold) { return true; } return (liquidationThreshold.sub(currentCollatRatio) <= LIQUIDATION_WARNING_THRESHOLD); } function liquidateAllPositions() internal override returns (uint256 _amountFreed) { (_amountFreed, ) = liquidatePosition(type(uint256).max); } function prepareMigration(address _newStrategy) internal override { require(getCurrentSupply() < minWant); } function protectedTokens() internal view override returns (address[] memory) {} //emergency function that we can use to deleverage manually if something is broken function manualDeleverage(uint256 amount) external onlyVaultManagers { _withdrawCollateral(amount); _repayWant(amount); } //emergency function that we can use to deleverage manually if something is broken function manualReleaseWant(uint256 amount) external onlyVaultManagers { _withdrawCollateral(amount); } // emergency function that we can use to sell rewards if something is broken function manualClaimAndSellRewards() external onlyVaultManagers { _claimAndSellRewards(); } // INTERNAL ACTIONS function _claimAndSellRewards() internal returns (uint256) { uint256 stkAaveBalance = balanceOfStkAave(); uint8 cooldownStatus = stkAaveBalance == 0 ? 0 : _checkCooldown(); // don't check status if we have no stkAave // If it's the claim period claim if (stkAaveBalance > 0 && cooldownStatus == 1) { // redeem AAVE from stkAave stkAave.claimRewards(address(this), type(uint256).max); stkAave.redeem(address(this), stkAaveBalance); } // claim stkAave from lending and borrowing, this will reset the cooldown incentivesController.claimRewards( getAaveAssets(), type(uint256).max, address(this) ); stkAaveBalance = balanceOfStkAave(); // request start of cooldown period, if there's no cooldown in progress if (cooldownStkAave && stkAaveBalance > 0 && cooldownStatus == 0) { stkAave.cooldown(); } // Always keep 1 wei to get around cooldown clear if (sellStkAave && stkAaveBalance >= minRewardToSell.add(1)) { uint256 minAAVEOut = stkAaveBalance.mul(MAX_BPS.sub(maxStkAavePriceImpactBps)).div( MAX_BPS ); _sellSTKAAVEToAAVE(stkAaveBalance.sub(1), minAAVEOut); } // sell AAVE for want uint256 aaveBalance = balanceOfAave(); if (aaveBalance >= minRewardToSell) { _sellAAVEForWant(aaveBalance, 0); } } function _freeFunds(uint256 amountToFree) internal returns (uint256) { if (amountToFree == 0) return 0; (uint256 deposits, uint256 borrows) = getCurrentPosition(); uint256 realAssets = deposits.sub(borrows); uint256 amountRequired = Math.min(amountToFree, realAssets); uint256 newSupply = realAssets.sub(amountRequired); uint256 newBorrow = getBorrowFromSupply(newSupply, targetCollatRatio); // repay required amount _leverDownTo(newBorrow, borrows); return balanceOfWant(); } function _leverMax() internal { (uint256 deposits, uint256 borrows) = getCurrentPosition(); // NOTE: decimals should cancel out uint256 realSupply = deposits.sub(borrows); uint256 newBorrow = getBorrowFromSupply(realSupply, targetCollatRatio); uint256 totalAmountToBorrow = newBorrow.sub(borrows); if (isDyDxActive) { // The best approach is to lever up using regular method, then finish with flash loan totalAmountToBorrow = totalAmountToBorrow.sub( _leverUpStep(totalAmountToBorrow) ); if (totalAmountToBorrow > minWant) { totalAmountToBorrow = totalAmountToBorrow.sub( _leverUpFlashLoan(totalAmountToBorrow) ); } } else { for ( uint8 i = 0; i < maxIterations && totalAmountToBorrow > minWant; i++ ) { totalAmountToBorrow = totalAmountToBorrow.sub( _leverUpStep(totalAmountToBorrow) ); } } } function _leverUpFlashLoan(uint256 amount) internal returns (uint256) { return FlashLoanLib.doDyDxFlashLoan(false, amount, address(want)); } function _leverUpStep(uint256 amount) internal returns (uint256) { if (amount == 0) { return 0; } uint256 wantBalance = balanceOfWant(); // calculate how much borrow can I take (uint256 deposits, uint256 borrows) = getCurrentPosition(); uint256 canBorrow = getBorrowFromDeposit( deposits.add(wantBalance), maxBorrowCollatRatio ); if (canBorrow <= borrows) { return 0; } canBorrow = canBorrow.sub(borrows); if (canBorrow < amount) { amount = canBorrow; } // deposit available want as collateral _depositCollateral(wantBalance); // borrow available amount _borrowWant(amount); return amount; } function _leverDownTo(uint256 newAmountBorrowed, uint256 currentBorrowed) internal returns (uint256) { if (newAmountBorrowed >= currentBorrowed) { // we don't need to repay return 0; } uint256 totalRepayAmount = currentBorrowed.sub(newAmountBorrowed); if (isDyDxActive) { totalRepayAmount = totalRepayAmount.sub( _leverDownFlashLoan(totalRepayAmount) ); _withdrawExcessCollateral(); } for ( uint8 i = 0; i < maxIterations && totalRepayAmount > minWant; i++ ) { uint256 toRepay = totalRepayAmount; uint256 wantBalance = balanceOfWant(); if (toRepay > wantBalance) { toRepay = wantBalance; } uint256 repaid = _repayWant(toRepay); totalRepayAmount = totalRepayAmount.sub(repaid); // withdraw collateral _withdrawExcessCollateral(); } // deposit back to get targetCollatRatio (we always need to leave this in this ratio) (uint256 deposits, uint256 borrows) = getCurrentPosition(); uint256 targetDeposit = getDepositFromBorrow(borrows, targetCollatRatio); if (targetDeposit > deposits) { uint256 toDeposit = targetDeposit.sub(deposits); if (toDeposit > minWant) { _depositCollateral(Math.min(toDeposit, balanceOfWant())); } } } function _leverDownFlashLoan(uint256 amount) internal returns (uint256) { if (amount <= minWant) return 0; (, uint256 borrows) = getCurrentPosition(); if (amount > borrows) { amount = borrows; } return FlashLoanLib.doDyDxFlashLoan(true, amount, address(want)); } function _withdrawExcessCollateral() internal returns (uint256 amount) { (uint256 deposits, uint256 borrows) = getCurrentPosition(); uint256 theoDeposits = getDepositFromBorrow(borrows, maxCollatRatio); if (deposits > theoDeposits) { uint256 toWithdraw = deposits.sub(theoDeposits); return _withdrawCollateral(toWithdraw); } } function _depositCollateral(uint256 amount) internal returns (uint256) { if (amount == 0) return 0; lendingPool.deposit(address(want), amount, address(this), referral); return amount; } function _withdrawCollateral(uint256 amount) internal returns (uint256) { if (amount == 0) return 0; lendingPool.withdraw(address(want), amount, address(this)); return amount; } function _repayWant(uint256 amount) internal returns (uint256) { if (amount == 0) return 0; return lendingPool.repay(address(want), amount, 2, address(this)); } function _borrowWant(uint256 amount) internal returns (uint256) { if (amount == 0) return 0; lendingPool.borrow(address(want), amount, 2, referral, address(this)); return amount; } // INTERNAL VIEWS function balanceOfWant() internal view returns (uint256) { return want.balanceOf(address(this)); } function balanceOfAToken() internal view returns (uint256) { return aToken.balanceOf(address(this)); } function balanceOfDebtToken() internal view returns (uint256) { return debtToken.balanceOf(address(this)); } function balanceOfAave() internal view returns (uint256) { return IERC20(aave).balanceOf(address(this)); } function balanceOfStkAave() internal view returns (uint256) { return IERC20(address(stkAave)).balanceOf(address(this)); } // Flashloan callback function function callFunction( address sender, Account.Info memory account, bytes memory data ) public override { (bool deficit, uint256 amount) = abi.decode(data, (bool, uint256)); require(msg.sender == FlashLoanLib.SOLO); require(sender == address(this)); FlashLoanLib.loanLogic(deficit, amount, address(want)); } function getCurrentPosition() public view returns (uint256 deposits, uint256 borrows) { deposits = balanceOfAToken(); borrows = balanceOfDebtToken(); } function getCurrentCollatRatio() public view returns (uint256 currentCollatRatio) { (uint256 deposits, uint256 borrows) = getCurrentPosition(); if (deposits > 0) { currentCollatRatio = borrows.mul(COLLATERAL_RATIO_PRECISION).div( deposits ); } } function getCurrentSupply() public view returns (uint256) { (uint256 deposits, uint256 borrows) = getCurrentPosition(); return deposits.sub(borrows); } // conversions function tokenToWant(address token, uint256 amount) internal view returns (uint256) { if (amount == 0 || address(want) == token) { return amount; } uint256[] memory amounts = IUni(V2ROUTER).getAmountsOut( amount, getTokenOutPathV2(token, address(want)) ); return amounts[amounts.length - 1]; } function ethToWant(uint256 _amtInWei) public view override returns (uint256) { return tokenToWant(weth, _amtInWei); } // returns cooldown status // 0 = no cooldown or past withdraw period // 1 = claim period // 2 = cooldown initiated, future claim period function _checkCooldown() internal view returns (uint8) { uint256 cooldownStartTimestamp = IStakedAave(stkAave).stakersCooldowns(address(this)); uint256 COOLDOWN_SECONDS = IStakedAave(stkAave).COOLDOWN_SECONDS(); uint256 UNSTAKE_WINDOW = IStakedAave(stkAave).UNSTAKE_WINDOW(); uint256 nextClaimStartTimestamp = cooldownStartTimestamp.add(COOLDOWN_SECONDS); if (cooldownStartTimestamp == 0) { return 0; } if ( block.timestamp > nextClaimStartTimestamp && block.timestamp <= nextClaimStartTimestamp.add(UNSTAKE_WINDOW) ) { return 1; } if (block.timestamp < nextClaimStartTimestamp) { return 2; } } function getTokenOutPathV2(address _token_in, address _token_out) internal pure returns (address[] memory _path) { bool is_weth = _token_in == address(weth) || _token_out == address(weth); _path = new address[](is_weth ? 2 : 3); _path[0] = _token_in; if (is_weth) { _path[1] = _token_out; } else { _path[1] = address(weth); _path[2] = _token_out; } } function getTokenOutPathV3(address _token_in, address _token_out) internal view returns (bytes memory _path) { if (address(want) == weth) { _path = abi.encodePacked( address(aave), aaveToWethSwapFee, address(weth) ); } else { _path = abi.encodePacked( address(aave), aaveToWethSwapFee, address(weth), wethToWantSwapFee, address(want) ); } } function _sellAAVEForWant(uint256 amountIn, uint256 minOut) internal { if (amountIn == 0) { return; } if (useUniV3) { V3ROUTER.exactInput( ISwapRouter.ExactInputParams( getTokenOutPathV3(address(aave), address(want)), address(this), now, amountIn, minOut ) ); } else { V2ROUTER.swapExactTokensForTokens( amountIn, minOut, getTokenOutPathV2(address(aave), address(want)), address(this), now ); } } function _sellSTKAAVEToAAVE(uint256 amountIn, uint256 minOut) internal { // Swap Rewards in UNIV3 // NOTE: Unoptimized, can be frontrun and most importantly this pool is low liquidity V3ROUTER.exactInputSingle( ISwapRouter.ExactInputSingleParams( address(stkAave), address(aave), stkAaveToAaveSwapFee, address(this), now, amountIn, // wei minOut, 0 ) ); } function getAaveAssets() internal view returns (address[] memory assets) { assets = new address[](2); assets[0] = address(aToken); assets[1] = address(debtToken); } function getBorrowFromDeposit(uint256 deposit, uint256 collatRatio) internal pure returns (uint256) { return deposit.mul(collatRatio).div(COLLATERAL_RATIO_PRECISION); } function getDepositFromBorrow(uint256 borrow, uint256 collatRatio) internal pure returns (uint256) { return borrow.mul(COLLATERAL_RATIO_PRECISION).div(collatRatio); } function getBorrowFromSupply(uint256 supply, uint256 collatRatio) internal pure returns (uint256) { return supply.mul(collatRatio).div( COLLATERAL_RATIO_PRECISION.sub(collatRatio) ); } function approveMaxSpend(address token, address spender) internal { IERC20(token).safeApprove(spender, type(uint256).max); } }
if we don't have a position, don't worry about rewards
function estimatedTotalAssets() public view override returns (uint256) { uint256 balanceExcludingRewards = balanceOfWant().add(getCurrentSupply()); if (balanceExcludingRewards < minWant) { return balanceExcludingRewards; } uint256 rewards = estimatedRewardsInWant().mul(MAX_BPS.sub(PESSIMISM_FACTOR)).div( MAX_BPS ); return balanceExcludingRewards.add(rewards); }
219,096
[ 1, 430, 732, 2727, 1404, 1240, 279, 1754, 16, 2727, 1404, 26784, 2973, 283, 6397, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 13137, 5269, 10726, 1435, 1071, 1476, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2254, 5034, 11013, 424, 18596, 17631, 14727, 273, 203, 5411, 11013, 951, 59, 970, 7675, 1289, 12, 588, 3935, 3088, 1283, 10663, 203, 203, 3639, 309, 261, 12296, 424, 18596, 17631, 14727, 411, 1131, 59, 970, 13, 288, 203, 5411, 327, 11013, 424, 18596, 17631, 14727, 31, 203, 3639, 289, 203, 203, 3639, 2254, 5034, 283, 6397, 273, 203, 5411, 13137, 17631, 14727, 382, 59, 970, 7675, 16411, 12, 6694, 67, 38, 5857, 18, 1717, 12, 1423, 1260, 3445, 5127, 49, 67, 26835, 13, 2934, 2892, 12, 203, 7734, 4552, 67, 38, 5857, 203, 5411, 11272, 203, 3639, 327, 11013, 424, 18596, 17631, 14727, 18, 1289, 12, 266, 6397, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.6.6; import "./BToken.sol"; import "./BMath.sol"; // Core contract; can't be changed. So disable solhint (reminder for v2) /* solhint-disable func-order */ /* solhint-disable event-name-camelcase */ contract BPool is BBronze, BToken, BMath { struct Record { bool bound; // is token bound to pool uint256 index; // private uint256 denorm; // denormalized weight uint256 balance; } event LOG_SWAP( address indexed caller, address indexed tokenIn, address indexed tokenOut, uint256 tokenAmountIn, uint256 tokenAmountOut ); event LOG_JOIN(address indexed caller, address indexed tokenIn, uint256 tokenAmountIn); event LOG_EXIT(address indexed caller, address indexed tokenOut, uint256 tokenAmountOut); event LOG_CALL(bytes4 indexed sig, address indexed caller, bytes data) anonymous; modifier _logs_() { emit LOG_CALL(msg.sig, msg.sender, msg.data); _; } modifier _lock_() { require(!_mutex, "ERR_REENTRY"); _mutex = true; _; _mutex = false; } modifier _viewlock_() { require(!_mutex, "ERR_REENTRY"); _; } bool private _mutex; address private _factory; // BFactory address to push token exitFee to address private _controller; // has CONTROL role bool private _publicSwap; // true if PUBLIC can call SWAP functions // `setSwapFee` and `finalize` require CONTROL // `finalize` sets `PUBLIC can SWAP`, `PUBLIC can JOIN` uint256 private _swapFee; bool private _finalized; address[] private _tokens; mapping(address => Record) private _records; uint256 private _totalWeight; bool public initialized; constructor() public { initialized = true; } function init() public { require(initialized == false, "Pool already initialized"); _controller = msg.sender; _factory = msg.sender; _swapFee = MIN_FEE; _publicSwap = false; _finalized = false; } function isPublicSwap() external view returns (bool) { return _publicSwap; } function isFinalized() external view returns (bool) { return _finalized; } function isBound(address t) external view returns (bool) { return _records[t].bound; } function getNumTokens() external view returns (uint256) { return _tokens.length; } function getCurrentTokens() external view _viewlock_ returns (address[] memory tokens) { return _tokens; } function getFinalTokens() external view _viewlock_ returns (address[] memory tokens) { require(_finalized, "ERR_NOT_FINALIZED"); return _tokens; } function getDenormalizedWeight(address token) external view _viewlock_ returns (uint256) { require(_records[token].bound, "ERR_NOT_BOUND"); return _records[token].denorm; } function getTotalDenormalizedWeight() external view _viewlock_ returns (uint256) { return _totalWeight; } function getNormalizedWeight(address token) external view _viewlock_ returns (uint256) { require(_records[token].bound, "ERR_NOT_BOUND"); uint256 denorm = _records[token].denorm; return bdiv(denorm, _totalWeight); } function getBalance(address token) external view _viewlock_ returns (uint256) { require(_records[token].bound, "ERR_NOT_BOUND"); return _records[token].balance; } function getSwapFee() external view _viewlock_ returns (uint256) { return _swapFee; } function getController() external view _viewlock_ returns (address) { return _controller; } function setSwapFee(uint256 swapFee) external _logs_ _lock_ { require(!_finalized, "ERR_IS_FINALIZED"); require(msg.sender == _controller, "ERR_NOT_CONTROLLER"); require(swapFee >= MIN_FEE, "ERR_MIN_FEE"); require(swapFee <= MAX_FEE, "ERR_MAX_FEE"); _swapFee = swapFee; } function setController(address manager) external _logs_ _lock_ { require(msg.sender == _controller, "ERR_NOT_CONTROLLER"); _controller = manager; } function setPublicSwap(bool public_) external _logs_ _lock_ { require(!_finalized, "ERR_IS_FINALIZED"); require(msg.sender == _controller, "ERR_NOT_CONTROLLER"); _publicSwap = public_; } function finalize() external _logs_ _lock_ { require(msg.sender == _controller, "ERR_NOT_CONTROLLER"); require(!_finalized, "ERR_IS_FINALIZED"); require(_tokens.length >= MIN_BOUND_TOKENS, "ERR_MIN_TOKENS"); _finalized = true; _publicSwap = true; _mintPoolShare(INIT_POOL_SUPPLY); _pushPoolShare(msg.sender, INIT_POOL_SUPPLY); } function bind( address token, uint256 balance, uint256 denorm ) external _logs_ // _lock_ Bind does not lock because it jumps to `rebind`, which does { require(msg.sender == _controller, "ERR_NOT_CONTROLLER"); require(!_records[token].bound, "ERR_IS_BOUND"); require(!_finalized, "ERR_IS_FINALIZED"); require(_tokens.length < MAX_BOUND_TOKENS, "ERR_MAX_TOKENS"); _records[token] = Record({ bound: true, index: _tokens.length, denorm: 0, // balance and denorm will be validated balance: 0 // and set by `rebind` }); _tokens.push(token); rebind(token, balance, denorm); } function rebind( address token, uint256 balance, uint256 denorm ) public _logs_ _lock_ { require(msg.sender == _controller, "ERR_NOT_CONTROLLER"); require(_records[token].bound, "ERR_NOT_BOUND"); require(!_finalized, "ERR_IS_FINALIZED"); require(denorm >= MIN_WEIGHT, "ERR_MIN_WEIGHT"); require(denorm <= MAX_WEIGHT, "ERR_MAX_WEIGHT"); require(balance >= MIN_BALANCE, "ERR_MIN_BALANCE"); // Adjust the denorm and totalWeight uint256 oldWeight = _records[token].denorm; if (denorm > oldWeight) { _totalWeight = badd(_totalWeight, bsub(denorm, oldWeight)); require(_totalWeight <= MAX_TOTAL_WEIGHT, "ERR_MAX_TOTAL_WEIGHT"); } else if (denorm < oldWeight) { _totalWeight = bsub(_totalWeight, bsub(oldWeight, denorm)); } _records[token].denorm = denorm; // Adjust the balance record and actual token balance uint256 oldBalance = _records[token].balance; _records[token].balance = balance; if (balance > oldBalance) { _pullUnderlying(token, msg.sender, bsub(balance, oldBalance)); } else if (balance < oldBalance) { // In this case liquidity is being withdrawn, so charge EXIT_FEE uint256 tokenBalanceWithdrawn = bsub(oldBalance, balance); uint256 tokenExitFee = bmul(tokenBalanceWithdrawn, EXIT_FEE); _pushUnderlying(token, msg.sender, bsub(tokenBalanceWithdrawn, tokenExitFee)); _pushUnderlying(token, _factory, tokenExitFee); } } function unbind(address token) external _logs_ _lock_ { require(msg.sender == _controller, "ERR_NOT_CONTROLLER"); require(_records[token].bound, "ERR_NOT_BOUND"); require(!_finalized, "ERR_IS_FINALIZED"); uint256 tokenBalance = _records[token].balance; uint256 tokenExitFee = bmul(tokenBalance, EXIT_FEE); _totalWeight = bsub(_totalWeight, _records[token].denorm); // Swap the token-to-unbind with the last token, // then delete the last token uint256 index = _records[token].index; uint256 last = _tokens.length - 1; _tokens[index] = _tokens[last]; _records[_tokens[index]].index = index; _tokens.pop(); _records[token] = Record({bound: false, index: 0, denorm: 0, balance: 0}); _pushUnderlying(token, msg.sender, bsub(tokenBalance, tokenExitFee)); _pushUnderlying(token, _factory, tokenExitFee); } // Absorb any tokens that have been sent to this contract into the pool function gulp(address token) external _logs_ _lock_ { require(_records[token].bound, "ERR_NOT_BOUND"); _records[token].balance = IERC20(token).balanceOf(address(this)); } function getSpotPrice(address tokenIn, address tokenOut) external view _viewlock_ returns (uint256 spotPrice) { require(_records[tokenIn].bound, "ERR_NOT_BOUND"); require(_records[tokenOut].bound, "ERR_NOT_BOUND"); Record storage inRecord = _records[tokenIn]; Record storage outRecord = _records[tokenOut]; return calcSpotPrice(inRecord.balance, inRecord.denorm, outRecord.balance, outRecord.denorm, _swapFee); } function getSpotPriceSansFee(address tokenIn, address tokenOut) external view _viewlock_ returns (uint256 spotPrice) { require(_records[tokenIn].bound, "ERR_NOT_BOUND"); require(_records[tokenOut].bound, "ERR_NOT_BOUND"); Record storage inRecord = _records[tokenIn]; Record storage outRecord = _records[tokenOut]; return calcSpotPrice(inRecord.balance, inRecord.denorm, outRecord.balance, outRecord.denorm, 0); } function joinPool(uint256 poolAmountOut, uint256[] calldata maxAmountsIn) external _logs_ _lock_ { require(_finalized, "ERR_NOT_FINALIZED"); uint256 poolTotal = totalSupply(); uint256 ratio = bdiv(poolAmountOut, poolTotal); require(ratio != 0, "ERR_MATH_APPROX"); for (uint256 i = 0; i < _tokens.length; i++) { address t = _tokens[i]; uint256 bal = _records[t].balance; uint256 tokenAmountIn = bmul(ratio, bal); require(tokenAmountIn != 0, "ERR_MATH_APPROX"); require(tokenAmountIn <= maxAmountsIn[i], "ERR_LIMIT_IN"); _records[t].balance = badd(_records[t].balance, tokenAmountIn); emit LOG_JOIN(msg.sender, t, tokenAmountIn); _pullUnderlying(t, msg.sender, tokenAmountIn); } _mintPoolShare(poolAmountOut); _pushPoolShare(msg.sender, poolAmountOut); } function exitPool(uint256 poolAmountIn, uint256[] calldata minAmountsOut) external _logs_ _lock_ { require(_finalized, "ERR_NOT_FINALIZED"); uint256 poolTotal = totalSupply(); uint256 exitFee = bmul(poolAmountIn, EXIT_FEE); uint256 pAiAfterExitFee = bsub(poolAmountIn, exitFee); uint256 ratio = bdiv(pAiAfterExitFee, poolTotal); require(ratio != 0, "ERR_MATH_APPROX"); _pullPoolShare(msg.sender, poolAmountIn); _pushPoolShare(_factory, exitFee); _burnPoolShare(pAiAfterExitFee); for (uint256 i = 0; i < _tokens.length; i++) { address t = _tokens[i]; uint256 bal = _records[t].balance; uint256 tokenAmountOut = bmul(ratio, bal); require(tokenAmountOut != 0, "ERR_MATH_APPROX"); require(tokenAmountOut >= minAmountsOut[i], "ERR_LIMIT_OUT"); _records[t].balance = bsub(_records[t].balance, tokenAmountOut); emit LOG_EXIT(msg.sender, t, tokenAmountOut); _pushUnderlying(t, msg.sender, tokenAmountOut); } } function swapExactAmountIn( address tokenIn, uint256 tokenAmountIn, address tokenOut, uint256 minAmountOut, uint256 maxPrice ) external _logs_ _lock_ returns (uint256 tokenAmountOut, uint256 spotPriceAfter) { require(_records[tokenIn].bound, "ERR_NOT_BOUND"); require(_records[tokenOut].bound, "ERR_NOT_BOUND"); require(_publicSwap, "ERR_SWAP_NOT_PUBLIC"); Record storage inRecord = _records[address(tokenIn)]; Record storage outRecord = _records[address(tokenOut)]; require(tokenAmountIn <= bmul(inRecord.balance, MAX_IN_RATIO), "ERR_MAX_IN_RATIO"); uint256 spotPriceBefore = calcSpotPrice( inRecord.balance, inRecord.denorm, outRecord.balance, outRecord.denorm, _swapFee ); require(spotPriceBefore <= maxPrice, "ERR_BAD_LIMIT_PRICE"); tokenAmountOut = calcOutGivenIn( inRecord.balance, inRecord.denorm, outRecord.balance, outRecord.denorm, tokenAmountIn, _swapFee ); require(tokenAmountOut >= minAmountOut, "ERR_LIMIT_OUT"); inRecord.balance = badd(inRecord.balance, tokenAmountIn); outRecord.balance = bsub(outRecord.balance, tokenAmountOut); spotPriceAfter = calcSpotPrice( inRecord.balance, inRecord.denorm, outRecord.balance, outRecord.denorm, _swapFee ); require(spotPriceAfter >= spotPriceBefore, "ERR_MATH_APPROX"); require(spotPriceAfter <= maxPrice, "ERR_LIMIT_PRICE"); require(spotPriceBefore <= bdiv(tokenAmountIn, tokenAmountOut), "ERR_MATH_APPROX"); emit LOG_SWAP(msg.sender, tokenIn, tokenOut, tokenAmountIn, tokenAmountOut); _pullUnderlying(tokenIn, msg.sender, tokenAmountIn); _pushUnderlying(tokenOut, msg.sender, tokenAmountOut); return (tokenAmountOut, spotPriceAfter); } function swapExactAmountOut( address tokenIn, uint256 maxAmountIn, address tokenOut, uint256 tokenAmountOut, uint256 maxPrice ) external _logs_ _lock_ returns (uint256 tokenAmountIn, uint256 spotPriceAfter) { require(_records[tokenIn].bound, "ERR_NOT_BOUND"); require(_records[tokenOut].bound, "ERR_NOT_BOUND"); require(_publicSwap, "ERR_SWAP_NOT_PUBLIC"); Record storage inRecord = _records[address(tokenIn)]; Record storage outRecord = _records[address(tokenOut)]; require(tokenAmountOut <= bmul(outRecord.balance, MAX_OUT_RATIO), "ERR_MAX_OUT_RATIO"); uint256 spotPriceBefore = calcSpotPrice( inRecord.balance, inRecord.denorm, outRecord.balance, outRecord.denorm, _swapFee ); require(spotPriceBefore <= maxPrice, "ERR_BAD_LIMIT_PRICE"); tokenAmountIn = calcInGivenOut( inRecord.balance, inRecord.denorm, outRecord.balance, outRecord.denorm, tokenAmountOut, _swapFee ); require(tokenAmountIn <= maxAmountIn, "ERR_LIMIT_IN"); inRecord.balance = badd(inRecord.balance, tokenAmountIn); outRecord.balance = bsub(outRecord.balance, tokenAmountOut); spotPriceAfter = calcSpotPrice( inRecord.balance, inRecord.denorm, outRecord.balance, outRecord.denorm, _swapFee ); require(spotPriceAfter >= spotPriceBefore, "ERR_MATH_APPROX"); require(spotPriceAfter <= maxPrice, "ERR_LIMIT_PRICE"); require(spotPriceBefore <= bdiv(tokenAmountIn, tokenAmountOut), "ERR_MATH_APPROX"); emit LOG_SWAP(msg.sender, tokenIn, tokenOut, tokenAmountIn, tokenAmountOut); _pullUnderlying(tokenIn, msg.sender, tokenAmountIn); _pushUnderlying(tokenOut, msg.sender, tokenAmountOut); return (tokenAmountIn, spotPriceAfter); } function joinswapExternAmountIn( address tokenIn, uint256 tokenAmountIn, uint256 minPoolAmountOut ) external _logs_ _lock_ returns (uint256 poolAmountOut) { require(_finalized, "ERR_NOT_FINALIZED"); require(_records[tokenIn].bound, "ERR_NOT_BOUND"); require(tokenAmountIn <= bmul(_records[tokenIn].balance, MAX_IN_RATIO), "ERR_MAX_IN_RATIO"); Record storage inRecord = _records[tokenIn]; poolAmountOut = calcPoolOutGivenSingleIn( inRecord.balance, inRecord.denorm, _totalSupply, _totalWeight, tokenAmountIn, _swapFee ); require(poolAmountOut >= minPoolAmountOut, "ERR_LIMIT_OUT"); inRecord.balance = badd(inRecord.balance, tokenAmountIn); emit LOG_JOIN(msg.sender, tokenIn, tokenAmountIn); _mintPoolShare(poolAmountOut); _pushPoolShare(msg.sender, poolAmountOut); _pullUnderlying(tokenIn, msg.sender, tokenAmountIn); return poolAmountOut; } function joinswapPoolAmountOut( address tokenIn, uint256 poolAmountOut, uint256 maxAmountIn ) external _logs_ _lock_ returns (uint256 tokenAmountIn) { require(_finalized, "ERR_NOT_FINALIZED"); require(_records[tokenIn].bound, "ERR_NOT_BOUND"); Record storage inRecord = _records[tokenIn]; tokenAmountIn = calcSingleInGivenPoolOut( inRecord.balance, inRecord.denorm, _totalSupply, _totalWeight, poolAmountOut, _swapFee ); require(tokenAmountIn != 0, "ERR_MATH_APPROX"); require(tokenAmountIn <= maxAmountIn, "ERR_LIMIT_IN"); require(tokenAmountIn <= bmul(_records[tokenIn].balance, MAX_IN_RATIO), "ERR_MAX_IN_RATIO"); inRecord.balance = badd(inRecord.balance, tokenAmountIn); emit LOG_JOIN(msg.sender, tokenIn, tokenAmountIn); _mintPoolShare(poolAmountOut); _pushPoolShare(msg.sender, poolAmountOut); _pullUnderlying(tokenIn, msg.sender, tokenAmountIn); return tokenAmountIn; } function exitswapPoolAmountIn( address tokenOut, uint256 poolAmountIn, uint256 minAmountOut ) external _logs_ _lock_ returns (uint256 tokenAmountOut) { require(_finalized, "ERR_NOT_FINALIZED"); require(_records[tokenOut].bound, "ERR_NOT_BOUND"); Record storage outRecord = _records[tokenOut]; tokenAmountOut = calcSingleOutGivenPoolIn( outRecord.balance, outRecord.denorm, _totalSupply, _totalWeight, poolAmountIn, _swapFee ); require(tokenAmountOut >= minAmountOut, "ERR_LIMIT_OUT"); require(tokenAmountOut <= bmul(_records[tokenOut].balance, MAX_OUT_RATIO), "ERR_MAX_OUT_RATIO"); outRecord.balance = bsub(outRecord.balance, tokenAmountOut); uint256 exitFee = bmul(poolAmountIn, EXIT_FEE); emit LOG_EXIT(msg.sender, tokenOut, tokenAmountOut); _pullPoolShare(msg.sender, poolAmountIn); _burnPoolShare(bsub(poolAmountIn, exitFee)); _pushPoolShare(_factory, exitFee); _pushUnderlying(tokenOut, msg.sender, tokenAmountOut); return tokenAmountOut; } function exitswapExternAmountOut( address tokenOut, uint256 tokenAmountOut, uint256 maxPoolAmountIn ) external _logs_ _lock_ returns (uint256 poolAmountIn) { require(_finalized, "ERR_NOT_FINALIZED"); require(_records[tokenOut].bound, "ERR_NOT_BOUND"); require(tokenAmountOut <= bmul(_records[tokenOut].balance, MAX_OUT_RATIO), "ERR_MAX_OUT_RATIO"); Record storage outRecord = _records[tokenOut]; poolAmountIn = calcPoolInGivenSingleOut( outRecord.balance, outRecord.denorm, _totalSupply, _totalWeight, tokenAmountOut, _swapFee ); require(poolAmountIn != 0, "ERR_MATH_APPROX"); require(poolAmountIn <= maxPoolAmountIn, "ERR_LIMIT_IN"); outRecord.balance = bsub(outRecord.balance, tokenAmountOut); uint256 exitFee = bmul(poolAmountIn, EXIT_FEE); emit LOG_EXIT(msg.sender, tokenOut, tokenAmountOut); _pullPoolShare(msg.sender, poolAmountIn); _burnPoolShare(bsub(poolAmountIn, exitFee)); _pushPoolShare(_factory, exitFee); _pushUnderlying(tokenOut, msg.sender, tokenAmountOut); return poolAmountIn; } // == // 'Underlying' token-manipulation functions make external calls but are NOT locked // You must `_lock_` or otherwise ensure reentry-safety function _pullUnderlying( address erc20, address from, uint256 amount ) internal { bool xfer = IERC20(erc20).transferFrom(from, address(this), amount); require(xfer, "ERR_ERC20_FALSE"); } function _pushUnderlying( address erc20, address to, uint256 amount ) internal { bool xfer = IERC20(erc20).transfer(to, amount); require(xfer, "ERR_ERC20_FALSE"); } function _pullPoolShare(address from, uint256 amount) internal { _pull(from, amount); } function _pushPoolShare(address to, uint256 amount) internal { _push(to, amount); } function _mintPoolShare(uint256 amount) internal { _mint(amount); } function _burnPoolShare(uint256 amount) internal { _burn(amount); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.6.6; import "./BNum.sol"; import "./PCToken.sol"; // Highly opinionated token implementation /* interface IERC20 { event Approval(address indexed src, address indexed dst, uint amt); event Transfer(address indexed src, address indexed dst, uint amt); function totalSupply() external view returns (uint); function balanceOf(address whom) external view returns (uint); function allowance(address src, address dst) external view returns (uint); function approve(address dst, uint amt) external returns (bool); function transfer(address dst, uint amt) external returns (bool); function transferFrom( address src, address dst, uint amt ) external returns (bool); } */ // Core contract; can't be changed. So disable solhint (reminder for v2) /* solhint-disable func-order */ contract BTokenBase is BNum { mapping(address => uint256) internal _balance; mapping(address => mapping(address => uint256)) internal _allowance; uint256 internal _totalSupply; event Approval(address indexed src, address indexed dst, uint256 amt); event Transfer(address indexed src, address indexed dst, uint256 amt); function _mint(uint256 amt) internal { _balance[address(this)] = badd(_balance[address(this)], amt); _totalSupply = badd(_totalSupply, amt); emit Transfer(address(0), address(this), amt); } function _burn(uint256 amt) internal { require(_balance[address(this)] >= amt, "ERR_INSUFFICIENT_BAL"); _balance[address(this)] = bsub(_balance[address(this)], amt); _totalSupply = bsub(_totalSupply, amt); emit Transfer(address(this), address(0), amt); } function _move( address src, address dst, uint256 amt ) internal { require(_balance[src] >= amt, "ERR_INSUFFICIENT_BAL"); _balance[src] = bsub(_balance[src], amt); _balance[dst] = badd(_balance[dst], amt); emit Transfer(src, dst, amt); } function _push(address to, uint256 amt) internal { _move(address(this), to, amt); } function _pull(address from, uint256 amt) internal { _move(from, address(this), amt); } } contract BToken is BTokenBase, IERC20 { string private _name = "Balancer Pool Token"; string private _symbol = "BPT"; uint8 private _decimals = 18; function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function allowance(address src, address dst) external view override returns (uint256) { return _allowance[src][dst]; } function balanceOf(address whom) external view override returns (uint256) { return _balance[whom]; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function approve(address dst, uint256 amt) external override returns (bool) { _allowance[msg.sender][dst] = amt; emit Approval(msg.sender, dst, amt); return true; } function increaseApproval(address dst, uint256 amt) external returns (bool) { _allowance[msg.sender][dst] = badd(_allowance[msg.sender][dst], amt); emit Approval(msg.sender, dst, _allowance[msg.sender][dst]); return true; } function decreaseApproval(address dst, uint256 amt) external returns (bool) { uint256 oldValue = _allowance[msg.sender][dst]; if (amt > oldValue) { _allowance[msg.sender][dst] = 0; } else { _allowance[msg.sender][dst] = bsub(oldValue, amt); } emit Approval(msg.sender, dst, _allowance[msg.sender][dst]); return true; } function transfer(address dst, uint256 amt) external override returns (bool) { _move(msg.sender, dst, amt); return true; } function transferFrom( address src, address dst, uint256 amt ) external override returns (bool) { require(msg.sender == src || amt <= _allowance[src][msg.sender], "ERR_BTOKEN_BAD_CALLER"); _move(src, dst, amt); if (msg.sender != src && _allowance[src][msg.sender] != uint256(-1)) { _allowance[src][msg.sender] = bsub(_allowance[src][msg.sender], amt); emit Approval(msg.sender, dst, _allowance[src][msg.sender]); } return true; } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.6.6; import "./BNum.sol"; contract BMath is BBronze, BConst, BNum { /********************************************************************************************** // calcSpotPrice // // sP = spotPrice // // bI = tokenBalanceIn ( bI / wI ) 1 // // bO = tokenBalanceOut sP = ----------- * ---------- // // wI = tokenWeightIn ( bO / wO ) ( 1 - sF ) // // wO = tokenWeightOut // // sF = swapFee // **********************************************************************************************/ function calcSpotPrice( uint256 tokenBalanceIn, uint256 tokenWeightIn, uint256 tokenBalanceOut, uint256 tokenWeightOut, uint256 swapFee ) public pure returns (uint256 spotPrice) { uint256 numer = bdiv(tokenBalanceIn, tokenWeightIn); uint256 denom = bdiv(tokenBalanceOut, tokenWeightOut); uint256 ratio = bdiv(numer, denom); uint256 scale = bdiv(BONE, bsub(BONE, swapFee)); return (spotPrice = bmul(ratio, scale)); } /********************************************************************************************** // calcOutGivenIn // // aO = tokenAmountOut // // bO = tokenBalanceOut // // bI = tokenBalanceIn / / bI \ (wI / wO) \ // // aI = tokenAmountIn aO = bO * | 1 - | -------------------------- | ^ | // // wI = tokenWeightIn \ \ ( bI + ( aI * ( 1 - sF )) / / // // wO = tokenWeightOut // // sF = swapFee // **********************************************************************************************/ function calcOutGivenIn( uint256 tokenBalanceIn, uint256 tokenWeightIn, uint256 tokenBalanceOut, uint256 tokenWeightOut, uint256 tokenAmountIn, uint256 swapFee ) public pure returns (uint256 tokenAmountOut) { uint256 weightRatio = bdiv(tokenWeightIn, tokenWeightOut); uint256 adjustedIn = bsub(BONE, swapFee); adjustedIn = bmul(tokenAmountIn, adjustedIn); uint256 y = bdiv(tokenBalanceIn, badd(tokenBalanceIn, adjustedIn)); uint256 foo = bpow(y, weightRatio); uint256 bar = bsub(BONE, foo); tokenAmountOut = bmul(tokenBalanceOut, bar); return tokenAmountOut; } /********************************************************************************************** // calcInGivenOut // // aI = tokenAmountIn // // bO = tokenBalanceOut / / bO \ (wO / wI) \ // // bI = tokenBalanceIn bI * | | ------------ | ^ - 1 | // // aO = tokenAmountOut aI = \ \ ( bO - aO ) / / // // wI = tokenWeightIn -------------------------------------------- // // wO = tokenWeightOut ( 1 - sF ) // // sF = swapFee // **********************************************************************************************/ function calcInGivenOut( uint256 tokenBalanceIn, uint256 tokenWeightIn, uint256 tokenBalanceOut, uint256 tokenWeightOut, uint256 tokenAmountOut, uint256 swapFee ) public pure returns (uint256 tokenAmountIn) { uint256 weightRatio = bdiv(tokenWeightOut, tokenWeightIn); uint256 diff = bsub(tokenBalanceOut, tokenAmountOut); uint256 y = bdiv(tokenBalanceOut, diff); uint256 foo = bpow(y, weightRatio); foo = bsub(foo, BONE); tokenAmountIn = bsub(BONE, swapFee); tokenAmountIn = bdiv(bmul(tokenBalanceIn, foo), tokenAmountIn); return tokenAmountIn; } /********************************************************************************************** // calcPoolOutGivenSingleIn // // pAo = poolAmountOut / \ // // tAi = tokenAmountIn /// / // wI \ \\ \ wI \ // // wI = tokenWeightIn //| tAi *| 1 - || 1 - -- | * sF || + tBi \ -- \ // // tW = totalWeight pAo=|| \ \ \\ tW / // | ^ tW | * pS - pS // // tBi = tokenBalanceIn \\ ------------------------------------- / / // // pS = poolSupply \\ tBi / / // // sF = swapFee \ / // **********************************************************************************************/ function calcPoolOutGivenSingleIn( uint256 tokenBalanceIn, uint256 tokenWeightIn, uint256 poolSupply, uint256 totalWeight, uint256 tokenAmountIn, uint256 swapFee ) public pure returns (uint256 poolAmountOut) { // Charge the trading fee for the proportion of tokenAi // which is implicitly traded to the other pool tokens. // That proportion is (1- weightTokenIn) // tokenAiAfterFee = tAi * (1 - (1-weightTi) * poolFee); uint256 normalizedWeight = bdiv(tokenWeightIn, totalWeight); uint256 zaz = bmul(bsub(BONE, normalizedWeight), swapFee); uint256 tokenAmountInAfterFee = bmul(tokenAmountIn, bsub(BONE, zaz)); uint256 newTokenBalanceIn = badd(tokenBalanceIn, tokenAmountInAfterFee); uint256 tokenInRatio = bdiv(newTokenBalanceIn, tokenBalanceIn); // uint newPoolSupply = (ratioTi ^ weightTi) * poolSupply; uint256 poolRatio = bpow(tokenInRatio, normalizedWeight); uint256 newPoolSupply = bmul(poolRatio, poolSupply); poolAmountOut = bsub(newPoolSupply, poolSupply); return poolAmountOut; } /********************************************************************************************** // calcSingleInGivenPoolOut // // tAi = tokenAmountIn //(pS + pAo)\ / 1 \\ // // pS = poolSupply || --------- | ^ | --------- || * bI - bI // // pAo = poolAmountOut \\ pS / \(wI / tW)// // // bI = balanceIn tAi = -------------------------------------------- // // wI = weightIn / wI \ // // tW = totalWeight | 1 - ---- | * sF // // sF = swapFee \ tW / // **********************************************************************************************/ function calcSingleInGivenPoolOut( uint256 tokenBalanceIn, uint256 tokenWeightIn, uint256 poolSupply, uint256 totalWeight, uint256 poolAmountOut, uint256 swapFee ) public pure returns (uint256 tokenAmountIn) { uint256 normalizedWeight = bdiv(tokenWeightIn, totalWeight); uint256 newPoolSupply = badd(poolSupply, poolAmountOut); uint256 poolRatio = bdiv(newPoolSupply, poolSupply); //uint newBalTi = poolRatio^(1/weightTi) * balTi; uint256 boo = bdiv(BONE, normalizedWeight); uint256 tokenInRatio = bpow(poolRatio, boo); uint256 newTokenBalanceIn = bmul(tokenInRatio, tokenBalanceIn); uint256 tokenAmountInAfterFee = bsub(newTokenBalanceIn, tokenBalanceIn); // Do reverse order of fees charged in joinswap_ExternAmountIn, this way // ``` pAo == joinswap_ExternAmountIn(Ti, joinswap_PoolAmountOut(pAo, Ti)) ``` //uint tAi = tAiAfterFee / (1 - (1-weightTi) * swapFee) ; uint256 zar = bmul(bsub(BONE, normalizedWeight), swapFee); tokenAmountIn = bdiv(tokenAmountInAfterFee, bsub(BONE, zar)); return tokenAmountIn; } /********************************************************************************************** // calcSingleOutGivenPoolIn // // tAo = tokenAmountOut / / \\ // // bO = tokenBalanceOut / // pS - (pAi * (1 - eF)) \ / 1 \ \\ // // pAi = poolAmountIn | bO - || ----------------------- | ^ | --------- | * b0 || // // ps = poolSupply \ \\ pS / \(wO / tW)/ // // // wI = tokenWeightIn tAo = \ \ // // // tW = totalWeight / / wO \ \ // // sF = swapFee * | 1 - | 1 - ---- | * sF | // // eF = exitFee \ \ tW / / // **********************************************************************************************/ function calcSingleOutGivenPoolIn( uint256 tokenBalanceOut, uint256 tokenWeightOut, uint256 poolSupply, uint256 totalWeight, uint256 poolAmountIn, uint256 swapFee ) public pure returns (uint256 tokenAmountOut) { uint256 normalizedWeight = bdiv(tokenWeightOut, totalWeight); // charge exit fee on the pool token side // pAiAfterExitFee = pAi*(1-exitFee) uint256 poolAmountInAfterExitFee = bmul(poolAmountIn, bsub(BONE, EXIT_FEE)); uint256 newPoolSupply = bsub(poolSupply, poolAmountInAfterExitFee); uint256 poolRatio = bdiv(newPoolSupply, poolSupply); // newBalTo = poolRatio^(1/weightTo) * balTo; uint256 tokenOutRatio = bpow(poolRatio, bdiv(BONE, normalizedWeight)); uint256 newTokenBalanceOut = bmul(tokenOutRatio, tokenBalanceOut); uint256 tokenAmountOutBeforeSwapFee = bsub(tokenBalanceOut, newTokenBalanceOut); // charge swap fee on the output token side //uint tAo = tAoBeforeSwapFee * (1 - (1-weightTo) * swapFee) uint256 zaz = bmul(bsub(BONE, normalizedWeight), swapFee); tokenAmountOut = bmul(tokenAmountOutBeforeSwapFee, bsub(BONE, zaz)); return tokenAmountOut; } /********************************************************************************************** // calcPoolInGivenSingleOut // // pAi = poolAmountIn // / tAo \\ / wO \ \ // // bO = tokenBalanceOut // | bO - -------------------------- |\ | ---- | \ // // tAo = tokenAmountOut pS - || \ 1 - ((1 - (tO / tW)) * sF)/ | ^ \ tW / * pS | // // ps = poolSupply \\ -----------------------------------/ / // // wO = tokenWeightOut pAi = \\ bO / / // // tW = totalWeight ------------------------------------------------------------- // // sF = swapFee ( 1 - eF ) // // eF = exitFee // **********************************************************************************************/ function calcPoolInGivenSingleOut( uint256 tokenBalanceOut, uint256 tokenWeightOut, uint256 poolSupply, uint256 totalWeight, uint256 tokenAmountOut, uint256 swapFee ) public pure returns (uint256 poolAmountIn) { // charge swap fee on the output token side uint256 normalizedWeight = bdiv(tokenWeightOut, totalWeight); //uint tAoBeforeSwapFee = tAo / (1 - (1-weightTo) * swapFee) ; uint256 zoo = bsub(BONE, normalizedWeight); uint256 zar = bmul(zoo, swapFee); uint256 tokenAmountOutBeforeSwapFee = bdiv(tokenAmountOut, bsub(BONE, zar)); uint256 newTokenBalanceOut = bsub(tokenBalanceOut, tokenAmountOutBeforeSwapFee); uint256 tokenOutRatio = bdiv(newTokenBalanceOut, tokenBalanceOut); //uint newPoolSupply = (ratioTo ^ weightTo) * poolSupply; uint256 poolRatio = bpow(tokenOutRatio, normalizedWeight); uint256 newPoolSupply = bmul(poolRatio, poolSupply); uint256 poolAmountInAfterExitFee = bsub(poolSupply, newPoolSupply); // charge exit fee on the pool token side // pAi = pAiAfterExitFee/(1-exitFee) poolAmountIn = bdiv(poolAmountInAfterExitFee, bsub(BONE, EXIT_FEE)); return poolAmountIn; } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.6.6; import "./BConst.sol"; // Core contract; can't be changed. So disable solhint (reminder for v2) /* solhint-disable private-vars-leading-underscore */ contract BNum is BConst { function btoi(uint256 a) internal pure returns (uint256) { return a / BONE; } function bfloor(uint256 a) internal pure returns (uint256) { return btoi(a) * BONE; } function badd(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "ERR_ADD_OVERFLOW"); return c; } function bsub(uint256 a, uint256 b) internal pure returns (uint256) { (uint256 c, bool flag) = bsubSign(a, b); require(!flag, "ERR_SUB_UNDERFLOW"); return c; } function bsubSign(uint256 a, uint256 b) internal pure returns (uint256, bool) { if (a >= b) { return (a - b, false); } else { return (b - a, true); } } function bmul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c0 = a * b; require(a == 0 || c0 / a == b, "ERR_MUL_OVERFLOW"); uint256 c1 = c0 + (BONE / 2); require(c1 >= c0, "ERR_MUL_OVERFLOW"); uint256 c2 = c1 / BONE; return c2; } function bdiv(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "ERR_DIV_ZERO"); uint256 c0 = a * BONE; require(a == 0 || c0 / a == BONE, "ERR_DIV_INTERNAL"); // bmul overflow uint256 c1 = c0 + (b / 2); require(c1 >= c0, "ERR_DIV_INTERNAL"); // badd require uint256 c2 = c1 / b; return c2; } // DSMath.wpow function bpowi(uint256 a, uint256 n) internal pure returns (uint256) { uint256 z = n % 2 != 0 ? a : BONE; for (n /= 2; n != 0; n /= 2) { a = bmul(a, a); if (n % 2 != 0) { z = bmul(z, a); } } return z; } // Compute b^(e.w) by splitting it into (b^e)*(b^0.w). // Use `bpowi` for `b^e` and `bpowK` for k iterations // of approximation of b^0.w function bpow(uint256 base, uint256 exp) internal pure returns (uint256) { require(base >= MIN_BPOW_BASE, "ERR_BPOW_BASE_TOO_LOW"); require(base <= MAX_BPOW_BASE, "ERR_BPOW_BASE_TOO_HIGH"); uint256 whole = bfloor(exp); uint256 remain = bsub(exp, whole); uint256 wholePow = bpowi(base, btoi(whole)); if (remain == 0) { return wholePow; } uint256 partialResult = bpowApprox(base, remain, BPOW_PRECISION); return bmul(wholePow, partialResult); } function bpowApprox( uint256 base, uint256 exp, uint256 precision ) internal pure returns (uint256) { // term 0: uint256 a = exp; (uint256 x, bool xneg) = bsubSign(base, BONE); uint256 term = BONE; uint256 sum = term; bool negative = false; // term(k) = numer / denom // = (product(a - i - 1, i=1-->k) * x^k) / (k!) // each iteration, multiply previous term by (a-(k-1)) * x / k // continue until term is less than precision for (uint256 i = 1; term >= precision; i++) { uint256 bigK = i * BONE; (uint256 c, bool cneg) = bsubSign(a, bsub(bigK, BONE)); term = bmul(term, bmul(c, x)); term = bdiv(term, bigK); if (term == 0) break; if (xneg) negative = !negative; if (cneg) negative = !negative; if (negative) { sum = bsub(sum, term); } else { sum = badd(sum, term); } } return sum; } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.6.12; // Imports import "./libraries/BalancerSafeMath.sol"; import "./interfaces/IERC20.sol"; // Contracts /* solhint-disable func-order */ /** * @author Balancer Labs * @title Highly opinionated token implementation */ contract PCToken is IERC20 { using BalancerSafeMath for uint256; // State variables string public constant NAME = "Balancer Smart Pool"; uint8 public constant DECIMALS = 18; // No leading underscore per naming convention (non-private) // Cannot call totalSupply (name conflict) // solhint-disable-next-line private-vars-leading-underscore uint256 internal varTotalSupply; mapping(address => uint256) private _balance; mapping(address => mapping(address => uint256)) private _allowance; string private _symbol; string private _name; // Event declarations // See definitions above; must be redeclared to be emitted from this contract event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); // Function declarations /** * @notice Base token constructor * @param tokenSymbol - the token symbol */ constructor(string memory tokenSymbol, string memory tokenName) public { _symbol = tokenSymbol; _name = tokenName; } // External functions /** * @notice Getter for allowance: amount spender will be allowed to spend on behalf of owner * @param owner - owner of the tokens * @param spender - entity allowed to spend the tokens * @return uint - remaining amount spender is allowed to transfer */ function allowance(address owner, address spender) external view override returns (uint256) { return _allowance[owner][spender]; } /** * @notice Getter for current account balance * @param account - address we're checking the balance of * @return uint - token balance in the account */ function balanceOf(address account) external view override returns (uint256) { return _balance[account]; } /** * @notice Approve owner (sender) to spend a certain amount * @dev emits an Approval event * @param spender - entity the owner (sender) is approving to spend his tokens * @param amount - number of tokens being approved * @return bool - result of the approval (will always be true if it doesn't revert) */ function approve(address spender, uint256 amount) external override returns (bool) { /* In addition to the increase/decreaseApproval functions, could avoid the "approval race condition" by only allowing calls to approve when the current approval amount is 0 require(_allowance[msg.sender][spender] == 0, "ERR_RACE_CONDITION"); Some token contracts (e.g., KNC), already revert if you call approve on a non-zero allocation. To deal with these, we use the SafeApprove library and safeApprove function when adding tokens to the pool. */ _allowance[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } /** * @notice Increase the amount the spender is allowed to spend on behalf of the owner (sender) * @dev emits an Approval event * @param spender - entity the owner (sender) is approving to spend his tokens * @param amount - number of tokens being approved * @return bool - result of the approval (will always be true if it doesn't revert) */ function increaseApproval(address spender, uint256 amount) external returns (bool) { _allowance[msg.sender][spender] = BalancerSafeMath.badd(_allowance[msg.sender][spender], amount); emit Approval(msg.sender, spender, _allowance[msg.sender][spender]); return true; } /** * @notice Decrease the amount the spender is allowed to spend on behalf of the owner (sender) * @dev emits an Approval event * @dev If you try to decrease it below the current limit, it's just set to zero (not an error) * @param spender - entity the owner (sender) is approving to spend his tokens * @param amount - number of tokens being approved * @return bool - result of the approval (will always be true if it doesn't revert) */ function decreaseApproval(address spender, uint256 amount) external returns (bool) { uint256 oldValue = _allowance[msg.sender][spender]; // Gas optimization - if amount == oldValue (or is larger), set to zero immediately if (amount >= oldValue) { _allowance[msg.sender][spender] = 0; } else { _allowance[msg.sender][spender] = BalancerSafeMath.bsub(oldValue, amount); } emit Approval(msg.sender, spender, _allowance[msg.sender][spender]); return true; } /** * @notice Transfer the given amount from sender (caller) to recipient * @dev _move emits a Transfer event if successful * @param recipient - entity receiving the tokens * @param amount - number of tokens being transferred * @return bool - result of the transfer (will always be true if it doesn't revert) */ function transfer(address recipient, uint256 amount) external override returns (bool) { require(recipient != address(0), "ERR_ZERO_ADDRESS"); _move(msg.sender, recipient, amount); return true; } /** * @notice Transfer the given amount from sender to recipient * @dev _move emits a Transfer event if successful; may also emit an Approval event * @param sender - entity sending the tokens (must be caller or allowed to spend on behalf of caller) * @param recipient - recipient of the tokens * @param amount - number of tokens being transferred * @return bool - result of the transfer (will always be true if it doesn't revert) */ function transferFrom( address sender, address recipient, uint256 amount ) external override returns (bool) { require(recipient != address(0), "ERR_ZERO_ADDRESS"); require(msg.sender == sender || amount <= _allowance[sender][msg.sender], "ERR_PCTOKEN_BAD_CALLER"); _move(sender, recipient, amount); // memoize for gas optimization uint256 oldAllowance = _allowance[sender][msg.sender]; // If the sender is not the caller, adjust the allowance by the amount transferred if (msg.sender != sender && oldAllowance != uint256(-1)) { _allowance[sender][msg.sender] = BalancerSafeMath.bsub(oldAllowance, amount); emit Approval(msg.sender, recipient, _allowance[sender][msg.sender]); } return true; } // public functions /** * @notice Getter for the total supply * @dev declared external for gas optimization * @return uint - total number of tokens in existence */ function totalSupply() external view override returns (uint256) { return varTotalSupply; } // Public functions /** * @dev Returns the name of the token. * We allow the user to set this name (as well as the symbol). * Alternatives are 1) A fixed string (original design) * 2) A fixed string plus the user-defined symbol * return string(abi.encodePacked(NAME, "-", _symbol)); */ function name() external view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() external 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() external pure returns (uint8) { return DECIMALS; } // internal functions // Mint an amount of new tokens, and add them to the balance (and total supply) // Emit a transfer amount from the null address to this contract function _mint(uint256 amount) internal virtual { _balance[address(this)] = BalancerSafeMath.badd(_balance[address(this)], amount); varTotalSupply = BalancerSafeMath.badd(varTotalSupply, amount); emit Transfer(address(0), address(this), amount); } // Burn an amount of new tokens, and subtract them from the balance (and total supply) // Emit a transfer amount from this contract to the null address function _burn(uint256 amount) internal virtual { // Can't burn more than we have // Remove require for gas optimization - bsub will revert on underflow // require(_balance[address(this)] >= amount, "ERR_INSUFFICIENT_BAL"); _balance[address(this)] = BalancerSafeMath.bsub(_balance[address(this)], amount); varTotalSupply = BalancerSafeMath.bsub(varTotalSupply, amount); emit Transfer(address(this), address(0), amount); } // Transfer tokens from sender to recipient // Adjust balances, and emit a Transfer event function _move( address sender, address recipient, uint256 amount ) internal virtual { // Can't send more than sender has // Remove require for gas optimization - bsub will revert on underflow // require(_balance[sender] >= amount, "ERR_INSUFFICIENT_BAL"); _balance[sender] = BalancerSafeMath.bsub(_balance[sender], amount); _balance[recipient] = BalancerSafeMath.badd(_balance[recipient], amount); emit Transfer(sender, recipient, amount); } // Transfer from this contract to recipient // Emits a transfer event if successful function _push(address recipient, uint256 amount) internal { _move(address(this), recipient, amount); } // Transfer from recipient to this contract // Emits a transfer event if successful function _pull(address sender, uint256 amount) internal { _move(sender, address(this), amount); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.6.6; import "./BColor.sol"; contract BConst is BBronze { uint256 public constant BONE = 10**18; uint256 public constant MIN_BOUND_TOKENS = 2; uint256 public constant MAX_BOUND_TOKENS = 8; uint256 public constant MIN_FEE = BONE / 10**6; uint256 public constant MAX_FEE = BONE / 10; uint256 public constant EXIT_FEE = 0; uint256 public constant MIN_WEIGHT = BONE; uint256 public constant MAX_WEIGHT = BONE * 50; uint256 public constant MAX_TOTAL_WEIGHT = BONE * 50; uint256 public constant MIN_BALANCE = BONE / 10**12; uint256 public constant INIT_POOL_SUPPLY = BONE * 100; uint256 public constant MIN_BPOW_BASE = 1 wei; uint256 public constant MAX_BPOW_BASE = (2 * BONE) - 1 wei; uint256 public constant BPOW_PRECISION = BONE / 10**10; uint256 public constant MAX_IN_RATIO = BONE / 2; uint256 public constant MAX_OUT_RATIO = (BONE / 3) + 1 wei; } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.6.6; // abstract contract BColor { // function getColor() // external view virtual // returns (bytes32); // } contract BBronze { function getColor() external pure returns (bytes32) { return bytes32("BRONZE"); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.6.12; // Imports import "./BalancerConstants.sol"; /** * @author Balancer Labs * @title SafeMath - wrap Solidity operators to prevent underflow/overflow * @dev badd and bsub are basically identical to OpenZeppelin SafeMath; mul/div have extra checks */ library BalancerSafeMath { /** * @notice Safe addition * @param a - first operand * @param b - second operand * @dev if we are adding b to a, the resulting sum must be greater than a * @return - sum of operands; throws if overflow */ function badd(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "ERR_ADD_OVERFLOW"); return c; } /** * @notice Safe unsigned subtraction * @param a - first operand * @param b - second operand * @dev Do a signed subtraction, and check that it produces a positive value * (i.e., a - b is valid if b <= a) * @return - a - b; throws if underflow */ function bsub(uint256 a, uint256 b) internal pure returns (uint256) { (uint256 c, bool negativeResult) = bsubSign(a, b); require(!negativeResult, "ERR_SUB_UNDERFLOW"); return c; } /** * @notice Safe signed subtraction * @param a - first operand * @param b - second operand * @dev Do a signed subtraction * @return - difference between a and b, and a flag indicating a negative result * (i.e., a - b if a is greater than or equal to b; otherwise b - a) */ function bsubSign(uint256 a, uint256 b) internal pure returns (uint256, bool) { if (b <= a) { return (a - b, false); } else { return (b - a, true); } } /** * @notice Safe multiplication * @param a - first operand * @param b - second operand * @dev Multiply safely (and efficiently), rounding down * @return - product of operands; throws if overflow or rounding error */ function bmul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization (see github.com/OpenZeppelin/openzeppelin-contracts/pull/522) if (a == 0) { return 0; } // Standard overflow check: a/a*b=b uint256 c0 = a * b; require(c0 / a == b, "ERR_MUL_OVERFLOW"); // Round to 0 if x*y < BONE/2? uint256 c1 = c0 + (BalancerConstants.BONE / 2); require(c1 >= c0, "ERR_MUL_OVERFLOW"); uint256 c2 = c1 / BalancerConstants.BONE; return c2; } /** * @notice Safe division * @param dividend - first operand * @param divisor - second operand * @dev Divide safely (and efficiently), rounding down * @return - quotient; throws if overflow or rounding error */ function bdiv(uint256 dividend, uint256 divisor) internal pure returns (uint256) { require(divisor != 0, "ERR_DIV_ZERO"); // Gas optimization if (dividend == 0) { return 0; } uint256 c0 = dividend * BalancerConstants.BONE; require(c0 / dividend == BalancerConstants.BONE, "ERR_DIV_INTERNAL"); // bmul overflow uint256 c1 = c0 + (divisor / 2); require(c1 >= c0, "ERR_DIV_INTERNAL"); // badd require uint256 c2 = c1 / divisor; return c2; } /** * @notice Safe unsigned integer modulo * @dev Returns the remainder of dividing two unsigned integers. * 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). * * @param dividend - first operand * @param divisor - second operand -- cannot be zero * @return - quotient; throws if overflow or rounding error */ function bmod(uint256 dividend, uint256 divisor) internal pure returns (uint256) { require(divisor != 0, "ERR_MODULO_BY_ZERO"); return dividend % divisor; } /** * @notice Safe unsigned integer max * @dev Returns the greater of the two input values * * @param a - first operand * @param b - second operand * @return - the maximum of a and b */ function bmax(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @notice Safe unsigned integer min * @dev returns b, if b < a; otherwise returns a * * @param a - first operand * @param b - second operand * @return - the lesser of the two input values */ function bmin(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @notice Safe unsigned integer average * @dev Guard against (a+b) overflow by dividing each operand separately * * @param a - first operand * @param b - second operand * @return - the average of the two values */ function baverage(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); } /** * @notice Babylonian square root implementation * @dev (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) * @param y - operand * @return z - the square root result */ 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; } } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.6.12; // Interface declarations /* solhint-disable func-order */ interface IERC20 { // 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); // 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); // Returns the amount of tokens in existence function totalSupply() external view returns (uint256); // Returns the amount of tokens owned by account function balanceOf(address account) external view returns (uint256); // 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); // Sets amount as the allowance of spender over the caller’s tokens // Returns a boolean value indicating whether the operation succeeded // Emits an Approval event. function approve(address spender, uint256 amount) external returns (bool); // 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); // 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); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.6.12; /** * @author Balancer Labs * @title Put all the constants in one place */ library BalancerConstants { // State variables (must be constant in a library) // B "ONE" - all math is in the "realm" of 10 ** 18; // where numeric 1 = 10 ** 18 uint256 public constant BONE = 10**18; uint256 public constant MIN_WEIGHT = BONE; uint256 public constant MAX_WEIGHT = BONE * 50; uint256 public constant MAX_TOTAL_WEIGHT = BONE * 50; uint256 public constant MIN_BALANCE = BONE / 10**6; uint256 public constant MAX_BALANCE = BONE * 10**12; uint256 public constant MIN_POOL_SUPPLY = BONE * 100; uint256 public constant MAX_POOL_SUPPLY = BONE * 10**9; uint256 public constant MIN_FEE = BONE / 10**6; uint256 public constant MAX_FEE = BONE / 10; // EXIT_FEE must always be zero, or ConfigurableRightsPool._pushUnderlying will fail uint256 public constant EXIT_FEE = 0; uint256 public constant MAX_IN_RATIO = BONE / 2; uint256 public constant MAX_OUT_RATIO = (BONE / 3) + 1 wei; // Must match BConst.MIN_BOUND_TOKENS and BConst.MAX_BOUND_TOKENS uint256 public constant MIN_ASSET_LIMIT = 2; uint256 public constant MAX_ASSET_LIMIT = 8; uint256 public constant MAX_UINT = uint256(-1); }
********************************************************************************************* calcInGivenOut aI = tokenAmountIn bO = tokenBalanceOut / / bO \ (wO / wI) \ bI = tokenBalanceIn bI * | | ------------ | ^ - 1 | aO = tokenAmountOut aI = \ \ ( bO - aO ) / / wI = tokenWeightIn -------------------------------------------- wO = tokenWeightOut ( 1 - sF ) sF = swapFee /
function calcInGivenOut( uint256 tokenBalanceIn, uint256 tokenWeightIn, uint256 tokenBalanceOut, uint256 tokenWeightOut, uint256 tokenAmountOut, uint256 swapFee ) public pure returns (uint256 tokenAmountIn) { uint256 weightRatio = bdiv(tokenWeightOut, tokenWeightIn); uint256 diff = bsub(tokenBalanceOut, tokenAmountOut); uint256 y = bdiv(tokenBalanceOut, diff); uint256 foo = bpow(y, weightRatio); foo = bsub(foo, BONE); tokenAmountIn = bsub(BONE, swapFee); tokenAmountIn = bdiv(bmul(tokenBalanceIn, foo), tokenAmountIn); return tokenAmountIn; }
303,154
[ 1, 12448, 382, 6083, 1182, 28524, 2398, 279, 45, 273, 1147, 6275, 382, 28524, 540, 324, 51, 273, 1147, 13937, 1182, 9079, 342, 225, 342, 377, 324, 51, 1377, 521, 565, 261, 91, 51, 342, 341, 45, 13, 1377, 521, 5375, 324, 45, 273, 1147, 13937, 382, 1850, 324, 45, 225, 571, 225, 571, 300, 13849, 225, 571, 3602, 5411, 300, 404, 225, 571, 1171, 279, 51, 273, 1147, 6275, 1182, 565, 279, 45, 273, 3639, 521, 225, 521, 261, 324, 51, 300, 279, 51, 262, 342, 10402, 342, 5375, 341, 45, 273, 1147, 6544, 382, 6647, 19134, 13849, 5375, 341, 51, 273, 1147, 6544, 1182, 12900, 261, 404, 300, 272, 42, 262, 4766, 565, 272, 42, 273, 7720, 14667, 28524, 2868, 342, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7029, 382, 6083, 1182, 12, 203, 3639, 2254, 5034, 1147, 13937, 382, 16, 203, 3639, 2254, 5034, 1147, 6544, 382, 16, 203, 3639, 2254, 5034, 1147, 13937, 1182, 16, 203, 3639, 2254, 5034, 1147, 6544, 1182, 16, 203, 3639, 2254, 5034, 1147, 6275, 1182, 16, 203, 3639, 2254, 5034, 7720, 14667, 203, 565, 262, 1071, 16618, 1135, 261, 11890, 5034, 1147, 6275, 382, 13, 288, 203, 3639, 2254, 5034, 3119, 8541, 273, 324, 2892, 12, 2316, 6544, 1182, 16, 1147, 6544, 382, 1769, 203, 3639, 2254, 5034, 3122, 273, 324, 1717, 12, 2316, 13937, 1182, 16, 1147, 6275, 1182, 1769, 203, 3639, 2254, 5034, 677, 273, 324, 2892, 12, 2316, 13937, 1182, 16, 3122, 1769, 203, 3639, 2254, 5034, 8431, 273, 9107, 543, 12, 93, 16, 3119, 8541, 1769, 203, 3639, 8431, 273, 324, 1717, 12, 11351, 16, 605, 5998, 1769, 203, 3639, 1147, 6275, 382, 273, 324, 1717, 12, 38, 5998, 16, 7720, 14667, 1769, 203, 3639, 1147, 6275, 382, 273, 324, 2892, 12, 70, 16411, 12, 2316, 13937, 382, 16, 8431, 3631, 1147, 6275, 382, 1769, 203, 3639, 327, 1147, 6275, 382, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
claimers[0xEB079Ee381FC821B809F6110cCF7a8439C7A6870] = 0; // seq: 0 -> tkn_id: 0 claimers[0xcBD56A71a02fA7AA01bF1c94c0AeB2828Bebdc0A] = 1; // seq: 1 -> tkn_id: 1 claimers[0x9E1fDAB0FE4141fe269060f098bc7076d248cE7B] = 2; // seq: 2 -> tkn_id: 2 claimers[0x33aEA8f43D9685683b236B20a1818aFcD48204cD] = 3; // seq: 3 -> tkn_id: 3 claimers[0xFD289c26cEF8BB89A76252d9F4617cf54ce4EeBD] = 4; // seq: 4 -> tkn_id: 4 claimers[0x04bfcB7b6bc81361F14c1E2C7592d712e3b9f456] = 5; // seq: 5 -> tkn_id: 5 claimers[0x47E51859134f7d7F7379B1AEcD17a19924025A10] = 6; // seq: 6 -> tkn_id: 6 claimers[0x557159300478941E61cb60A46340F8100C590A56] = 7; // seq: 7 -> tkn_id: 7 claimers[0x7Ed273A361D6bb16833f0E563C313e205738112f] = 8; // seq: 8 -> tkn_id: 8 claimers[0x010594cA1B98ffEd9dFE3d15b749f8BaE3F21C1B] = 9; // seq: 9 -> tkn_id: 9 claimers[0x27221550A0ab5487e79460cd80C3E2aFDB48134e] = 10; // seq: 10 -> tkn_id: 10 claimers[0xF3920288e9DCCFED1AE5a05E466d5da2289062FC] = 11; // seq: 11 -> tkn_id: 11 claimers[0x8dca66E74007d8aD89aFC399d131030Ef29311eF] = 12; // seq: 12 -> tkn_id: 12 claimers[0x355B8F6059F5414AB1F69FcA34088c4aDC554B7f] = 13; // seq: 13 -> tkn_id: 13 claimers[0x020BE4338B750B85c73E598bF468E505A8eb76Ea] = 14; // seq: 14 -> tkn_id: 14 claimers[0x04B00a9F997799F4e265D8796a5F2d22C7A8b9AD] = 15; // seq: 15 -> tkn_id: 15 claimers[0xf8ab6312272E4f2eAB48ddcbD00D905e0E1bCb55] = 16; // seq: 16 -> tkn_id: 16 claimers[0x6B745dEfEE931Ee790DFe5333446eF454c45D8Cf] = 17; // seq: 17 -> tkn_id: 17 claimers[0xE770748e5781f171a0364fbd013188Bc0b33E72f] = 18; // seq: 18 -> tkn_id: 18 claimers[0xEa07596132df9F23Af112593dF0C27A0275d67E5] = 19; // seq: 19 -> tkn_id: 19 claimers[0xB22E58d1550D984b580c564E1dE7868521150988] = 20; // seq: 20 -> tkn_id: 20 claimers[0xf6EA8168a1D1D5d36f22436ad2030d397a616619] = 21; // seq: 21 -> tkn_id: 21 claimers[0x424E9cC4c00aD160c3f36b5471514a6C36a8d73e] = 22; // seq: 22 -> tkn_id: 22 claimers[0x365F34a3236c00823C7844885Ac6BF7a15430eD2] = 23; // seq: 23 -> tkn_id: 23 claimers[0x333C5dBa8179822056F2289BdeDe1B53A863F577] = 24; // seq: 24 -> tkn_id: 24 claimers[0xC9de959443935C3f3CC8E82889d5E80e8cD4a8a9] = 25; // seq: 25 -> tkn_id: 25 claimers[0xE2853A8Ba2e42e78cF8a6b063056F067307fB8f4] = 26; // seq: 26 -> tkn_id: 26 claimers[0xE8926AeBb36A046858D882309e7Aea367F8DB6Cd] = 27; // seq: 27 -> tkn_id: 27 claimers[0x7A48401B0543573D21dfEf15FC54a3E2F599CddF] = 28; // seq: 28 -> tkn_id: 28 claimers[0xd789A1a081553AF9407572711c1163F8A06b4d8F] = 29; // seq: 29 -> tkn_id: 29 claimers[0x498E96c727700a6B7aC2c4EfBd3E9a5DA4F0d137] = 30; // seq: 30 -> tkn_id: 30 claimers[0x7450Cc1b710Afd9B07EECAA19520735e1848479f] = 31; // seq: 31 -> tkn_id: 31 claimers[0x8637576EbDF8b8cb96de6a32C99cb8bDa61d2A11] = 32; // seq: 32 -> tkn_id: 32 claimers[0x77724E749eFB937CE0a78e16E1f1ec5979Cba55a] = 33; // seq: 33 -> tkn_id: 33 claimers[0x3b3D3491f9aE5125f156abA9380aFf62c201054C] = 34; // seq: 34 -> tkn_id: 34 claimers[0x782E60F18e4a3Fc21FF1409d4312ed769f70B1ef] = 35; // seq: 35 -> tkn_id: 35 claimers[0x05C4C65873473C13741c31De2d74005832A0A3d8] = 36; // seq: 36 -> tkn_id: 36 claimers[0xC5E57C099Ed08c882ea1ddF42AFf653e31Ac40df] = 37; // seq: 37 -> tkn_id: 37 claimers[0xe0dC972a92f3b463b43aB29b4F9C960983Bf948F] = 38; // seq: 38 -> tkn_id: 38 claimers[0x4348d40ee12932Aaf0e3412a3aC0598Eb22b96Ad] = 39; // seq: 39 -> tkn_id: 39 claimers[0x75Df0A4a6994AEAa458cfB15863131448fAeDf62] = 40; // seq: 40 -> tkn_id: 40 claimers[0x355e03d40211cc6b6D18ce52278e91566fF29839] = 41; // seq: 41 -> tkn_id: 41 claimers[0x9256EBe5cBcc67E28E2Cd981b835e02590aae7e4] = 42; // seq: 42 -> tkn_id: 42 claimers[0xFf0bAF087F2EE3BbcD2b8aA6560bd5B8F23D99B4] = 43; // seq: 43 -> tkn_id: 43 claimers[0x044bBDc90E1770abD48B6Ede37430b325B6A95EE] = 44; // seq: 44 -> tkn_id: 44 claimers[0x7060FE99b67e37c5fdA833edFe6135580876B996] = 45; // seq: 45 -> tkn_id: 45 claimers[0xaBfc1b7AFD818E1a44539b1EC5021C649b9Dded0] = 46; // seq: 46 -> tkn_id: 46 claimers[0xeec2f0f93e6BC7d13c5E61887aea39d233A0631f] = 47; // seq: 47 -> tkn_id: 47 claimers[0xF6d670C5C0B206f44E93dE811054F8C0b6e15905] = 48; // seq: 48 -> tkn_id: 48 claimers[0x679959449b608AF08d9419fE66D4e985c7d64D96] = 49; // seq: 49 -> tkn_id: 49 claimers[0xF5Dc9930f10Ca038De87C2FDdebe03C10aDeABDC] = 50; // seq: 50 -> tkn_id: 50 claimers[0x07587c046d4d4BD97C2d64EDBfAB1c1fE28A10E5] = 51; // seq: 51 -> tkn_id: 51 claimers[0xc674fFaD8082Aa238F15cd5a91aB1fd68aFEcEaE] = 52; // seq: 52 -> tkn_id: 52 claimers[0xF670B0Ce50B31B5BE40fD8cE84535a7D021775EF] = 53; // seq: 53 -> tkn_id: 53 claimers[0xEec4013a607D720989DB8F464361CdcF2cb7A7BD] = 54; // seq: 54 -> tkn_id: 54 claimers[0xA183B2f9d89367D935EC1Ebd1d33288a7113a971] = 55; // seq: 55 -> tkn_id: 55 claimers[0x42de824dA4C1Af884ebEdaA2352Fd4d4e00445DF] = 56; // seq: 56 -> tkn_id: 56 claimers[0x6F4440719569D61571f50c7e2B33b17E191b0654] = 57; // seq: 57 -> tkn_id: 57 claimers[0xBe671d9b29F218d711404D8F39f830eE14dAAF72] = 58; // seq: 58 -> tkn_id: 58 claimers[0xC7892093FEE029bF01D2b8C02098Cd4864bE3939] = 59; // seq: 59 -> tkn_id: 59 claimers[0x5a6541F3205D510ddB3B6dFD7b5fc5361C6fD47c] = 60; // seq: 60 -> tkn_id: 60 claimers[0xcBde85bF0b88791f902d4c18E4ad5F5CFAf76794] = 61; // seq: 61 -> tkn_id: 61 claimers[0x6A6181794DDDC287F54CF7393d81539Be2899cFd] = 62; // seq: 62 -> tkn_id: 62 claimers[0x70A2907B45A81f53b09976294B99b345B77fD134] = 63; // seq: 63 -> tkn_id: 63 claimers[0x171c3eEd74fcd74881f8Cb1de048C156D8c0EdE4] = 64; // seq: 64 -> tkn_id: 64 claimers[0x9d430D7338FF1E15f889ac90Ca992630F5150e64] = 65; // seq: 65 -> tkn_id: 65 claimers[0xd2C8CC3DcB9C79A4F85Bcad9EF4e0ccf4619d690] = 66; // seq: 66 -> tkn_id: 66 claimers[0x4e79317de3479dC23De1F1A9Ca664651bCAc8A43] = 67; // seq: 67 -> tkn_id: 67 claimers[0x35dF3706eD8779Fc4b401722754867304c11c95D] = 68; // seq: 68 -> tkn_id: 68 claimers[0xD29D862f28331705D432Dfab3f3491372E7295ad] = 69; // seq: 69 -> tkn_id: 69 claimers[0x889769e73f452E10B70414917c4d1fcd0F9a53b8] = 70; // seq: 70 -> tkn_id: 70 claimers[0x8a381C0bB4B2322a455897659cb34BC1395d3124] = 71; // seq: 71 -> tkn_id: 71 claimers[0x5319C3F016C7FC4b6770d4a8C313036da7F61290] = 72; // seq: 72 -> tkn_id: 72 claimers[0xC9D15F4E6f1b37CbF0E8068Ff84B5282edEF9707] = 73; // seq: 73 -> tkn_id: 73 claimers[0x826121D2a47c9D6e71Fd4FED082CECCc8A5381b1] = 74; // seq: 74 -> tkn_id: 74 claimers[0xb12F75B5F95022a54E6BbDd1086691635571911e] = 75; // seq: 75 -> tkn_id: 75 claimers[0xc9C56009DD643c2e6567E83F75A69C8Cc29AdeaC] = 76; // seq: 76 -> tkn_id: 76 claimers[0x40e00884ee94a5143cd9419d5DCA7Ede6730a793] = 77; // seq: 77 -> tkn_id: 77 claimers[0x78F3Aab3E918F2Bf8089EBC3698f78D3a273D6B2] = 78; // seq: 78 -> tkn_id: 78 claimers[0x7e6A5192cF2033c00efA844A353AFE1869bDF94B] = 79; // seq: 79 -> tkn_id: 79 claimers[0x3af46de2aCc78D4d4902a87618d28C0B194d7e63] = 80; // seq: 80 -> tkn_id: 80 claimers[0x0c84d74104Ac83AB98a80FB5e88F06137e842825] = 81; // seq: 81 -> tkn_id: 81 claimers[0x54280007118299877b466875B2aa6B59327DD93c] = 82; // seq: 82 -> tkn_id: 82 claimers[0x26122FE0a9966f1fA4897982782225037B3e490B] = 83; // seq: 83 -> tkn_id: 83 claimers[0xaCcE74f9dD9f3133f160417A8B554CD3Cc8a3B95] = 84; // seq: 84 -> tkn_id: 84 claimers[0xb081c44e699A895f126D09D362B1088826D12963] = 85; // seq: 85 -> tkn_id: 85 claimers[0x86c8283764C402C9E61d916096780014724C8fC9] = 86; // seq: 86 -> tkn_id: 86 claimers[0xC7857556C226b0e61bb18EB8Dd191bE7E1ee8Ad3] = 87; // seq: 87 -> tkn_id: 87 claimers[0xc45e08A07F491e778463460D52c592d11C3f761a] = 88; // seq: 88 -> tkn_id: 88 claimers[0x6F08fdC20c018121c6BE83218C95eBf42A45b571] = 89; // seq: 89 -> tkn_id: 89 claimers[0x073859cdA73a56d92a13DbE2B4e0B34dEF4756e8] = 90; // seq: 90 -> tkn_id: 90 claimers[0xA2531843629b036C6691A63bE5a91291902d42E0] = 91; // seq: 91 -> tkn_id: 91 claimers[0x4C697E1432cB49AC229241b5577284671Bae9d16] = 92; // seq: 92 -> tkn_id: 92 claimers[0x5973FFe2B9608e66A328c87c534e4Bb758618e73] = 93; // seq: 93 -> tkn_id: 93 claimers[0xcdB76A96af6eEC323a0fAC36D852b552f16C5a5F] = 94; // seq: 94 -> tkn_id: 94 claimers[0x23D623D3C6F334f55EF0DDF14FF0e05f1c88A76F] = 95; // seq: 95 -> tkn_id: 95 claimers[0x843D261B740F97BF31d09846F9d96dcC5Fd2a0D0] = 96; // seq: 96 -> tkn_id: 96 claimers[0x81cee999e0cf2DA5b420a5c02649C894F69C86bD] = 97; // seq: 97 -> tkn_id: 97 claimers[0x927a03B6606380147e38E88b1B491c7D29a62eEa] = 98; // seq: 98 -> tkn_id: 98 claimers[0x64F8eF34aC5Dc26410f2A1A0e2b4641189040231] = 99; // seq: 99 -> tkn_id: 99 claimers[0x1cFACa65bF36aE4548c9fB84d4d8A22bfBAA7B84] = 100; // seq: 100 -> tkn_id: 100 claimers[0xa069cD30b87e947Ba78e36e30E485e4926e4d176] = 101; // seq: 101 -> tkn_id: 101 claimers[0x9631200833a348641c5D08C5E146BBBFcD5367D2] = 102; // seq: 102 -> tkn_id: 102 claimers[0xb521154e8f8978f64567FE0FA7359Ab47f7363fA] = 103; // seq: 103 -> tkn_id: 103 claimers[0x9b534B88E83013B2fCE9Bb5BA813a6B96707cc8F] = 104; // seq: 104 -> tkn_id: 104 claimers[0xAaC5Ca3FEe00833ACC563FB41048179ACA8b9c07] = 105; // seq: 105 -> tkn_id: 105 claimers[0xeb0f5dce389A86a64c71F91eCE001067A9cD574E] = 106; // seq: 106 -> tkn_id: 106 claimers[0xA735E424fD55a18148BB5FE1f128Fbe30B7b56DB] = 107; // seq: 107 -> tkn_id: 107 claimers[0x85222954e2742ACe2F14f23E7694Ec1AbFD00F49] = 108; // seq: 108 -> tkn_id: 108 claimers[0x601379eF00F1879F13E4b498133b560b06bfeC36] = 109; // seq: 109 -> tkn_id: 109 claimers[0xD0c72d410D06C4C4A70Ff96beaB8432071F4d3B8] = 110; // seq: 110 -> tkn_id: 110 claimers[0xC1c2E49a3223E56f07068d836fd354e7269cBD78] = 111; // seq: 111 -> tkn_id: 111 claimers[0x88bf9430fE41AC4Dd87BeC4ba3C44012f7876e55] = 112; // seq: 112 -> tkn_id: 112 claimers[0xB8F69EC91b068E702BafCBf282feca36c585a539] = 113; // seq: 113 -> tkn_id: 113 claimers[0x6E03a79F43A6bd3b77531603990e9b39456389Ed] = 114; // seq: 114 -> tkn_id: 114 claimers[0xf522F0672107333dC549A8AcEDF62746844b65ce] = 115; // seq: 115 -> tkn_id: 115 claimers[0x4A74407858aeF6532ed771cFBb154829c53ABc47] = 116; // seq: 116 -> tkn_id: 116 claimers[0xa10e13c392EBB57adD9f23aa3792ac05D0d6dE7E] = 117; // seq: 117 -> tkn_id: 117 claimers[0xB0C054B2F0CA15fEadD4172037dC1e93b113AcC9] = 118; // seq: 118 -> tkn_id: 118 claimers[0xdC30CABcfBD95Ea2D5675002B5b00a2C499FAc12] = 119; // seq: 119 -> tkn_id: 119 claimers[0xc6c1E852ECCE4Ce5a0C93F0E68063202dA81202b] = 120; // seq: 120 -> tkn_id: 120 claimers[0x9cf39Ad673E95F292CD2060A36AE552227198a0C] = 121; // seq: 121 -> tkn_id: 121 claimers[0xbE20DFb456b7E81f691A8445d073e56602E3cefa] = 122; // seq: 122 -> tkn_id: 122 claimers[0xb29D3652ebe85C4303c87d3B728C511c4b0943E3] = 123; // seq: 123 -> tkn_id: 123 claimers[0x8CFAb48f1B6328eEAF6abaFa5Ba780550bC5109D] = 124; // seq: 124 -> tkn_id: 124 claimers[0x26cF22300E6B89437e7EEc90Bf56CadDBF4bB322] = 125; // seq: 125 -> tkn_id: 125 claimers[0x9B39dadCD266337e8F7C91dCA03fF61484a8882b] = 126; // seq: 126 -> tkn_id: 126 claimers[0x3E5e35208a84eF21d441a5365BE09BF65Af2f709] = 127; // seq: 127 -> tkn_id: 127 claimers[0x630098B792120d38dF22ecE88378d0676A3ce48c] = 128; // seq: 128 -> tkn_id: 128 claimers[0x70c5d2942b12C0aa6103129B18B3503c0610408e] = 129; // seq: 129 -> tkn_id: 129 claimers[0x91Fa472FB12Ef104d649facCE00e3bA43dE57A8D] = 130; // seq: 130 -> tkn_id: 130 claimers[0xCA755A9bD26148F18B4D2e316966E9fE915d46aC] = 131; // seq: 131 -> tkn_id: 131 claimers[0x6d6AB746901f8F7de018DCc417b6D417725B41aF] = 132; // seq: 132 -> tkn_id: 132 claimers[0x42a2D911F4C526233F203D2d156Aa5146044cB7e] = 133; // seq: 133 -> tkn_id: 133 claimers[0x0B01fE5189d95c0fa890fd6b431928B5dF58D027] = 134; // seq: 134 -> tkn_id: 134 claimers[0x84b8bfD62Bb591976429dC060ABd9bfD0eD6508B] = 135; // seq: 135 -> tkn_id: 135 claimers[0xe0d30e989810470A74Ab2D7EBaD424d76FFA8cdd] = 136; // seq: 136 -> tkn_id: 136 claimers[0x390b07DC402DcFD54D5113C8f85d90329A0141ef] = 137; // seq: 137 -> tkn_id: 137 claimers[0xfbF30C01041A372Be48217FE201a30470b0b3Ac2] = 138; // seq: 138 -> tkn_id: 138 claimers[0x973b79656F9A2B6d3F9B04E93F3C340C9f7b4C6C] = 139; // seq: 139 -> tkn_id: 139 claimers[0xDf5B7bE800A5A7A67e887C2f677Cd29a7a05b6E1] = 140; // seq: 140 -> tkn_id: 140 claimers[0x3720c491F4564429154862285E7F1f830E059065] = 141; // seq: 141 -> tkn_id: 141 claimers[0x6046D412B45dACe6c963C7c3C892AD951EC97e57] = 142; // seq: 142 -> tkn_id: 142 claimers[0x4b4E4A8bCB923783A401dc80766D7aBf5631dC0d] = 143; // seq: 143 -> tkn_id: 143 claimers[0x4460dD70a847481f63e015b689a9E226E8bD5b71] = 144; // seq: 144 -> tkn_id: 144 claimers[0x7d2D2E04f1Db8B54746eFA719CB62F32A6C84a84] = 145; // seq: 145 -> tkn_id: 145 claimers[0xdFA56E55811b6F9548F4cB876CC796a6A4071993] = 146; // seq: 146 -> tkn_id: 146 claimers[0xceCb7E46Ed153BfC38961b27Da43f8fddCbEF210] = 147; // seq: 147 -> tkn_id: 147 claimers[0xCffA068214d25B3D75f4676302C0E9390cCBBbEb] = 148; // seq: 148 -> tkn_id: 148 claimers[0x0873E406b948314E516eF6B6C618ba42B72b46C6] = 149; // seq: 149 -> tkn_id: 149 claimers[0xdC67aF6B6Ee64eec179135103b62FB68360Af860] = 150; // seq: 150 -> tkn_id: 150 claimers[0xDB7b6AA8240f527c35FD8E8c5e3a9eFc7359341d] = 151; // seq: 151 -> tkn_id: 151 claimers[0xF962e687562999a127a5b5A2ECBE99d0601564Eb] = 152; // seq: 152 -> tkn_id: 152 claimers[0x6Fa98A4254c7E9Ec681cCeb3Cb8D64a70Dbea256] = 153; // seq: 153 -> tkn_id: 153 claimers[0x5EFACb9C824eb8b0acE54a0054B7924e6c9eFaf0] = 154; // seq: 154 -> tkn_id: 154 claimers[0xaB59d30a5CE7cD360Cc333235a1deA7e3Ba3f2a1] = 155; // seq: 155 -> tkn_id: 155 claimers[0x8f1b33E27b6135BFC87Cda27Ebc90025f039F5fe] = 156; // seq: 156 -> tkn_id: 156 claimers[0x49e03A6C22602682B3Fbecc5B181F7649b1DB6Ad] = 157; // seq: 157 -> tkn_id: 157 claimers[0x0A3e7c501d685dcc9d65119e3f3A9f8F4875f8F6] = 158; // seq: 158 -> tkn_id: 158 claimers[0x2fb0d4F09e5F7E399354D8DbF602c871b84c081F] = 159; // seq: 159 -> tkn_id: 159 claimers[0xe2D18861c892f4eFbaB6b2749e2eDe16aF458A94] = 160; // seq: 160 -> tkn_id: 160 claimers[0x03aEC62437E9f1485410654E5daf4f5ad707f395] = 161; // seq: 161 -> tkn_id: 161 claimers[0xB7493191Dbf9f687D3e019cDaaDc3C52d95C87EF] = 162; // seq: 162 -> tkn_id: 162 claimers[0x6F6ed604bc1A64a385978c99310D2fc0758AF29e] = 163; // seq: 163 -> tkn_id: 163 claimers[0xF9A508D543416f530295048985e7a7C295b7F957] = 164; // seq: 164 -> tkn_id: 164 claimers[0xfB89fBaFE753873386D6E46dB066c47d8Ef857Fa] = 165; // seq: 165 -> tkn_id: 165 claimers[0xF81d36Dd1406f937323aC6C43F1be8D3b5Fd8d30] = 166; // seq: 166 -> tkn_id: 166 claimers[0x88591bc3054339708bA101116E04f0359232962F] = 167; // seq: 167 -> tkn_id: 167 claimers[0xC707b5BD687749e7e418eBDd79a387904025B02e] = 168; // seq: 168 -> tkn_id: 168 claimers[0x2cBC074df0dC03defDd1d3D985B4B1a961DB5415] = 169; // seq: 169 -> tkn_id: 169 claimers[0xf4BD7C08403250BeE1fD9D819d9DF0Ae956C3ceb] = 170; // seq: 170 -> tkn_id: 170 claimers[0x442670b5f713c61Eb9FcB4e27fcA6505815c9861] = 171; // seq: 171 -> tkn_id: 171 claimers[0xBB8135f8136425f7af9De8ee926C58D09E9525eE] = 172; // seq: 172 -> tkn_id: 172 claimers[0x5e0819Db5c0b3952149150310945752ae22745B0] = 173; // seq: 173 -> tkn_id: 173 claimers[0x3d359BE336fa4760d4399230F4067e04D1b9ed7B] = 174; // seq: 174 -> tkn_id: 174 claimers[0x136BE67011Dd5F97dcdba8d0F3b5B650aCdcaE5C] = 175; // seq: 175 -> tkn_id: 175 claimers[0x24f39151D6d8A9574D1DAC49a44F1263999D0dda] = 176; // seq: 176 -> tkn_id: 176 claimers[0x1c458B84B81B5Cc1ed226c05873E75e2Ae1dCA90] = 177; // seq: 177 -> tkn_id: 177 claimers[0xFab6e024A48d1d56D3A030E9ecC6f17F3122fB73] = 178; // seq: 178 -> tkn_id: 178 claimers[0x47b0A090Ea0D040F65F3f2Ab0fFc7824C924E144] = 179; // seq: 179 -> tkn_id: 179 claimers[0xAd2D729Ad42373A3cad2ef405197E2550f4af860] = 180; // seq: 180 -> tkn_id: 180 claimers[0x62cfc31f574F8ec9719d719709BCCE9866BEcaCd] = 181; // seq: 181 -> tkn_id: 181 claimers[0xe6BB1bEBF6829ca5240A80F7076E4CFD6Ee540ae] = 182; // seq: 182 -> tkn_id: 182 claimers[0x94d3B13745c23fB57a9634Db0b6e4f0d8b5a1053] = 183; // seq: 183 -> tkn_id: 183 claimers[0x1eF576f02107BEc448d74DcA749964013A8531e7] = 184; // seq: 184 -> tkn_id: 184 claimers[0x9b2D76f2E5E92b2C78C6e2ce07c6f86B95091964] = 185; // seq: 185 -> tkn_id: 185 claimers[0x06e9f7674a2cC609adA8dc6777f07385A238006a] = 186; // seq: 186 -> tkn_id: 186 claimers[0xC5b09ee88Cfb4FF08C8769A89B0c314FC1636b19] = 187; // seq: 187 -> tkn_id: 187 claimers[0x6595cfA52F9F91bA319386c4549039581259D57A] = 188; // seq: 188 -> tkn_id: 188 claimers[0x06B40D42b10ADBEa8CA0f12Db1E6E1e11632EB0d] = 189; // seq: 189 -> tkn_id: 189 claimers[0x98a784132CF101E8Cd2764ded4c2F246325F1fe6] = 190; // seq: 190 -> tkn_id: 190 claimers[0x693Ab9656C70BfA41443A84d4c96eAFb82d382B4] = 191; // seq: 191 -> tkn_id: 191 claimers[0xBC0147233b8a028Ed4fbcEa6CF473e30EdcfabD3] = 192; // seq: 192 -> tkn_id: 192 claimers[0xd6fE3581974330145d703B1914a6A441512992A7] = 193; // seq: 193 -> tkn_id: 193 claimers[0x935016109bFA23F810112F5Fe2862cB0c5F26bd2] = 194; // seq: 194 -> tkn_id: 194 claimers[0x2E5F97Ce8b95Ffb5B007DA1dD8fE0399679a6F23] = 195; // seq: 195 -> tkn_id: 195 claimers[0xF0fE8DA6C23c4772455F49102947157A56d22C76] = 196; // seq: 196 -> tkn_id: 196 claimers[0x03890EeB6303C86A4b44218Fbe8e8811fab0CB43] = 197; // seq: 197 -> tkn_id: 197 claimers[0x6A2e363b31D5fd9556765C8f37C1ddd2Cd480fA3] = 198; // seq: 198 -> tkn_id: 198 claimers[0x4744e7077Cf68Bca4feFFc42f3E8C1dbDF59CBaa] = 199; // seq: 199 -> tkn_id: 199 claimers[0xcEa283786F5f676d9A63599AF98D850eFEB95BaD] = 200; // seq: 200 -> tkn_id: 200 claimers[0xcb1C261dc5EF5D611c7E2F83653eA0e744654089] = 201; // seq: 201 -> tkn_id: 201 claimers[0x970393Db17dde3b234A4C17D2Be2Bad3A34249f7] = 202; // seq: 202 -> tkn_id: 202 claimers[0x84414ef56970b4F6B44673cdeC093cEE916Ad471] = 203; // seq: 203 -> tkn_id: 203 claimers[0x237b3c12D93885b65227094092013b2a792e92dd] = 204; // seq: 204 -> tkn_id: 204 claimers[0x611b3f03fc28Eb165279eADeaB258388D125e8BC] = 205; // seq: 205 -> tkn_id: 205 claimers[0x20DC3e9ECcc11075A055Aa631B64aF4b0d6dc571] = 206; // seq: 206 -> tkn_id: 206 claimers[0x5703Cf5FCE210caA2dbbFB6e88B77d126683fA76] = 207; // seq: 207 -> tkn_id: 207 claimers[0x1850AB1344493b8f66a0780c6806fe57AE7a13B4] = 208; // seq: 208 -> tkn_id: 208 claimers[0x710A169B822Bf51b8F8E6538c63deD200932BB29] = 209; // seq: 209 -> tkn_id: 209 claimers[0xA37EDEE06096F9fbA272B4943066fcd28d39Dc2d] = 210; // seq: 210 -> tkn_id: 210 claimers[0xb42FeE033AD3809cf9D1d6C1f922478F1C4A652c] = 211; // seq: 211 -> tkn_id: 211 claimers[0xebfc11fE400f2DF40B8b669845d4A3479192e859] = 212; // seq: 212 -> tkn_id: 212 claimers[0xf18210B928bc3CD75966329429131a7fD6D1b667] = 213; // seq: 213 -> tkn_id: 213 claimers[0x24d32644137e2Bc36f3d039977C83e5cD489F809] = 214; // seq: 214 -> tkn_id: 214 claimers[0x99dcfb0E41BEF20Dc9661905D4ABBD92267095Ee] = 215; // seq: 215 -> tkn_id: 215 claimers[0x1e390D5391B98F3a2d489F1a7CA646F8F336491C] = 216; // seq: 216 -> tkn_id: 216 claimers[0xBECb82002565aa5C6c4722A473AdDb5e2c909f9C] = 217; // seq: 217 -> tkn_id: 217 claimers[0x721D12Fc93F4E6509D388BF79EcE34CDcB775d62] = 218; // seq: 218 -> tkn_id: 218 claimers[0x108fF5724eC28D6066855899c4a422De4E0ae6a2] = 219; // seq: 219 -> tkn_id: 219 claimers[0x44e02B37c29d3689d95Df1C87e6153CC7e2609AA] = 220; // seq: 220 -> tkn_id: 220 claimers[0x41e309Fb027372e28907c0FCAD78DD26460Dd4c2] = 221; // seq: 221 -> tkn_id: 221 claimers[0xb827857235d4eACc540A79e9813c80E351F0dC06] = 222; // seq: 222 -> tkn_id: 222 claimers[0x8e27ac9EA29ecFfC575BbC73502D3c18848e57a0] = 223; // seq: 223 -> tkn_id: 223 claimers[0x4Fa0DE7b23BcF1e8714E0c91f7B856e5Ff99c6D0] = 224; // seq: 224 -> tkn_id: 224 claimers[0x8f6869697ab3ee78C3480D3D36B112025373438C] = 225; // seq: 225 -> tkn_id: 225 claimers[0x20fac303520CB60860065871FA213DE09D10A009] = 226; // seq: 226 -> tkn_id: 226 claimers[0x61603cD19B067B417284cf9fC94B3ebF5703824a] = 227; // seq: 227 -> tkn_id: 227 claimers[0x468769E894f0894A44B50AE363395793b17F11b3] = 228; // seq: 228 -> tkn_id: 228 claimers[0xE797B7d15f06733b9ceCF87656aD5f56945A1eBf] = 229; // seq: 229 -> tkn_id: 229 claimers[0x6592aB22faD2d91c01cCB4429F11022E2595C401] = 230; // seq: 230 -> tkn_id: 230 claimers[0x68cf193fFE134aD92C1DB0267d2062D01FEFDD06] = 231; // seq: 231 -> tkn_id: 231 claimers[0x7988E3ae0d19Eff3c8bC567CA0438F6Df3cB2813] = 232; // seq: 232 -> tkn_id: 232 claimers[0xd85bCc93d3A3E89303AAaF43c58E624D24160455] = 233; // seq: 233 -> tkn_id: 233 claimers[0xc34F0F4cf2ffD0F91DB7DFBd81B432580019F1a8] = 234; // seq: 234 -> tkn_id: 234 claimers[0xbf9fe0f5cAeE6967C874e108fE69969E09fa156c] = 235; // seq: 235 -> tkn_id: 235 claimers[0x1eE73ad65581d5Efe7430dcb5a653d5015332454] = 236; // seq: 236 -> tkn_id: 236 claimers[0xFfcef83Eb7Dd0Ec7770Ac08D8f11a87fA87E12d9] = 237; // seq: 237 -> tkn_id: 237 claimers[0x6Acb64A76e62D433a9bDCB4eeA8343Be8b3BeF48] = 238; // seq: 238 -> tkn_id: 238 claimers[0x8eCAD8Da3D1F5E0E91e8A55dd979A863CFdFCee7] = 239; // seq: 239 -> tkn_id: 239 claimers[0x572f60c0b887203324149D9C308574BcF2dfaD82] = 240; // seq: 240 -> tkn_id: 240 claimers[0xcCf70d7637AEbF9D0fa22e542Ac4082569f4ED5A] = 241; // seq: 241 -> tkn_id: 241 claimers[0x9de35B6bE7B911DEA9A4DE84E9b8a34038c6ECea] = 242; // seq: 242 -> tkn_id: 242 claimers[0x1c05141A1A0d425E92653ADfefDaFaec40681bdB] = 243; // seq: 243 -> tkn_id: 243 claimers[0x79Bc1a648aa95618bBeB3BFb2a15E3415C52FF86] = 244; // seq: 244 -> tkn_id: 244 claimers[0x5f3E1bf780cA86a7fFA3428ce571d4a6D531575D] = 245; // seq: 245 -> tkn_id: 245 claimers[0xcD426623A98E22e76758a98F7A85d4499973b37F] = 246; // seq: 246 -> tkn_id: 246 claimers[0x674901AdeB413C126a069402E751ba80F2e2152e] = 247; // seq: 247 -> tkn_id: 247 claimers[0x111f5B33389BBA60c3b16a6ae891F7D281762369] = 248; // seq: 248 -> tkn_id: 248 claimers[0x51679136e1a3407912f8fA131Bc5F611c52d9fEe] = 249; // seq: 249 -> tkn_id: 249 claimers[0xB955E56849E0875E44074C56F21CF009E2B8B6c4] = 250; // seq: 250 -> tkn_id: 250 claimers[0x3D7af9ABecFe6BdD60C8dcDFaF3b83f92DB06885] = 251; // seq: 251 -> tkn_id: 251 claimers[0x836B55F9A4A39f5b39b372a0943C782cE48C0Ef8] = 252; // seq: 252 -> tkn_id: 252 claimers[0x6412dDF748608073034090646D37D5E4CE71a4CE] = 253; // seq: 253 -> tkn_id: 253 claimers[0x924fD2357ACe38052C5f73c0bFDCd2666b02F908] = 254; // seq: 254 -> tkn_id: 254 claimers[0xFA3C94ab4Ba1fD92bf8331C7cC6aabe50074D08D] = 255; // seq: 255 -> tkn_id: 255 claimers[0xE75a37358127B089Ae9E2E23322E23bAE28ea3D9] = 256; // seq: 256 -> tkn_id: 256 claimers[0xA2Eef2A6EB56118C910101d53a860F62cf2Ec903] = 257; // seq: 257 -> tkn_id: 257 claimers[0xeA83A7a09229F7921D9a72A1f5Ff03aA5bA096E2] = 258; // seq: 258 -> tkn_id: 258 claimers[0xA0C9D9d21b2CB0400D59C70AC6CEA3e7a81F1AA7] = 259; // seq: 259 -> tkn_id: 259 claimers[0x295Cf1759Af15bE4b81D12d6Ee41C3D9A30Ad410] = 260; // seq: 260 -> tkn_id: 260 claimers[0xb8b52400D83e12e61Ea0D00A1fcD7e1E2F8d5f83] = 261; // seq: 261 -> tkn_id: 261 claimers[0x499E5938F54C3769c4208F1Bc58AEAdF13A1FF8B] = 262; // seq: 262 -> tkn_id: 262 claimers[0x2F48e68D0e507AF5a278130d375AA39f4966E452] = 263; // seq: 263 -> tkn_id: 263 claimers[0xCAB03A436F0af91cE68594f45A95D8f7f5004A14] = 264; // seq: 264 -> tkn_id: 264 claimers[0x8ee4219378c25ca2023690A71f2d337a29d67A89] = 265; // seq: 265 -> tkn_id: 265 claimers[0x00737ac98C3272Ee47014273431fE189047524e1] = 266; // seq: 266 -> tkn_id: 266 claimers[0x29175A067860f9BDBDb411dB0A76F5EbDa5544fF] = 267; // seq: 267 -> tkn_id: 267 claimers[0x5bb3e01c8dDCE82AF3f6e76f46d8965176A2daEe] = 268; // seq: 268 -> tkn_id: 268 claimers[0x47F2F66729171D0b40E9fDccAbBae5d8ec2d2065] = 269; // seq: 269 -> tkn_id: 269 claimers[0x86017110100312E0C2cCc0c14A58C4bf830a7EF6] = 270; // seq: 270 -> tkn_id: 270 claimers[0x26ceA6C7a525c17027750d315aBa267b7B0bB209] = 271; // seq: 271 -> tkn_id: 271 claimers[0xa0E609533840b910208BFb4b711df62C4a6247D2] = 272; // seq: 272 -> tkn_id: 272 claimers[0x35570f310697a5C687Eb37b63B4Ae696cE0d14C0] = 273; // seq: 273 -> tkn_id: 273 claimers[0x9e0eD477f110cb75453181Cd4261D40Fa7396056] = 274; // seq: 274 -> tkn_id: 274 claimers[0xd53b873683Df491553eea6a069770144Ad30F3A9] = 275; // seq: 275 -> tkn_id: 275 claimers[0x164934C2A068932b83Bbf81A66FF01825F2dc5e1] = 276; // seq: 276 -> tkn_id: 276 claimers[0x3eC7e5215984bE5FebA858c9502BD563bB135B1a] = 277; // seq: 277 -> tkn_id: 277 claimers[0x587A050489516119D39C228519536b561ff3fA93] = 278; // seq: 278 -> tkn_id: 278 claimers[0x8767149b0520f2e6A56eed33166Ff8484B3Ac058] = 279; // seq: 279 -> tkn_id: 279 claimers[0x49A3f1200730D84551d13FcBC121A6405eDe4D56] = 280; // seq: 280 -> tkn_id: 280 claimers[0xc206014aAf21E07ae5868730098D919F99d79616] = 281; // seq: 281 -> tkn_id: 281 claimers[0x38878917a3EC081c4C78dde8Dd49F43eE10CAf12] = 282; // seq: 282 -> tkn_id: 282 claimers[0x2FfF3F5b8560407781dFCb04a068D7635A179EFE] = 283; // seq: 283 -> tkn_id: 283 claimers[0x56256Df5A901D0B566C1944D4307E2e4Efb23838] = 284; // seq: 284 -> tkn_id: 284 claimers[0x280b8503E2927060120391baf51733E357B190eb] = 285; // seq: 285 -> tkn_id: 285 claimers[0x8C0Da5cc7524Ed8a3f6C79B07aC43081F5A54975] = 286; // seq: 286 -> tkn_id: 286 claimers[0xdE4f8a84929bF5185c03697444D8ddb8ae852116] = 287; // seq: 287 -> tkn_id: 287 claimers[0x8BB01a948ABAC1758E3ED59621f1CD7d90C8FF8C] = 288; // seq: 288 -> tkn_id: 288 claimers[0x59B7759338666625957B1Ef4482DeBd5da1a6091] = 289; // seq: 289 -> tkn_id: 289 claimers[0xD63ba61D2f3C3f108a3C54B987e9435aFB715Cc5] = 290; // seq: 290 -> tkn_id: 290 claimers[0x9f8eF2849133286860A8216cA11359381706Fa4a] = 291; // seq: 291 -> tkn_id: 291 claimers[0x125EaE40D9898610C926bb5fcEE9529D9ac885aF] = 292; // seq: 292 -> tkn_id: 292 claimers[0xB4Ae4070a56624A7c99B438664853D0f454BE116] = 293; // seq: 293 -> tkn_id: 293 claimers[0xb651Ad89b16cca4bD6FE8b4C0Bc3481b15F779c1] = 294; // seq: 294 -> tkn_id: 294 claimers[0x0F193c91a7F3B41Db23d1ab0eeD96003b9f62Ca8] = 295; // seq: 295 -> tkn_id: 295 claimers[0x09A221b474B51e530f20C727d519e243207E128B] = 296; // seq: 296 -> tkn_id: 296 claimers[0x6ea3A5faA3788814262bB1b3a5c0b82d3d24fCA6] = 297; // seq: 297 -> tkn_id: 297 claimers[0xfDf9EAfF221dB644Eb5acCA77Fe72B6553FFbDc9] = 298; // seq: 298 -> tkn_id: 298 claimers[0xb6ccBc7252a4576387d7AF08E603A330950477c5] = 299; // seq: 299 -> tkn_id: 299 claimers[0xB248B3309e31Ca924449fd2dbe21862E9f1accf5] = 300; // seq: 300 -> tkn_id: 300 claimers[0x53d9Bfc075ed4Adb207ed0C95f230A2387Bb001c] = 301; // seq: 301 -> tkn_id: 301 claimers[0x36870b333D653A201d3D7a1209937fE229B7926a] = 302; // seq: 302 -> tkn_id: 302 claimers[0x8A289c7CA7224bEf1Acf234bcD92bF1b8EE5e2D4] = 303; // seq: 303 -> tkn_id: 303 claimers[0xC3aB2C2Eb604F159C842D9cAdaBBa2d6254c43d5] = 304; // seq: 304 -> tkn_id: 304 claimers[0x90C4BF2bd887E0AbC40Fb3f1fAd0d294eBb18146] = 305; // seq: 305 -> tkn_id: 305 claimers[0x0130F60bFe7EA24027eBa9894Dd4dAb331885209] = 306; // seq: 306 -> tkn_id: 306 claimers[0x83c4224A765dEE2Fc903dDed4f9A2046Ba7891E2] = 307; // seq: 307 -> tkn_id: 307 claimers[0xA86CB26efc0Cb9d0aC53a2a56292f4BCDfEa6E1a] = 308; // seq: 308 -> tkn_id: 308 claimers[0x031bE1B4fEe66C3cB66DE265172F3567a6CAb2Eb] = 309; // seq: 309 -> tkn_id: 309 claimers[0x5402C9674B5918B803A2826CCF4CE5af813fCd97] = 310; // seq: 310 -> tkn_id: 310 claimers[0xb14ae50038abBd0F5B38b93F4384e4aFE83b9350] = 311; // seq: 311 -> tkn_id: 311 claimers[0xb200d463bCD09CE93454A394a91573DcDe76Bc28] = 312; // seq: 312 -> tkn_id: 312 claimers[0x3a2C5863e401093F9F994Aa989DDFE5F3a154AbD] = 313; // seq: 313 -> tkn_id: 313 claimers[0x3cB704A5FB4428796b728DF7e4CbC67BCA1497Ae] = 314; // seq: 314 -> tkn_id: 314 claimers[0x9BEcaC41878CA0a280Edd9A6360e3beece1a21Bb] = 315; // seq: 315 -> tkn_id: 315 claimers[0x8a382bb6BF2008492268DEdC549B6Cf189a067B5] = 316; // seq: 316 -> tkn_id: 316 claimers[0x8956CBFB070e6fdf8FF8e94DcEDD665902707Dda] = 317; // seq: 317 -> tkn_id: 317 claimers[0x21B9c3830ef962aFA00e4f45d1618F61Df99C404] = 318; // seq: 318 -> tkn_id: 318 claimers[0x48A6ab900eE882f02649f565419b96C32827E29E] = 319; // seq: 319 -> tkn_id: 319 claimers[0x15041371A7aD0a8a97e5A448804dD33FD8DdE233] = 320; // seq: 320 -> tkn_id: 320 claimers[0xA9786dA5d3ABb6C404b79DF28b7f402E58eF7c5B] = 321; // seq: 321 -> tkn_id: 321 claimers[0xea0Ca6DAF5019935ecd3693688941Bdbd4A510b4] = 322; // seq: 322 -> tkn_id: 322 claimers[0xD40356b1304CD0c7Ae2a07ea45917552001b6ed9] = 323; // seq: 323 -> tkn_id: 323 claimers[0x4622fc2DaB3E3E4e1c2d67B8E1Ecf0c63b517d80] = 324; // seq: 324 -> tkn_id: 324 claimers[0xA63328aE7c2Da36133D1F2ecFB9074403667EfE4] = 325; // seq: 325 -> tkn_id: 325 claimers[0x86fce8cB12e663eD626b20E48F1e9095e930Bfa3] = 327; // seq: 326 -> tkn_id: 327 claimers[0xC28Ac85a4A2b5C7B99cA997B9c4919a7f300A2DA] = 328; // seq: 327 -> tkn_id: 328 claimers[0xCbc3906EFE25eD7CF06265f6B02e83dB67eF41AC] = 329; // seq: 328 -> tkn_id: 329 claimers[0xC64E4d5Ecda0b4D8d9255340c9E3B138c846F17F] = 330; // seq: 329 -> tkn_id: 330 claimers[0x3a434BBF72AF14Ae7cBf25c5cFA19Afe6A25510c] = 331; // seq: 330 -> tkn_id: 331 claimers[0xEC712Ce410df07c9a5a38954d1A85520410b8b83] = 332; // seq: 331 -> tkn_id: 332 claimers[0x640Ea12876aE881c578ab5C953F30e6cA2F6b51A] = 333; // seq: 332 -> tkn_id: 333 claimers[0x266EEC4B2968fd655C362B1D1c5a9269caD4aA42] = 334; // seq: 333 -> tkn_id: 334 claimers[0x79ff9938d22D39d6FA7E774637FA6D5cfc0897Cc] = 335; // seq: 334 -> tkn_id: 335 claimers[0xE513dE08500025E9a15E0cb54B232169e5c169BC] = 336; // seq: 335 -> tkn_id: 336 claimers[0xe7F032d734Dd90F2011E46170493f4Ad335C583f] = 337; // seq: 336 -> tkn_id: 337 claimers[0x20a6Dab0c262c28CD9ed6F96A08309220a60601A] = 338; // seq: 337 -> tkn_id: 338 claimers[0xB7da649e07D3C3406427124672bCf3318E4eAD88] = 339; // seq: 338 -> tkn_id: 339 claimers[0xA3D4f816c0deB4Da228D931D419cE2Deb7A362a8] = 340; // seq: 339 -> tkn_id: 340 claimers[0xDd0A2bE389cfc5f1Eb7BDa07147F3ddEa5692821] = 341; // seq: 340 -> tkn_id: 341 claimers[0x1C4Cdcd7f746Dd1d513fae4eBdC9abbca5068924] = 342; // seq: 341 -> tkn_id: 342 claimers[0xf13D7625bf1838c14Af331c5A5014Aea39CC9A8c] = 343; // seq: 342 -> tkn_id: 343 claimers[0xe2C05bB4ffAFfcc3d32039C9153b2bF8aa1C0613] = 344; // seq: 343 -> tkn_id: 344 claimers[0xB9e39A55b80f449cB847Aa679807b7e3309d22C3] = 345; // seq: 344 -> tkn_id: 345 claimers[0x2Bd69F9dFAf984aa97c2f443F4CAa4067B223f1A] = 346; // seq: 345 -> tkn_id: 346 claimers[0xeDf32B8F98D464b9Eb29C74202e6Baae28134fC7] = 347; // seq: 346 -> tkn_id: 347 claimers[0x59aD1737E02556E64487969c844646Dd3B451251] = 348; // seq: 347 -> tkn_id: 348 claimers[0x6895335Bbef92D7cE00465Ebe625fb84cc5fEc2F] = 349; // seq: 348 -> tkn_id: 349 claimers[0xbcBa4F18f391b9E7914E586a7477fbf56E42e90e] = 350; // seq: 349 -> tkn_id: 350 claimers[0x4fee40110623aD02BA4d76c76157D01e22DFbA72] = 351; // seq: 350 -> tkn_id: 351 claimers[0xa8f530a2F1cc7eCeba848BD089ffA923873a835e] = 352; // seq: 351 -> tkn_id: 352 claimers[0xC4b1bb0c1c8c29E234F1884b7787c7e14E1bC0a1] = 353; // seq: 352 -> tkn_id: 353 claimers[0xae3d939ffDc30837ba1b1fF24856e1249cDda61D] = 354; // seq: 353 -> tkn_id: 354 claimers[0x79d39642A48597A9943Cc64432bE1D50F25EFb2b] = 355; // seq: 354 -> tkn_id: 355 claimers[0x65772909024899817Fb7333EC50e4B05534e3dB1] = 356; // seq: 355 -> tkn_id: 356 claimers[0xce2C6c7c40bCe8718786484561a20fbE71416F9f] = 357; // seq: 356 -> tkn_id: 357 claimers[0x7777515751843e7cdcC47E10833E159c47777777] = 358; // seq: 357 -> tkn_id: 358 claimers[0x783a108e6bCD910d476aF96b5A49f54fE379C0eE] = 359; // seq: 358 -> tkn_id: 359 claimers[0xabF552b23902ccC9B1A36512cFaC9869a15C76F6] = 360; // seq: 359 -> tkn_id: 360 claimers[0x16c3576d3c85CBC564ac79bf5F48512ee42054f6] = 361; // seq: 360 -> tkn_id: 361 claimers[0x178025dc029CAA1ff1fEe4Bf4d2b60437ebE661c] = 362; // seq: 361 -> tkn_id: 362 claimers[0x68F38334ca94956AfC2DE794A1E8536eb055bECB] = 363; // seq: 362 -> tkn_id: 363 claimers[0x276A235D7822694C9738f441C777938eb6Dd2a7b] = 364; // seq: 363 -> tkn_id: 364 claimers[0xc7B5D7057BB3A77d8FFD89D3065Ad14E1E9deD7c] = 365; // seq: 364 -> tkn_id: 365 claimers[0xCf57A3b1C076838116731FDe404492D9d168747A] = 366; // seq: 365 -> tkn_id: 366 claimers[0x7eea2a6FEA12a60b67EFEAf4DbeCf028A2F41a2d] = 367; // seq: 366 -> tkn_id: 367 claimers[0xa72ce2426D395380756401fCA476cC6C3CF47354] = 368; // seq: 367 -> tkn_id: 368 claimers[0x5CaF975D380a6f8A4f25Dc9b5A1fC41eb714eF7C] = 369; // seq: 368 -> tkn_id: 369 claimers[0x764d8B7F4d75803008ACaec24745D978A7dF84D6] = 370; // seq: 369 -> tkn_id: 370 claimers[0x0BDfAA5444Eb0fd5E03bCB1ab34e10044971bF39] = 371; // seq: 370 -> tkn_id: 371 claimers[0x0DAddc0280b9B312c56d187BBBDDAFDcdB68Fe02] = 372; // seq: 371 -> tkn_id: 372 claimers[0x299B907233549Fa565d1C8D92429E2c6182F13B8] = 373; // seq: 372 -> tkn_id: 373 claimers[0xA30C27Bcc7A75045385941C7cF9415893ff45b1A] = 374; // seq: 373 -> tkn_id: 374 claimers[0x4E2ECa32c15389F8da0883d11E11d490A3e06d4D] = 375; // seq: 374 -> tkn_id: 375 claimers[0x9318Db19966B03fe3b2DC6A4A59d46d8C98f7c9f] = 376; // seq: 375 -> tkn_id: 376 claimers[0x524b7c9B4cA33ba72445DFd2d6404C81d8D1F2E3] = 377; // seq: 376 -> tkn_id: 377 claimers[0xB862D5e30DE97368801bDC24A53aD90F56a9C068] = 378; // seq: 377 -> tkn_id: 378 claimers[0x53C2A37BEef67489f0a19890F5fEb2Fc53384C72] = 379; // seq: 378 -> tkn_id: 379 claimers[0xe926545EA364a95473905e882f8559a091FD7383] = 380; // seq: 379 -> tkn_id: 380 claimers[0x73c18BEeF34332e91E94250781DcE0BA996c072b] = 381; // seq: 380 -> tkn_id: 381 claimers[0x5451C07DEb2bc853081716632c7827e84bd2e24A] = 382; // seq: 381 -> tkn_id: 382 claimers[0x47dab6E0FEA8f3664b201EBEA2700458C25C66cc] = 383; // seq: 382 -> tkn_id: 383 claimers[0x3dE345e0042cBBDa5e1080691d9439DC1A35933e] = 384; // seq: 383 -> tkn_id: 384 claimers[0xb8AB7c24f5C52Ed17f1f38Eb8286Bd1888D3D68e] = 385; // seq: 384 -> tkn_id: 385 claimers[0xd7201730Fd6d8769ca80c3a77905a397F8732e90] = 386; // seq: 385 -> tkn_id: 386 claimers[0x256b09f7Ae7d5fec8C8ac77184CA09F867BbBf4c] = 387; // seq: 386 -> tkn_id: 387 claimers[0xDaE5D2ceaC11c0a9F15f745e55744C108a5fb266] = 388; // seq: 387 -> tkn_id: 388 claimers[0x2A967A09304B8334BE70cF9D9E10469127E4303D] = 389; // seq: 388 -> tkn_id: 389 claimers[0xAA504202187c620EeB0B1434695b32a2eE24E043] = 390; // seq: 389 -> tkn_id: 390 claimers[0xA8231e126fB45EdFE070d72583774Ee3FE55EcD9] = 391; // seq: 390 -> tkn_id: 391 claimers[0x015b2738D14Da6d7775444E6Cf0b46E722F45aDD] = 392; // seq: 391 -> tkn_id: 392 claimers[0x56cbBaF7F1eB247c4F526fE3e2109f19e5f63994] = 393; // seq: 392 -> tkn_id: 393 claimers[0xA0f31bF73eD86ab881d6E8f5Ae2E4Ec9E81f04Fc] = 394; // seq: 393 -> tkn_id: 394 claimers[0x3A484fc4E7873Bd79D0B9B05ED6067A549eC9f49] = 395; // seq: 394 -> tkn_id: 395 claimers[0x184cfB6915daDb4536D397fEcfA4fD8A18823719] = 396; // seq: 395 -> tkn_id: 396 claimers[0xee86f2BAFC7e33EFDD5cf3970e33C361Cb7aDeD9] = 397; // seq: 396 -> tkn_id: 397 claimers[0x4D3c3E7F5EBae3aCBac78EfF2457a842Ab86577e] = 398; // seq: 397 -> tkn_id: 398 claimers[0xf459958a3e43A9d08e7ce4567cd6Bba37304642D] = 399; // seq: 398 -> tkn_id: 399 claimers[0xC1e4B49876c3D4b5F4DfbF635a31a7CAE738d8D4] = 400; // seq: 399 -> tkn_id: 400 claimers[0xc09e52C36BeFcF605a7f308824395753Bb5693CE] = 401; // seq: 400 -> tkn_id: 401 claimers[0xC383395EdCf07183c5190833859751836755E549] = 402; // seq: 401 -> tkn_id: 402 claimers[0x41D43f1fb956351F39925C17b6639DFe198c6E58] = 403; // seq: 402 -> tkn_id: 403 claimers[0xea52Fb67C64EE535e6493bDA464c1776B029E68a] = 404; // seq: 403 -> tkn_id: 404 claimers[0x769Fcbe8A35D6B2E30cbD16B32CA6BA7D124FA5c] = 405; // seq: 404 -> tkn_id: 405 claimers[0x2733Deb98cC52921701A1FA018Bc084E017D6C2B] = 406; // seq: 405 -> tkn_id: 406 claimers[0xFB81414570E338E28C98417c38A3A5c9C6503516] = 407; // seq: 406 -> tkn_id: 407 claimers[0x0bEb916792e88Bc018a60403c2A5B3E88bc94E8C] = 408; // seq: 407 -> tkn_id: 408 claimers[0xC9A9943A2230ae6b3423F00d1435f96950f82B23] = 409; // seq: 408 -> tkn_id: 409 claimers[0x65028EEE0F81E76A8Ffc39721eD4c18643cB9A4C] = 410; // seq: 409 -> tkn_id: 410 claimers[0x0e173d5df309000cA6bC3a48064b6dA90642C088] = 411; // seq: 410 -> tkn_id: 411 claimers[0x5dB10F169d7193cb5A9A1A787b06E973e0c670eA] = 412; // seq: 411 -> tkn_id: 412 claimers[0xa6eB69bCA906F5A463E4BEdaf98cFb6eF4AeAF5f] = 413; // seq: 412 -> tkn_id: 413 claimers[0x053AA35E51A8Ef8F43fd0d89dd24Ef40a8C91556] = 414; // seq: 413 -> tkn_id: 414 claimers[0x90DB49Ac2f9d9ae14E9adBB4666bBbc890495fb3] = 415; // seq: 414 -> tkn_id: 415 claimers[0xaF85Cf9A8a0AfAE6071aaBe8856f487C1790Ef32] = 416; // seq: 415 -> tkn_id: 416 claimers[0x1d69159798e83d8eB39842367869D52be5EeD87d] = 417; // seq: 416 -> tkn_id: 417 claimers[0xD0A5ce6b581AFF1813f4376eF50A155e952218D8] = 418; // seq: 417 -> tkn_id: 418 claimers[0x915af533bFC63D46ffD38A0589AF6d2f5AC86B23] = 419; // seq: 418 -> tkn_id: 419 claimers[0xe5abD6895aE353496E4b44E212085B91bCD3274A] = 420; // seq: 419 -> tkn_id: 420 claimers[0x14b0b438A346d8555148e3765Cc3E6FE911546D5] = 421; // seq: 420 -> tkn_id: 421 claimers[0xAa7708065610BeEFB8e1aead8E27510bf5d5C3A8] = 422; // seq: 421 -> tkn_id: 422 claimers[0x2800D157C4D77F234AC49f401076BBf79fef6fF3] = 423; // seq: 422 -> tkn_id: 423 claimers[0xF33782f1384a931A3e66650c3741FCC279a838fC] = 424; // seq: 423 -> tkn_id: 424 claimers[0x20B5db733532A6a36B41BFE62bD177B6FA9622e7] = 425; // seq: 424 -> tkn_id: 425 claimers[0xa086F516d4591c0D2c67d9ABcbfee0D598eB3988] = 426; // seq: 425 -> tkn_id: 426 claimers[0x572AD2e517CBC0E7EA60948DfF099Fafde9d8022] = 427; // seq: 426 -> tkn_id: 427 claimers[0xbE3164647cfF2518931454DD55FD2bA0C7B29297] = 428; // seq: 427 -> tkn_id: 428 claimers[0x239D5c0CfD4ED667ad78Cdc7F3DCB17D09740a0d] = 429; // seq: 428 -> tkn_id: 429 claimers[0xdAD3f7d6D9Fa998c804b0BD7Cc02FA0C243bEE17] = 430; // seq: 429 -> tkn_id: 430 claimers[0x96C7fcC0d3426714Bf62c4B508A0fBADb7A9B692] = 431; // seq: 430 -> tkn_id: 431 claimers[0x2c46bc2F0b73b75248567CA25db6CA83d56dEA65] = 432; // seq: 431 -> tkn_id: 432 claimers[0x2220d8b0539CB4613A5112856a9B192b380be37f] = 433; // seq: 432 -> tkn_id: 433 claimers[0xcC3ee4f6002B17E741f6d753Da3DBB0c0EFbbC0F] = 434; // seq: 433 -> tkn_id: 434 claimers[0x6E9B220B915b6E18A1C36B6B7bcc5bde9838142B] = 435; // seq: 434 -> tkn_id: 435 claimers[0x3d370054667010D228822b60eA8e92A6491c6f13] = 436; // seq: 435 -> tkn_id: 436 claimers[0xd63613F91a6EFF9f479e052dF2c610108FE48048] = 437; // seq: 436 -> tkn_id: 437 claimers[0x0be82Fe1422d6D5cA74fd73A37a6C89636235B25] = 438; // seq: 437 -> tkn_id: 438 claimers[0xfA79F7c2601a4C2A40C80eC10cE0667988B0FC36] = 439; // seq: 438 -> tkn_id: 439 claimers[0x3786F2693B144d14b205B7CD719c71A95ffB8F82] = 440; // seq: 439 -> tkn_id: 440 claimers[0x88D09b28739B6C301be94b76Aab0554bde287D50] = 441; // seq: 440 -> tkn_id: 441 claimers[0xbdB1aD55728Be046C4eb3C24406c60fA8EB40A4F] = 442; // seq: 441 -> tkn_id: 442 claimers[0xF77bC2475ad7D0830753C87C375Fe9dF443dD1f5] = 443; // seq: 442 -> tkn_id: 443 claimers[0x0667b277d3CC7F8e0dc0c2106bD546214dB7B4B7] = 444; // seq: 443 -> tkn_id: 444 claimers[0x87698583DB020081DA64713E7A75D6276F970Ea6] = 445; // seq: 444 -> tkn_id: 445 claimers[0x49CEC0c4ec7B40e10aD2c46E4c863Fff9f0F8D09] = 446; // seq: 445 -> tkn_id: 446 claimers[0xAfc6bcc856644AA00A2e076e2EdDbA607326c517] = 447; // seq: 446 -> tkn_id: 447 claimers[0x8D8d7315f31C04c96E5c3944eE332599C3533131] = 448; // seq: 447 -> tkn_id: 448 claimers[0xc65D945aaAB7D2928A0bd9a51602451BD24E17cb] = 449; // seq: 448 -> tkn_id: 449 claimers[0x3A79caC51e770a84E8Cb5155AAafAA9CaC83F429] = 450; // seq: 449 -> tkn_id: 450 claimers[0x2b2248E158Bfe5710b82404b6Af9ceD5aE90b859] = 451; // seq: 450 -> tkn_id: 451 claimers[0x9c3C4d995BF0Cea85edF50ec552D1eEb879e1a47] = 452; // seq: 451 -> tkn_id: 452 claimers[0x93C927A836bF0CD6f92760ECB05E46A67D8A3FB3] = 453; // seq: 452 -> tkn_id: 453 claimers[0xaa8404c21A938551aD09719392a0Ed282538305F] = 454; // seq: 453 -> tkn_id: 454 claimers[0x03bE7e943c99eaF1630033adf8A9B8DE68e25D6E] = 455; // seq: 454 -> tkn_id: 455 claimers[0x2a8D7c661828c4e312Cde8e2CD8Ab63a1aCAD396] = 456; // seq: 455 -> tkn_id: 456 claimers[0xBeB6Bdb317bf0D7a3b3dA1D39bD07313b35c983f] = 457; // seq: 456 -> tkn_id: 457 claimers[0xf1180102846D1b587cD326358Bc1D54fC7441ec3] = 458; // seq: 457 -> tkn_id: 458 claimers[0x931ddC55Ea7074a190ded7429E82dfAdFeDC0269] = 459; // seq: 458 -> tkn_id: 459 claimers[0x871cAEF9d39e05f76A3F6A3Bb7690168f0188925] = 460; // seq: 459 -> tkn_id: 460 claimers[0x131BA338c35b0954Fd483C527852828B378666Db] = 461; // seq: 460 -> tkn_id: 461 claimers[0xADeA561251c72328EDf558CB0eBE536ae864fD74] = 462; // seq: 461 -> tkn_id: 462 claimers[0xdCB7Bf063D73FA67c987f459D885b3Df86061548] = 463; // seq: 462 -> tkn_id: 463 claimers[0xDaac8766ef95E86D839768F7EFf7ed972CA30628] = 464; // seq: 463 -> tkn_id: 464 claimers[0x07F3813CB3A7302eF49903f112e9543D44170a50] = 465; // seq: 464 -> tkn_id: 465 claimers[0x55E9762e2aa135584969DCd6A7d550A0FaadBcd6] = 466; // seq: 465 -> tkn_id: 466 claimers[0xca0d901CF1dddf950431849B2F200524C12baC1D] = 467; // seq: 466 -> tkn_id: 467 claimers[0x315a99D2403C2bdb04265ce74Ca375b513C7f0a4] = 468; // seq: 467 -> tkn_id: 468 claimers[0x05BE7F4a524a7169F66348d3A71CFc49654961EB] = 469; // seq: 468 -> tkn_id: 469 claimers[0x8D88F01D183DDfD30782E565fdBcD85c14413cAF] = 470; // seq: 469 -> tkn_id: 470 claimers[0xFb4ad2136d64C83762D9AcbAb12837ed0d47c1D4] = 471; // seq: 470 -> tkn_id: 471 claimers[0xD3Edeb449B2F93210D19e19A9E7f348998F437EC] = 472; // seq: 471 -> tkn_id: 472 claimers[0x9a1094393c60476FF2875E581c07CDbb51B8d63e] = 473; // seq: 472 -> tkn_id: 473 claimers[0x4F14B92dB4021d1545d396ba529c02464C692044] = 474; // seq: 473 -> tkn_id: 474 claimers[0xbb8b593aE36FaDFE56c20A054Bc095DFCcd000Ec] = 475; // seq: 474 -> tkn_id: 475 claimers[0xC0FFd04728F3D0Dd3d355d1DdE4F65740565A640] = 476; // seq: 475 -> tkn_id: 476 claimers[0x236D33B5CdBC9b44Ab2C5B0D3B43B3C365f7f455] = 477; // seq: 476 -> tkn_id: 477 claimers[0x31981027E99D7322bbfAAdC056e26c908b1A4eAf] = 478; // seq: 477 -> tkn_id: 478 claimers[0xa7A2FeB7fe3414832fc8DC0f55dcd66F04536C56] = 479; // seq: 478 -> tkn_id: 479 claimers[0x68E9496F98652a2FcFcA5a81B44A03D177567844] = 480; // seq: 479 -> tkn_id: 480 claimers[0x21130c9b9D00BcB6cDAF24d0E85809cf96251F35] = 481; // seq: 480 -> tkn_id: 481 claimers[0x0Ab49FcBdcf3D8d369D0C9E7Cd620e668c98C296] = 482; // seq: 481 -> tkn_id: 482 claimers[0x811Fc30D7eD89438E2FFad5df1Bd8F7560F41a37] = 483; // seq: 482 -> tkn_id: 483 claimers[0xb62C16D2D70B0121697Ed4ca4D5BAbeb5d573f8e] = 484; // seq: 483 -> tkn_id: 484 claimers[0x5E0bD50345356FdD6f3bDB7398D80e027975Ddf3] = 485; // seq: 484 -> tkn_id: 485 claimers[0x0118838575Be097D0e41E666924cd5E267ceF444] = 486; // seq: 485 -> tkn_id: 486 claimers[0x044D9739cAC0eE9aCB33D83a949ec7A4Ba342de4] = 487; // seq: 486 -> tkn_id: 487 claimers[0x3d8D1C9A6Db0C49774f28fE2E81C0083032522Be] = 488; // seq: 487 -> tkn_id: 488 claimers[0xCB95dC3DF3007330A5C6Ea57a7fBD0024F3560C0] = 489; // seq: 488 -> tkn_id: 489 claimers[0xcafEfe36aDE7561bb28037Ac8807AA4a5b22102e] = 490; // seq: 489 -> tkn_id: 490 claimers[0x2230A3fa220B0234E468a52389272d239CEB809d] = 491; // seq: 490 -> tkn_id: 491 claimers[0xA504BcF03748740b49dDA8b26BF3081D9dcd3114] = 492; // seq: 491 -> tkn_id: 492 claimers[0x357494619Aa4419437D10970E9F953c26C1aF51d] = 493; // seq: 492 -> tkn_id: 493 claimers[0x57AAeAB03d27B0EF9Dd45c79F3dd486b912e4Ed9] = 494; // seq: 493 -> tkn_id: 494 claimers[0x0753B66aA5652bA60F1b33C34Ee1E9bD85E0dC88] = 495; // seq: 494 -> tkn_id: 495 claimers[0xbbd85FE0869340D1458d593fF8379aed857C00aC] = 496; // seq: 495 -> tkn_id: 496 claimers[0x84c51a0237Bda0b4b0F820e03DB70a035e26Dd15] = 497; // seq: 496 -> tkn_id: 497 claimers[0x22827dF138Fb40F2A80c00245aF2177b5eB71F38] = 498; // seq: 497 -> tkn_id: 498 claimers[0x0Acc621E4956d1102DE13F1D8ED9B80dC98b8F5f] = 499; // seq: 498 -> tkn_id: 499 claimers[0xff8994c6a99a44b708dEA64897De7E4DD0Fb3939] = 500; // seq: 499 -> tkn_id: 500 claimers[0x2a0948cfFe88e193F453084A8702b59D8FeC6D5a] = 501; // seq: 500 -> tkn_id: 501 claimers[0x5a90f33f31924f0b502602C7f6a00F43EAaB7C0A] = 502; // seq: 501 -> tkn_id: 502 claimers[0x66251D264ED22E4eD362EA0FBDc3D96028786e85] = 503; // seq: 502 -> tkn_id: 503 claimers[0x76B8AeCDaC440a1f3bf300DE29bd0A652B67a94F] = 504; // seq: 503 -> tkn_id: 504 claimers[0x0534Ce5CbB832140d3B6a372217eEA65c4d8A65c] = 505; // seq: 504 -> tkn_id: 505 claimers[0x59897640bBF64426747BDf14bA4B9509c7404f77] = 506; // seq: 505 -> tkn_id: 506 claimers[0x7ACB9314364c7Fe3b01bc6B41E95eF3D360456d9] = 507; // seq: 506 -> tkn_id: 507 claimers[0xd2f97ADbe4bF3eaB86cA464c8C652977Ec72E51f] = 508; // seq: 507 -> tkn_id: 508 claimers[0xEc8c50223E785C3Ff21fd9F9ABafAcfB1e2215FC] = 509; // seq: 508 -> tkn_id: 509 claimers[0x843E8e7996F10d397b7C8b6251A035518D10D437] = 510; // seq: 509 -> tkn_id: 510 claimers[0x190f7a8e33E07d1230FA8C42bea1392606D02808] = 511; // seq: 510 -> tkn_id: 511 claimers[0x5c33ed519972c7cD746D261dcbBDa8ee6F9aadA7] = 512; // seq: 511 -> tkn_id: 512 claimers[0x1A33aC98AB15Ed89147Fe0edd5B726565d7972c9] = 513; // seq: 512 -> tkn_id: 513 claimers[0x915855E0b041468A8497c2E1D0959780904dA171] = 514; // seq: 513 -> tkn_id: 514 claimers[0x2Ee0781c7CE1f1BDe71fD2010F06448420873e58] = 515; // seq: 514 -> tkn_id: 515 claimers[0xC8ab8461129fEaE84c4aB3929948235106514AdF] = 516; // seq: 515 -> tkn_id: 516 claimers[0x75daA09CE22eD9e4e27cB1f2D0251647831642A6] = 517; // seq: 516 -> tkn_id: 517 claimers[0xA31D7fe5acCBBA9795b4B2f8c1b58abE90590D6d] = 518; // seq: 517 -> tkn_id: 518 claimers[0x85d03E980A35517906a3665866E8a255C0212918] = 519; // seq: 518 -> tkn_id: 519 claimers[0x02A325603C41c24E1897C74840B5C78950223366] = 520; // seq: 519 -> tkn_id: 520 claimers[0xF2CA16da81687313AE2d8d3DD122ABEF11e1f68f] = 521; // seq: 520 -> tkn_id: 521 claimers[0xba028A2a6097f7Da63866965B7f045F166aeB958] = 522; // seq: 521 -> tkn_id: 522 claimers[0x787Efe41F4C940bC8c2a0D2B1877B7Fb71bC7c04] = 523; // seq: 522 -> tkn_id: 523 claimers[0xA368bae3df1107cF22Daf0a79761EF94656D789A] = 524; // seq: 523 -> tkn_id: 524 claimers[0x67ffa298DD79AE9de27Fd63e99c15716ddc93491] = 525; // seq: 524 -> tkn_id: 525 claimers[0xD79B70C1D4Ab78Cd97d53508b5CBf0D573728980] = 526; // seq: 525 -> tkn_id: 526 claimers[0x8aA79517903E473c548A36d80f54b7669056249a] = 527; // seq: 526 -> tkn_id: 527 claimers[0xaEC4a7621BEA9F03B9A893d61e6e6EA91b33c395] = 528; // seq: 527 -> tkn_id: 528 claimers[0xF6614172a85D7cB91327bd11e4884d3C76042580] = 529; // seq: 528 -> tkn_id: 529 claimers[0x8F1B34eAF577413db89889beecdb61f4cc590aC2] = 530; // seq: 529 -> tkn_id: 530 claimers[0xD85bc15495DEa1C510fE41794d0ca7818d8558f0] = 531; // seq: 530 -> tkn_id: 531 claimers[0x85b931A32a0725Be14285B66f1a22178c672d69B] = 532; // seq: 531 -> tkn_id: 532 claimers[0xCDCaDF2195c1376f59808028eA21630B361Ba9b8] = 533; // seq: 532 -> tkn_id: 533 claimers[0x32527CA6ec2B85AbaCA0fb2dd3878e5b7Bb5b370] = 534; // seq: 533 -> tkn_id: 534 claimers[0xe3fa3aefD1f122e2228fFE79EE36685215A05BCa] = 535; // seq: 534 -> tkn_id: 535 claimers[0x7AE29F334D7cb67b58df5aE2A19F360F1Fd3bE75] = 536; // seq: 535 -> tkn_id: 536 claimers[0xF29919b09037036b6f10aD7C41ADCE8677BE2F54] = 537; // seq: 536 -> tkn_id: 537 claimers[0x328824B1468f47163787d0Fa40c44a04aaaF4fD9] = 538; // seq: 537 -> tkn_id: 538 claimers[0x4d4180739775105c82627CCbf043d6d32e746dee] = 539; // seq: 538 -> tkn_id: 539 claimers[0x6372b52593537A3Be2F3752110cb709e6f213241] = 540; // seq: 539 -> tkn_id: 540 claimers[0x75187bA60caFC4A2Cb057aADdD5c9FdAc3896Cee] = 541; // seq: 540 -> tkn_id: 541 claimers[0xf5503988423F65b1d5F2263d33Ab161E889103EB] = 542; // seq: 541 -> tkn_id: 542 claimers[0x76b2e65407e9f24cE944B62DB0c82e4b61850233] = 543; // seq: 542 -> tkn_id: 543 claimers[0xDd6177ba0f8C5F15DB178452585BB52A7b0C9Aee] = 544; // seq: 543 -> tkn_id: 544 claimers[0x3017dC24849823c81c43b6F8288bC85D6214FD7E] = 545; // seq: 544 -> tkn_id: 545 claimers[0xdf59a1d81880bDE9175c3B766c3e95bEd21c3670] = 546; // seq: 545 -> tkn_id: 546 claimers[0x2A716b58127BC4341231833E3A586582b07bBB22] = 547; // seq: 546 -> tkn_id: 547 claimers[0x15c5F3a14d4492b1a26f4c6557251a6F247a2Dd5] = 548; // seq: 547 -> tkn_id: 548 claimers[0x239af5a76A69de3F13aed6970fdF37bf86e8FEB7] = 549; // seq: 548 -> tkn_id: 549 claimers[0xCF6E7e0676f5AC61446F6865e26a0f34bb86A622] = 550; // seq: 549 -> tkn_id: 550 claimers[0xfb580744F1fDc4fEb83D9846E907a63Aa94979bd] = 551; // seq: 550 -> tkn_id: 551 claimers[0x3de1820D8d3B7f6C61C34dfD74F941c88cb27143] = 552; // seq: 551 -> tkn_id: 552 claimers[0xDFfF9Df5665BD156ECc71769103C72D8D167E30b] = 553; // seq: 552 -> tkn_id: 553 claimers[0xf4775496624C382f74aDbAE79C5780F353B1f83B] = 554; // seq: 553 -> tkn_id: 554 claimers[0xd1f157e1798D20F905e8391e3AcC2351bd9873Ff] = 555; // seq: 554 -> tkn_id: 555 claimers[0x2BcfEC37A16eb258d641812A308edEc5B80b32C1] = 556; // seq: 555 -> tkn_id: 556 claimers[0xD7CE5Cec413cC35edc293BD0e9D6204bEb91a470] = 557; // seq: 556 -> tkn_id: 557 claimers[0xC195a064BE7Ac37702Cd8FBcE4d71b57111d559b] = 558; // seq: 557 -> tkn_id: 558 claimers[0xc148113F6508589538d65B29426331A12B04bC6C] = 559; // seq: 558 -> tkn_id: 559 claimers[0x687922176D1BbcBcdC295E121BcCaA45A1f40fCd] = 560; // seq: 559 -> tkn_id: 560 claimers[0xba5270bFd7245C37db5e9Bb5fC18A68b8cA622F8] = 561; // seq: 560 -> tkn_id: 561 claimers[0x2022e7E902DdF290B70AAF5FB5D777E7840Fc9D3] = 562; // seq: 561 -> tkn_id: 562 claimers[0x676be4D726F6e648cC41AcF71b3d099dC65242f3] = 563; // seq: 562 -> tkn_id: 563 claimers[0xCbBdE3eeb1005A8be374C0eeB9c02e0e33Ac4629] = 564; // seq: 563 -> tkn_id: 564 claimers[0xaf636e6585a1cD5CDD23A75d32cbd57e6D836dA6] = 565; // seq: 564 -> tkn_id: 565 claimers[0x7dE08dAb472F16F6713bD30B1B1BCd29FA7AC68c] = 566; // seq: 565 -> tkn_id: 566 claimers[0xc8fa8A80D241a06CB53d61Ceacce0d1a8715Bc2f] = 567; // seq: 566 -> tkn_id: 567 claimers[0xA661Ff505C9Be09C08341666bbB32c46a80Fe996] = 568; // seq: 567 -> tkn_id: 568 claimers[0x934Cc457EDC4b58b105188C3ECE78c7b2EE65d80] = 569; // seq: 568 -> tkn_id: 569 claimers[0xFF4a498B23f2E3aD0A5eBEd838F07F30Ab4dC800] = 570; // seq: 569 -> tkn_id: 570 claimers[0xf75b052036dB7d90D18C10C06d3535F0fc3A4b74] = 571; // seq: 570 -> tkn_id: 571 claimers[0x8f2a707153378551c450Ec28B29c72C0B97664FC] = 572; // seq: 571 -> tkn_id: 572 claimers[0x77167885E8393f1052A8cE8D5dfF2fF16c08f98d] = 573; // seq: 572 -> tkn_id: 573 claimers[0x186D482EB263492318Cd470f3e4C0cf7705b3963] = 574; // seq: 573 -> tkn_id: 574 claimers[0x0736C28bd6186Cc899F72aB3f68f542bC2479d90] = 575; // seq: 574 -> tkn_id: 575 claimers[0x5E6DbCb38555ec7B4c5C12F19144736010335d26] = 576; // seq: 575 -> tkn_id: 576 claimers[0xd85d3AcC28A235f9128938B99E26747dB0ba655D] = 577; // seq: 576 -> tkn_id: 577 claimers[0x812E1eeE6D76e2F3490a8C29C0CC9e38D71a1a4f] = 578; // seq: 577 -> tkn_id: 578 claimers[0x66D61B6BEb130197E8194B072215d9aE9b36e14d] = 579; // seq: 578 -> tkn_id: 579 claimers[0x36986961cc3037E40Ef6f01A7481941ed08aF566] = 580; // seq: 579 -> tkn_id: 580 claimers[0xB6ea652fBE96DeddC5fc7133C208D024f3CFFf5a] = 581; // seq: 580 -> tkn_id: 581 claimers[0x2F86c6e97C4E2d03939AfE7452448bD96b681938] = 582; // seq: 581 -> tkn_id: 582 claimers[0x6F36a7E4eA93aCbF753397C96DaBacD45ba88175] = 583; // seq: 582 -> tkn_id: 583 claimers[0x6394e38E5Fe6Fb9de9B2dD267F257035fe72a315] = 584; // seq: 583 -> tkn_id: 584 claimers[0xeE74a1e81B6C55e3D02D05D7CaE9FD6BCee0E651] = 585; // seq: 584 -> tkn_id: 585 claimers[0x9A7797Cf292579065CC204C5c975E0E7E9dF66f7] = 586; // seq: 585 -> tkn_id: 586 claimers[0xf50E61952aC37fa5DD770657326A5FBDB18cB694] = 587; // seq: 586 -> tkn_id: 587 claimers[0x0B60fF27655bCd5E9444c5D1865ec8CD3B403146] = 588; // seq: 587 -> tkn_id: 588 claimers[0x35f382D9daA602A23AD988D5bf837B8e6A01d002] = 589; // seq: 588 -> tkn_id: 589 claimers[0xFF7C32e9D881e6cabBCE7C0C17564F54260C3872] = 590; // seq: 589 -> tkn_id: 590 claimers[0xdE437ad59B5fcad477eB90a4742916FD04c0193e] = 591; // seq: 590 -> tkn_id: 591 claimers[0xB9f2946b6f35d8BB4a1522e7628F24416947ddda] = 592; // seq: 591 -> tkn_id: 592 claimers[0x67AE8A6e6587e6219141dC5a5BE35f30Beb30C50] = 593; // seq: 592 -> tkn_id: 593 claimers[0x04b5b1906745FE9E501C10B3191118FA76CD76Ba] = 594; // seq: 593 -> tkn_id: 594 claimers[0xc793B339FC99A912d8c4c420f55023e072Dc4A08] = 595; // seq: 594 -> tkn_id: 595 claimers[0x024713784f675dd28b5CE07dB91a4d47213c2394] = 596; // seq: 595 -> tkn_id: 596 claimers[0xE9011643a76aC1Ee4BDb32242B28424597C724A2] = 597; // seq: 596 -> tkn_id: 597 claimers[0xFA3ed3EDd606157c2FD49c900a0B1fE867b96d78] = 598; // seq: 597 -> tkn_id: 598 claimers[0xEb06301D471b0F8C8C5CC965B09Ce0B85021D398] = 599; // seq: 598 -> tkn_id: 599 claimers[0x57985E22ae7906cC693b44cC16473643F294Ff07] = 600; // seq: 599 -> tkn_id: 600 claimers[0x3ef7Bf350074EFDE3FD107ce38e652a10a5750f5] = 601; // seq: 600 -> tkn_id: 601 claimers[0xAA5990c918b845EE54ade1a962aDb9ddfF17D20A] = 602; // seq: 601 -> tkn_id: 602 claimers[0x7Ff698e124d1D14E6d836aF4dA0Ae448c8FfFa6F] = 603; // seq: 602 -> tkn_id: 603 claimers[0x95351210cf4F6270aaD413d5A2E07256a005D9B3] = 604; // seq: 603 -> tkn_id: 604 claimers[0x2aE024C5EE8dA720b9A51F50D53a291aca37dEb1] = 605; // seq: 604 -> tkn_id: 605 claimers[0xe0dAA80c1fF85fd070b561ef44cC7637059E5e57] = 606; // seq: 605 -> tkn_id: 606 claimers[0xD64212269c456D61bCA45403c4B93A2a57B7510E] = 607; // seq: 606 -> tkn_id: 607 claimers[0xC3A9eB254C875750A83750d1258220fA8a729F89] = 608; // seq: 607 -> tkn_id: 608 claimers[0x07b678695690183C644fEb37d9E95eBa4eFe53A8] = 609; // seq: 608 -> tkn_id: 609 claimers[0x4334c48D71b8D03799487a601509ac137b29904B] = 610; // seq: 609 -> tkn_id: 610 claimers[0xea2D190cBb3Be5074E9E144EDE095f059eDB7E53] = 611; // seq: 610 -> tkn_id: 611 claimers[0x93973b0dc20bEff165C087cB2A319640C210f30e] = 612; // seq: 611 -> tkn_id: 612 claimers[0x8015eA3DA10b9960378CdF6d529EBf19553c112A] = 613; // seq: 612 -> tkn_id: 613 claimers[0xE40Cc4De1a57e83AAc249Bb4EF833B766f26e2F2] = 614; // seq: 613 -> tkn_id: 614 claimers[0xdD2B93A4F52C138194C10686f175df55db690117] = 615; // seq: 614 -> tkn_id: 615 claimers[0x2EF48fA1785aE0C24fd791c1D7BAaf690d153793] = 616; // seq: 615 -> tkn_id: 616 claimers[0x2044E9cF4a61D4a49C73800168Ecfd8Bd19550c4] = 617; // seq: 616 -> tkn_id: 617 claimers[0xF6711aFF1462fd2f477769C2d442Cf2b10597C6D] = 618; // seq: 617 -> tkn_id: 618 claimers[0xf9F49E8B93f60535852A91FeE294fF6c4D460035] = 619; // seq: 618 -> tkn_id: 619 claimers[0x61b3c4c9dc16B686eD396319D48586f40c1F74E9] = 620; // seq: 619 -> tkn_id: 620 claimers[0x348F0cE2c24f14EfC18bfc2B2048726BDCDB759e] = 621; // seq: 620 -> tkn_id: 621 claimers[0x32f8E5d3F4039d1DF89B6A1e544288289A500Fd1] = 622; // seq: 621 -> tkn_id: 622 claimers[0xaF997affb94c5Ca556b28b024E162AA3164f4A43] = 623; // seq: 622 -> tkn_id: 623 claimers[0xb20Ce1911054DE1D77E1a66ec402fcB3d06c06c2] = 624; // seq: 623 -> tkn_id: 624 claimers[0xB83FC0c399e46b69e330f19baEB87B6832Ec890d] = 625; // seq: 624 -> tkn_id: 625 claimers[0x01B9b335Bb0D8Ff543f54eb9A59Ba57dBEf7A93B] = 626; // seq: 625 -> tkn_id: 626 claimers[0x2CC7dA5EF8fd01f4a7cD03E785A01941F28fE8da] = 627; // seq: 626 -> tkn_id: 627 claimers[0x46f75A3e9702d89E3E269361D9c1e4D2A9779044] = 628; // seq: 627 -> tkn_id: 628 claimers[0x7AEBDD84821190c1cfCaCe051E87913ae5d67439] = 629; // seq: 628 -> tkn_id: 629 claimers[0xE94F4519Ed1670123714d8f67B3A144Bf089f594] = 630; // seq: 629 -> tkn_id: 630 claimers[0xf10367decc6F0e6A12Aa14E7512AF94a4C791Fd7] = 631; // seq: 630 -> tkn_id: 631 claimers[0x49BA4256FE65b833b3dA9c26aA27E1eFD74EFD1d] = 632; // seq: 631 -> tkn_id: 632 claimers[0x33BE249B512DCb6D2FC7586047ab0220397aF2d3] = 633; // seq: 632 -> tkn_id: 633 claimers[0x07b449319D200b1189406c58967348c5bA0D4083] = 634; // seq: 633 -> tkn_id: 634 claimers[0x9B6498Ef7F47223f5F7d466FC4D26c570C7b375F] = 635; // seq: 634 -> tkn_id: 635 claimers[0xA40F625ce8e06Db1C41Bb7F8854C7d57644Ff9Cc] = 636; // seq: 635 -> tkn_id: 636 claimers[0x28864AF76e73B38e2C9D4e856Ea97F66947961aB] = 637; // seq: 636 -> tkn_id: 637 claimers[0x4aC4Ab29F4A87150D89D3fdd5cbC46112606E5e8] = 638; // seq: 637 -> tkn_id: 638 claimers[0x9D29BBF508cDf300D116FCA3cE3cd9d287850ccd] = 639; // seq: 638 -> tkn_id: 639 claimers[0xcC5Fb93A6e274Ac3C626a02B24F939b1307b46e1] = 640; // seq: 639 -> tkn_id: 640 claimers[0x0E590293aD7CB2Dd9968B7f16eac9614451A63E1] = 641; // seq: 640 -> tkn_id: 641 claimers[0x726d54570632b30c957E60CFf44AD4eE2b559dB6] = 642; // seq: 641 -> tkn_id: 642 claimers[0xE2927F7f6618E71A86CE3F8F5AC32B5BbFe163a6] = 643; // seq: 642 -> tkn_id: 643 claimers[0x3C7DEd16d0E5b5bA9fb3DE539ed28cb7B7D8C95C] = 644; // seq: 643 -> tkn_id: 644 claimers[0xB7c3A0928c06A80DC4A4CDc9dC0aec33E047A4c8] = 645; // seq: 644 -> tkn_id: 645 claimers[0x95f26898b144FF93283d38d0B1A92b69f90d3123] = 646; // seq: 645 -> tkn_id: 646 claimers[0x95a788A34b7781eF34660196BB615A97F7e7d2B8] = 647; // seq: 646 -> tkn_id: 647 claimers[0x317EA9Dd8fCac5A6Fd94eB2959FeC690931b61b8] = 648; // seq: 647 -> tkn_id: 648 claimers[0x2CE83785eD44961959bf5251e85af897Ba9ddAC7] = 649; // seq: 648 -> tkn_id: 649 claimers[0xE144E7e3948dCA4AD395794031A0289a83b150A0] = 650; // seq: 649 -> tkn_id: 650 claimers[0x18668B0244949570ec637465BAFdDe4d082afa69] = 651; // seq: 650 -> tkn_id: 651 claimers[0xaba035729057984c7431a711436D3e51e947cbD4] = 652; // seq: 651 -> tkn_id: 652 claimers[0x2519410f255A52CDF22a7DFA870073b1357B30A7] = 653; // seq: 652 -> tkn_id: 653 claimers[0x63a12D51Ee95eF213404308e1F8a2805A0c21899] = 654; // seq: 653 -> tkn_id: 654 claimers[0x882bBB07991c5c2f65988fd077CdDF405FE5b56f] = 655; // seq: 654 -> tkn_id: 655 claimers[0x11f53fdAb3054a5cA63778659263aF0838b642b1] = 656; // seq: 655 -> tkn_id: 656 claimers[0x093E088901909dEecC1b4a1479fBcCE1FBEd31E7] = 657; // seq: 656 -> tkn_id: 657 claimers[0x3c5cBddC5D6D6720d51CB563134d72E20dc4C713] = 658; // seq: 657 -> tkn_id: 658 claimers[0x3Db111A09A2e77A8DD6d03dc3f089f4A0F4557E9] = 659; // seq: 658 -> tkn_id: 659 claimers[0x8F53cA524c1451A930DEA18926df964Fb72B10F1] = 660; // seq: 659 -> tkn_id: 660 claimers[0x22C535D5EccCF398997eabA19Aa3FAbd3fe6AA16] = 661; // seq: 660 -> tkn_id: 661 claimers[0x93dF35071B3bc1B6d16D5f5F20fbB2be9D50FE67] = 662; // seq: 661 -> tkn_id: 662 claimers[0xfE61D830b99E40b3E905CD7EcF4a08DD06fa7F03] = 663; // seq: 662 -> tkn_id: 663 claimers[0x9cB5FAF0801ac959a0d40b2A7D69Ed8E42F792eA] = 664; // seq: 663 -> tkn_id: 664 claimers[0xC5B0f2afEC01807D964D76aEce6dB2F093239619] = 665; // seq: 664 -> tkn_id: 665 claimers[0x9b279dbaB2aE483EEDD106a583ACbBCFd722CE79] = 666; // seq: 665 -> tkn_id: 666 claimers[0x429c74f7C7fe7d31a70289e9B4b54e0F7300f376] = 667; // seq: 666 -> tkn_id: 667 claimers[0xeD08e8D72D35428b28390B7334ebe7F9f7a64822] = 668; // seq: 667 -> tkn_id: 668 claimers[0xB468076716C800Ce1eB9e9F515488099cC838128] = 669; // seq: 668 -> tkn_id: 669 claimers[0x3D7A35c89f04Af71F453b33848B49714859D061c] = 670; // seq: 669 -> tkn_id: 670 claimers[0x7DcE9e613b3583C600255A230497DD77429b0e21] = 671; // seq: 670 -> tkn_id: 671 claimers[0x2B00CaD253E88924290fFC7FeE221D135A0f083a] = 672; // seq: 671 -> tkn_id: 672 claimers[0xA2A64dE6BEe8c68DBCC948609708Ae54801CBAd8] = 673; // seq: 672 -> tkn_id: 673 claimers[0x6F255406306D6D78e97a29F7f249f6d2d85d9801] = 674; // seq: 673 -> tkn_id: 674 claimers[0xcDaf4c2e205A8077F29BF1dfF9Bd0B6a501B72cB] = 675; // seq: 674 -> tkn_id: 675 claimers[0xC45bF67A729B9A2b98521CDbCbf8bc70d8b81af3] = 676; // seq: 675 -> tkn_id: 676 claimers[0x35205135F0883e6a59aF9cb64310c53003433122] = 677; // seq: 676 -> tkn_id: 677 claimers[0xbAFcFC93A2fb6a042CA87f3d70670E2c114CE9fd] = 678; // seq: 677 -> tkn_id: 678 claimers[0xf664D1363FcE2da5ebb9aA935ef11Ce07be012Db] = 679; // seq: 678 -> tkn_id: 679 claimers[0x57e7ce99461FDeA80Ae8a6292e58AEfe053ed3a3] = 680; // seq: 679 -> tkn_id: 680 claimers[0xbD0Ad704f38AfebbCb4BA891389938D4177A8A92] = 681; // seq: 680 -> tkn_id: 681 claimers[0x0962FEeC7d4f0fa0EBadf6cd2e1CB783103B41F4] = 682; // seq: 681 -> tkn_id: 682 claimers[0x9B89f9Fd0952009fd556b19B18d85dA1089D005C] = 683; // seq: 682 -> tkn_id: 683 claimers[0xa511CB01cCe9c221cC73a9f9231937Cf6baf1D1A] = 684; // seq: 683 -> tkn_id: 684 claimers[0x79e5c907b9d4Af5840C687e6975a1C530895454a] = 685; // seq: 684 -> tkn_id: 685 claimers[0xf782f0Bf9B741FdE0E7c7dA4f71c7E33554f8397] = 686; // seq: 685 -> tkn_id: 686 claimers[0x228Bb6C83e8d0767eD342dd333DDbD55Ad217a3D] = 687; // seq: 686 -> tkn_id: 687 claimers[0xf2f62B5C7B3395b0ACe219d1B91D8083f8394720] = 688; // seq: 687 -> tkn_id: 688 claimers[0x2A77484F4cca78a5B3f71c22A50e3A1b8583072D] = 689; // seq: 688 -> tkn_id: 689 claimers[0xbB85877c4AEa11A141FC107Dc8D2E43C4B04F8C8] = 690; // seq: 689 -> tkn_id: 690 claimers[0x0414B2A60f8d4b84dE036677f8780F59AFEc1b65] = 691; // seq: 690 -> tkn_id: 691 claimers[0xb3aA296e046E0EFBd734cfa5DCd447Ae3a5e6104] = 692; // seq: 691 -> tkn_id: 692 claimers[0xa6700EA3f19830e2e8b35363c2978cb9D5630303] = 693; // seq: 692 -> tkn_id: 693 claimers[0xF976106afd7ADE91F8dFc5167284AD57795b17B1] = 694; // seq: 693 -> tkn_id: 694 claimers[0x793E446AFFf802e20bdb496A64250622BE32Df29] = 695; // seq: 694 -> tkn_id: 695 claimers[0x2E72d671fa07be54ae9671f793895520268eF00E] = 696; // seq: 695 -> tkn_id: 696 claimers[0xB67c99dfb3422b61f9E38070f021eaB7B42e9CAF] = 697; // seq: 696 -> tkn_id: 697 claimers[0x0095D1f7804D32A7921b26D3Eb1229873D3B11E0] = 698; // seq: 697 -> tkn_id: 698 claimers[0xEf31D013E222AaD9Eb90df9fd466c758B7603FaB] = 699; // seq: 698 -> tkn_id: 699 claimers[0x9936f05D5cE4259D44Aa51d54c0C245652efcc11] = 700; // seq: 699 -> tkn_id: 700 claimers[0x58bb897f0612235FA7Ae324F9b9718a06A2f6df3] = 701; // seq: 700 -> tkn_id: 701 claimers[0xa2cF94Bf60B6a6C08488B756E6695d990574e9C7] = 702; // seq: 701 -> tkn_id: 702 claimers[0x47754f6dCb011A308c91a666c5245abbC577c9eD] = 703; // seq: 702 -> tkn_id: 703 claimers[0xB6a95916221Abef28339594161cd154Bc650c515] = 704; // seq: 703 -> tkn_id: 704 claimers[0xb0471Ad0fEFD2151Efaa6C8415b1dB984526c0a6] = 705; // seq: 704 -> tkn_id: 705 claimers[0xC869ce145a5a72985540285Efde28f5176F39bC9] = 706; // seq: 705 -> tkn_id: 706 claimers[0x79440849d5BA6Df5fb1F45Ff36BE3979F4271fa4] = 707; // seq: 706 -> tkn_id: 707 claimers[0xD54F610d744b64393386a354cf1ADD944cBD42c9] = 708; // seq: 707 -> tkn_id: 708 claimers[0x3b368E77F110e3FE1C8482F395E51D1f75e50e5f] = 709; // seq: 708 -> tkn_id: 709 claimers[0x529ccAFA5aC0d18E7402244859AF8664BA736919] = 710; // seq: 709 -> tkn_id: 710 claimers[0x686241b898D7616FF78e22cc45fb07e92A74B7B5] = 711; // seq: 710 -> tkn_id: 711 claimers[0xd859ad8D8DCA1eEC61529833685FE59FAb804E7d] = 712; // seq: 711 -> tkn_id: 712 claimers[0x5AbfC4E2bB4941BD6773f120573618Ba8a4f7863] = 713; // seq: 712 -> tkn_id: 713 claimers[0x17c1cF2eeFda3f339996c67cd18d4389D132D033] = 714; // seq: 713 -> tkn_id: 714 claimers[0x6Ce5B05f0C6A8129DE3C7fC3E69ca35Be3ECB35e] = 715; // seq: 714 -> tkn_id: 715 claimers[0x4B992870CF27A548921082be7B447fc3c0534509] = 716; // seq: 715 -> tkn_id: 716 claimers[0xa278039DEE9B1fC58164Ef7B6f5eC86de9786178] = 717; // seq: 716 -> tkn_id: 717 claimers[0xBa64c61B45340994bABF676544025BcCc0bE6A9e] = 718; // seq: 717 -> tkn_id: 718 claimers[0x3656f4d852f15986beBE025AEF64a40dF2A5d4a1] = 719; // seq: 718 -> tkn_id: 719 claimers[0x4A57385D14882d6d8FDB3916792E9585102d22DA] = 720; // seq: 719 -> tkn_id: 720 claimers[0x764108BAcf10e30F6f249d17E7612fB9008923F0] = 721; // seq: 720 -> tkn_id: 721 claimers[0x880BD9ec1d3b71Bda5249baCCC63E9a8e5902250] = 722; // seq: 721 -> tkn_id: 722 claimers[0x1195e87Ca87C8f5989ecBa2d569E64784E5820f9] = 723; // seq: 722 -> tkn_id: 723 claimers[0x8591D21143794463A69017944F555E272965db06] = 724; // seq: 723 -> tkn_id: 724 claimers[0x032c255E5a84C2E8Ca242f85098988D69b982E85] = 725; // seq: 724 -> tkn_id: 725 claimers[0xFD9bCD1F71Cb016079077F659Ee99f8AD834732A] = 726; // seq: 725 -> tkn_id: 726 claimers[0x6Be049Bb4688dFf540E7798433c925E21c70Ac25] = 727; // seq: 726 -> tkn_id: 727 claimers[0xFbFB1aD08f5d60d0243CC88E1EDf9eD5875d2EFe] = 728; // seq: 727 -> tkn_id: 728 claimers[0xeBe91f187bF0b29185a8e4A362392Aa3665030a1] = 729; // seq: 728 -> tkn_id: 729 claimers[0xF6666FCE84FDe632f33c1A881b6AC2C0f545D271] = 730; // seq: 729 -> tkn_id: 730
seq: 475 -> tkn_id: 476
claimers[0xC0FFd04728F3D0Dd3d355d1DdE4F65740565A640] = 476;
12,654,971
[ 1, 5436, 30, 1059, 5877, 317, 13030, 82, 67, 350, 30, 1059, 6669, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 14784, 414, 63, 20, 14626, 20, 2246, 72, 3028, 27, 6030, 42, 23, 40, 20, 40, 72, 23, 72, 23, 2539, 72, 21, 40, 72, 41, 24, 42, 9222, 5608, 20, 4313, 25, 37, 1105, 20, 65, 273, 1059, 6669, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.0; /// @title SelfAuthorized - authorizes current contract to perform actions /// @author Richard Meissner - <[email protected]> contract SelfAuthorized { modifier authorized() { require(msg.sender == address(this), "Method can only be called from this contract"); _; } } /// @title MasterCopy - Base for master copy contracts (should always be first super contract) /// @author Richard Meissner - <[email protected]> contract MasterCopy is SelfAuthorized { // masterCopy always needs to be first declared variable, to ensure that it is at the same location as in the Proxy contract. // It should also always be ensured that the address is stored alone (uses a full word) address masterCopy; /// @dev Allows to upgrade the contract. This can only be done via a Safe transaction. /// @param _masterCopy New contract address. function changeMasterCopy(address _masterCopy) public authorized { // Master copy address cannot be null. require(_masterCopy != address(0), "Invalid master copy address provided"); masterCopy = _masterCopy; } } /// @title Enum - Collection of enums /// @author Richard Meissner - <[email protected]> contract Enum { enum Operation { Call, DelegateCall, Create } } /// @title EtherPaymentFallback - A contract that has a fallback to accept ether payments /// @author Richard Meissner - <[email protected]> contract EtherPaymentFallback { /// @dev Fallback function accepts Ether transactions. function () external payable { } } /// @title Executor - A contract that can execute transactions /// @author Richard Meissner - <[email protected]> contract Executor is EtherPaymentFallback { event ContractCreation(address newContract); function execute(address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 txGas) internal returns (bool success) { if (operation == Enum.Operation.Call) success = executeCall(to, value, data, txGas); else if (operation == Enum.Operation.DelegateCall) success = executeDelegateCall(to, data, txGas); else { address newContract = executeCreate(data); success = newContract != address(0); emit ContractCreation(newContract); } } function executeCall(address to, uint256 value, bytes memory data, uint256 txGas) internal returns (bool success) { // solium-disable-next-line security/no-inline-assembly assembly { success := call(txGas, to, value, add(data, 0x20), mload(data), 0, 0) } } function executeDelegateCall(address to, bytes memory data, uint256 txGas) internal returns (bool success) { // solium-disable-next-line security/no-inline-assembly assembly { success := delegatecall(txGas, to, add(data, 0x20), mload(data), 0, 0) } } function executeCreate(bytes memory data) internal returns (address newContract) { // solium-disable-next-line security/no-inline-assembly assembly { newContract := create(0, add(data, 0x20), mload(data)) } } } /// @title Module Manager - A contract that manages modules that can execute transactions via this contract /// @author Stefan George - <[email protected]> /// @author Richard Meissner - <[email protected]> contract ModuleManager is SelfAuthorized, Executor { event EnabledModule(Module module); event DisabledModule(Module module); address public constant SENTINEL_MODULES = address(0x1); mapping (address => address) internal modules; function setupModules(address to, bytes memory data) internal { require(modules[SENTINEL_MODULES] == address(0), "Modules have already been initialized"); modules[SENTINEL_MODULES] = SENTINEL_MODULES; if (to != address(0)) // Setup has to complete successfully or transaction fails. require(executeDelegateCall(to, data, gasleft()), "Could not finish initialization"); } /// @dev Allows to add a module to the whitelist. /// This can only be done via a Safe transaction. /// @param module Module to be whitelisted. function enableModule(Module module) public authorized { // Module address cannot be null or sentinel. require(address(module) != address(0) && address(module) != SENTINEL_MODULES, "Invalid module address provided"); // Module cannot be added twice. require(modules[address(module)] == address(0), "Module has already been added"); modules[address(module)] = modules[SENTINEL_MODULES]; modules[SENTINEL_MODULES] = address(module); emit EnabledModule(module); } /// @dev Allows to remove a module from the whitelist. /// This can only be done via a Safe transaction. /// @param prevModule Module that pointed to the module to be removed in the linked list /// @param module Module to be removed. function disableModule(Module prevModule, Module module) public authorized { // Validate module address and check that it corresponds to module index. require(address(module) != address(0) && address(module) != SENTINEL_MODULES, "Invalid module address provided"); require(modules[address(prevModule)] == address(module), "Invalid prevModule, module pair provided"); modules[address(prevModule)] = modules[address(module)]; modules[address(module)] = address(0); emit DisabledModule(module); } /// @dev Allows a Module to execute a Safe transaction without any further confirmations. /// @param to Destination address of module transaction. /// @param value Ether value of module transaction. /// @param data Data payload of module transaction. /// @param operation Operation type of module transaction. function execTransactionFromModule(address to, uint256 value, bytes memory data, Enum.Operation operation) public returns (bool success) { // Only whitelisted modules are allowed. require(msg.sender != SENTINEL_MODULES && modules[msg.sender] != address(0), "Method can only be called from an enabled module"); // Execute transaction without further confirmations. success = execute(to, value, data, operation, gasleft()); } /// @dev Returns array of modules. /// @return Array of modules. function getModules() public view returns (address[] memory) { // Calculate module count uint256 moduleCount = 0; address currentModule = modules[SENTINEL_MODULES]; while(currentModule != SENTINEL_MODULES) { currentModule = modules[currentModule]; moduleCount ++; } address[] memory array = new address[](moduleCount); // populate return array moduleCount = 0; currentModule = modules[SENTINEL_MODULES]; while(currentModule != SENTINEL_MODULES) { array[moduleCount] = currentModule; currentModule = modules[currentModule]; moduleCount ++; } return array; } } /// @title Module - Base class for modules. /// @author Stefan George - <[email protected]> /// @author Richard Meissner - <[email protected]> contract Module is MasterCopy { ModuleManager public manager; modifier authorized() { require(msg.sender == address(manager), "Method can only be called from manager"); _; } function setManager() internal { // manager can only be 0 at initalization of contract. // Check ensures that setup function can only be called once. require(address(manager) == address(0), "Manager has already been set"); manager = ModuleManager(msg.sender); } } /// @title OwnerManager - Manages a set of owners and a threshold to perform actions. /// @author Stefan George - <[email protected]> /// @author Richard Meissner - <[email protected]> contract OwnerManager is SelfAuthorized { event AddedOwner(address owner); event RemovedOwner(address owner); event ChangedThreshold(uint256 threshold); address public constant SENTINEL_OWNERS = address(0x1); mapping(address => address) internal owners; uint256 ownerCount; uint256 internal threshold; /// @dev Setup function sets initial storage of contract. /// @param _owners List of Safe owners. /// @param _threshold Number of required confirmations for a Safe transaction. function setupOwners(address[] memory _owners, uint256 _threshold) internal { // Threshold can only be 0 at initialization. // Check ensures that setup function can only be called once. require(threshold == 0, "Owners have already been setup"); // Validate that threshold is smaller than number of added owners. require(_threshold <= _owners.length, "Threshold cannot exceed owner count"); // There has to be at least one Safe owner. require(_threshold >= 1, "Threshold needs to be greater than 0"); // Initializing Safe owners. address currentOwner = SENTINEL_OWNERS; for (uint256 i = 0; i < _owners.length; i++) { // Owner address cannot be null. address owner = _owners[i]; require(owner != address(0) && owner != SENTINEL_OWNERS, "Invalid owner address provided"); // No duplicate owners allowed. require(owners[owner] == address(0), "Duplicate owner address provided"); owners[currentOwner] = owner; currentOwner = owner; } owners[currentOwner] = SENTINEL_OWNERS; ownerCount = _owners.length; threshold = _threshold; } /// @dev Allows to add a new owner to the Safe and update the threshold at the same time. /// This can only be done via a Safe transaction. /// @param owner New owner address. /// @param _threshold New threshold. function addOwnerWithThreshold(address owner, uint256 _threshold) public authorized { // Owner address cannot be null. require(owner != address(0) && owner != SENTINEL_OWNERS, "Invalid owner address provided"); // No duplicate owners allowed. require(owners[owner] == address(0), "Address is already an owner"); owners[owner] = owners[SENTINEL_OWNERS]; owners[SENTINEL_OWNERS] = owner; ownerCount++; emit AddedOwner(owner); // Change threshold if threshold was changed. if (threshold != _threshold) changeThreshold(_threshold); } /// @dev Allows to remove an owner from the Safe and update the threshold at the same time. /// This can only be done via a Safe transaction. /// @param prevOwner Owner that pointed to the owner to be removed in the linked list /// @param owner Owner address to be removed. /// @param _threshold New threshold. function removeOwner(address prevOwner, address owner, uint256 _threshold) public authorized { // Only allow to remove an owner, if threshold can still be reached. require(ownerCount - 1 >= _threshold, "New owner count needs to be larger than new threshold"); // Validate owner address and check that it corresponds to owner index. require(owner != address(0) && owner != SENTINEL_OWNERS, "Invalid owner address provided"); require(owners[prevOwner] == owner, "Invalid prevOwner, owner pair provided"); owners[prevOwner] = owners[owner]; owners[owner] = address(0); ownerCount--; emit RemovedOwner(owner); // Change threshold if threshold was changed. if (threshold != _threshold) changeThreshold(_threshold); } /// @dev Allows to swap/replace an owner from the Safe with another address. /// This can only be done via a Safe transaction. /// @param prevOwner Owner that pointed to the owner to be replaced in the linked list /// @param oldOwner Owner address to be replaced. /// @param newOwner New owner address. function swapOwner(address prevOwner, address oldOwner, address newOwner) public authorized { // Owner address cannot be null. require(newOwner != address(0) && newOwner != SENTINEL_OWNERS, "Invalid owner address provided"); // No duplicate owners allowed. require(owners[newOwner] == address(0), "Address is already an owner"); // Validate oldOwner address and check that it corresponds to owner index. require(oldOwner != address(0) && oldOwner != SENTINEL_OWNERS, "Invalid owner address provided"); require(owners[prevOwner] == oldOwner, "Invalid prevOwner, owner pair provided"); owners[newOwner] = owners[oldOwner]; owners[prevOwner] = newOwner; owners[oldOwner] = address(0); emit RemovedOwner(oldOwner); emit AddedOwner(newOwner); } /// @dev Allows to update the number of required confirmations by Safe owners. /// This can only be done via a Safe transaction. /// @param _threshold New threshold. function changeThreshold(uint256 _threshold) public authorized { // Validate that threshold is smaller than number of owners. require(_threshold <= ownerCount, "Threshold cannot exceed owner count"); // There has to be at least one Safe owner. require(_threshold >= 1, "Threshold needs to be greater than 0"); threshold = _threshold; emit ChangedThreshold(threshold); } function getThreshold() public view returns (uint256) { return threshold; } function isOwner(address owner) public view returns (bool) { return owner != SENTINEL_OWNERS && owners[owner] != address(0); } /// @dev Returns array of owners. /// @return Array of Safe owners. function getOwners() public view returns (address[] memory) { address[] memory array = new address[](ownerCount); // populate return array uint256 index = 0; address currentOwner = owners[SENTINEL_OWNERS]; while(currentOwner != SENTINEL_OWNERS) { array[index] = currentOwner; currentOwner = owners[currentOwner]; index ++; } return array; } } /// @title GEnum - Collection of enums for subscriptions /// @author Andrew Redden - <[email protected]> contract GEnum { enum SubscriptionStatus { INIT, TRIAL, VALID, CANCELLED, EXPIRED } enum Period { INIT, DAY, WEEK, MONTH, YEAR } } /// @title SignatureDecoder - Decodes signatures that a encoded as bytes /// @author Ricardo Guilherme Schmidt (Status Research & Development GmbH) /// @author Richard Meissner - <[email protected]> contract SignatureDecoder { /// @dev Recovers address who signed the message /// @param messageHash operation ethereum signed message hash /// @param messageSignature message `txHash` signature /// @param pos which signature to read function recoverKey ( bytes32 messageHash, bytes memory messageSignature, uint256 pos ) internal pure returns (address) { uint8 v; bytes32 r; bytes32 s; (v, r, s) = signatureSplit(messageSignature, pos); return ecrecover(messageHash, v, r, s); } /// @dev divides bytes signature into `uint8 v, bytes32 r, bytes32 s` /// @param pos which signature to read /// @param signatures concatenated rsv signatures function signatureSplit(bytes memory signatures, uint256 pos) internal pure returns (uint8 v, bytes32 r, bytes32 s) { // The signature format is a compact form of: // {bytes32 r}{bytes32 s}{uint8 v} // Compact means, uint8 is not padded to 32 bytes. // solium-disable-next-line security/no-inline-assembly assembly { let signaturePos := mul(0x41, pos) r := mload(add(signatures, add(signaturePos, 0x20))) s := mload(add(signatures, add(signaturePos, 0x40))) // Here we are loading the last 32 bytes, including 31 bytes // of 's'. There is no 'mload8' to do this. // // 'byte' is not working due to the Solidity parser, so lets // use the second best option, 'and' v := and(mload(add(signatures, add(signaturePos, 0x41))), 0xff) } } } // ---------------------------------------------------------------------------- // BokkyPooBah's DateTime Library v1.00 // // A gas-efficient Solidity date and time library // // https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary // // Tested date range 1970/01/01 to 2345/12/31 // // Conventions: // Unit | Range | Notes // :-------- |:-------------:|:----- // timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC // year | 1970 ... 2345 | // month | 1 ... 12 | // day | 1 ... 31 | // hour | 0 ... 23 | // minute | 0 ... 59 | // second | 0 ... 59 | // dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday // // // Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018. // // GNU Lesser General Public License 3.0 // https://www.gnu.org/licenses/lgpl-3.0.en.html // ---------------------------------------------------------------------------- library BokkyPooBahsDateTimeLibrary { uint constant SECONDS_PER_DAY = 24 * 60 * 60; uint constant SECONDS_PER_HOUR = 60 * 60; uint constant SECONDS_PER_MINUTE = 60; int constant OFFSET19700101 = 2440588; uint constant DOW_MON = 1; uint constant DOW_TUE = 2; uint constant DOW_WED = 3; uint constant DOW_THU = 4; uint constant DOW_FRI = 5; uint constant DOW_SAT = 6; uint constant DOW_SUN = 7; // ------------------------------------------------------------------------ // Calculate the number of days from 1970/01/01 to year/month/day using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and subtracting the offset 2440588 so that 1970/01/01 is day 0 // // days = day // - 32075 // + 1461 * (year + 4800 + (month - 14) / 12) / 4 // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12 // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4 // - offset // ------------------------------------------------------------------------ function _daysFromDate(uint year, uint month, uint day) internal pure returns (uint _days) { require(year >= 1970); int _year = int(year); int _month = int(month); int _day = int(day); int __days = _day - 32075 + 1461 * (_year + 4800 + (_month - 14) / 12) / 4 + 367 * (_month - 2 - (_month - 14) / 12 * 12) / 12 - 3 * ((_year + 4900 + (_month - 14) / 12) / 100) / 4 - OFFSET19700101; _days = uint(__days); } // ------------------------------------------------------------------------ // Calculate year/month/day from the number of days since 1970/01/01 using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and adding the offset 2440588 so that 1970/01/01 is day 0 // // int L = days + 68569 + offset // int N = 4 * L / 146097 // L = L - (146097 * N + 3) / 4 // year = 4000 * (L + 1) / 1461001 // L = L - 1461 * year / 4 + 31 // month = 80 * L / 2447 // dd = L - 2447 * month / 80 // L = month / 11 // month = month + 2 - 12 * L // year = 100 * (N - 49) + year + L // ------------------------------------------------------------------------ function _daysToDate(uint _days) internal pure returns (uint year, uint month, uint day) { int __days = int(_days); int L = __days + 68569 + OFFSET19700101; int N = 4 * L / 146097; L = L - (146097 * N + 3) / 4; int _year = 4000 * (L + 1) / 1461001; L = L - 1461 * _year / 4 + 31; int _month = 80 * L / 2447; int _day = L - 2447 * _month / 80; L = _month / 11; _month = _month + 2 - 12 * L; _year = 100 * (N - 49) + _year + L; year = uint(_year); month = uint(_month); day = uint(_day); } function timestampFromDate(uint year, uint month, uint day) internal pure returns (uint timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY; } function timestampFromDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (uint timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + hour * SECONDS_PER_HOUR + minute * SECONDS_PER_MINUTE + second; } function timestampToDate(uint timestamp) internal pure returns (uint year, uint month, uint day) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function timestampToDateTime(uint timestamp) internal pure returns (uint year, uint month, uint day, uint hour, uint minute, uint second) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; secs = secs % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; second = secs % SECONDS_PER_MINUTE; } function isValidDate(uint year, uint month, uint day) internal pure returns (bool valid) { if (year >= 1970 && month > 0 && month <= 12) { uint daysInMonth = _getDaysInMonth(year, month); if (day > 0 && day <= daysInMonth) { valid = true; } } } function isValidDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (bool valid) { if (isValidDate(year, month, day)) { if (hour < 24 && minute < 60 && second < 60) { valid = true; } } } function isLeapYear(uint timestamp) internal pure returns (bool leapYear) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); leapYear = _isLeapYear(year); } function _isLeapYear(uint year) internal pure returns (bool leapYear) { leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0); } function isWeekDay(uint timestamp) internal pure returns (bool weekDay) { weekDay = getDayOfWeek(timestamp) <= DOW_FRI; } function isWeekEnd(uint timestamp) internal pure returns (bool weekEnd) { weekEnd = getDayOfWeek(timestamp) >= DOW_SAT; } function getDaysInMonth(uint timestamp) internal pure returns (uint daysInMonth) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); daysInMonth = _getDaysInMonth(year, month); } function _getDaysInMonth(uint year, uint month) internal pure returns (uint daysInMonth) { if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) { daysInMonth = 31; } else if (month != 2) { daysInMonth = 30; } else { daysInMonth = _isLeapYear(year) ? 29 : 28; } } // 1 = Monday, 7 = Sunday function getDayOfWeek(uint timestamp) internal pure returns (uint dayOfWeek) { uint _days = timestamp / SECONDS_PER_DAY; dayOfWeek = (_days + 3) % 7 + 1; } function getYear(uint timestamp) internal pure returns (uint year) { uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getMonth(uint timestamp) internal pure returns (uint month) { uint year; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getDay(uint timestamp) internal pure returns (uint day) { uint year; uint month; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getHour(uint timestamp) internal pure returns (uint hour) { uint secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; } function getMinute(uint timestamp) internal pure returns (uint minute) { uint secs = timestamp % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; } function getSecond(uint timestamp) internal pure returns (uint second) { second = timestamp % SECONDS_PER_MINUTE; } function addYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); year += _years; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); month += _months; year += (month - 1) / 12; month = (month - 1) % 12 + 1; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _days * SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _hours * SECONDS_PER_HOUR; require(newTimestamp >= timestamp); } function addMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _minutes * SECONDS_PER_MINUTE; require(newTimestamp >= timestamp); } function addSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _seconds; require(newTimestamp >= timestamp); } function subYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); year -= _years; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint yearMonth = year * 12 + (month - 1) - _months; year = yearMonth / 12; month = yearMonth % 12 + 1; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _days * SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _hours * SECONDS_PER_HOUR; require(newTimestamp <= timestamp); } function subMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _minutes * SECONDS_PER_MINUTE; require(newTimestamp <= timestamp); } function subSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _seconds; require(newTimestamp <= timestamp); } function diffYears(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _years) { require(fromTimestamp <= toTimestamp); uint fromYear; uint fromMonth; uint fromDay; uint toYear; uint toMonth; uint toDay; (fromYear, fromMonth, fromDay) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (toYear, toMonth, toDay) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _years = toYear - fromYear; } function diffMonths(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _months) { require(fromTimestamp <= toTimestamp); uint fromYear; uint fromMonth; uint fromDay; uint toYear; uint toMonth; uint toDay; (fromYear, fromMonth, fromDay) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (toYear, toMonth, toDay) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth; } function diffDays(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _days) { require(fromTimestamp <= toTimestamp); _days = (toTimestamp - fromTimestamp) / SECONDS_PER_DAY; } function diffHours(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _hours) { require(fromTimestamp <= toTimestamp); _hours = (toTimestamp - fromTimestamp) / SECONDS_PER_HOUR; } function diffMinutes(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _minutes) { require(fromTimestamp <= toTimestamp); _minutes = (toTimestamp - fromTimestamp) / SECONDS_PER_MINUTE; } function diffSeconds(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _seconds) { require(fromTimestamp <= toTimestamp); _seconds = toTimestamp - fromTimestamp; } } /// math.sol -- mixin for inline numerical wizardry // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. library DSMath { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x); } function min(uint x, uint y) internal pure returns (uint z) { return x <= y ? x : y; } function max(uint x, uint y) internal pure returns (uint z) { return x >= y ? x : y; } function imin(int x, int y) internal pure returns (int z) { return x <= y ? x : y; } function imax(int x, int y) internal pure returns (int z) { return x >= y ? x : y; } uint constant WAD = 10 ** 18; uint constant RAY = 10 ** 27; function wmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), WAD / 2) / WAD; } function rmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), RAY / 2) / RAY; } function wdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, WAD), y / 2) / y; } function rdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, RAY), y / 2) / y; } function tmul(uint x, uint y, uint z) internal pure returns (uint a) { require(z != 0); a = add(mul(x, y), z / 2) / z; } function tdiv(uint x, uint y, uint z) internal pure returns (uint a) { a = add(mul(x, z), y / 2) / y; } // This famous algorithm is called "exponentiation by squaring" // and calculates x^n with x as fixed-point and n as regular unsigned. // // It's O(log n), instead of O(n) for naive repeated multiplication. // // These facts are why it works: // // If n is even, then x^n = (x^2)^(n/2). // If n is odd, then x^n = x * x^(n-1), // and applying the equation for even x gives // x^n = x * (x^2)^((n-1) / 2). // // Also, EVM division is flooring and // floor[(n-1) / 2] = floor[n / 2]. // function rpow(uint x, uint n) internal pure returns (uint z) { z = n % 2 != 0 ? x : RAY; for (n /= 2; n != 0; n /= 2) { x = rmul(x, x); if (n % 2 != 0) { z = rmul(z, x); } } } } interface OracleRegistry { function read( uint256 currencyPair ) external view returns (bytes32); function getNetworkExecutor() external view returns (address); function getNetworkWallet() external view returns (address payable); function getNetworkFee(address asset) external view returns (uint256 fee); } /// @title SubscriptionModule - A module with support for Subscription Payments /// @author Andrew Redden - <[email protected]> contract SubscriptionModule is Module, SignatureDecoder { using BokkyPooBahsDateTimeLibrary for uint256; using DSMath for uint256; string public constant NAME = "Groundhog"; string public constant VERSION = "0.1.0"; bytes32 public domainSeparator; address public oracleRegistry; //keccak256( // "EIP712Domain(address verifyingContract)" //); bytes32 public constant DOMAIN_SEPARATOR_TYPEHASH = 0x035aff83d86937d35b32e04f0ddc6ff469290eef2f1b692d8a815c89404d4749; //keccak256( // "SafeSubTx(address to,uint256 value,bytes data,uint8 operation,uint256 safeTxGas,uint256 dataGas,uint256 gasPrice,address gasToken,address refundReceiver,bytes meta)" //) bytes32 public constant SAFE_SUB_TX_TYPEHASH = 0x4494907805e3ceba396741b2837174bdf548ec2cbe03f5448d7fa8f6b1aaf98e; //keccak256( // "SafeSubCancelTx(bytes32 subscriptionHash,string action)" //) bytes32 public constant SAFE_SUB_CANCEL_TX_TYPEHASH = 0xef5a0c558cb538697e29722572248a2340a367e5079b08a00b35ef5dd1e66faa; mapping(bytes32 => Meta) public subscriptions; struct Meta { GEnum.SubscriptionStatus status; uint256 nextWithdraw; uint256 endDate; uint256 cycle; } event NextPayment( bytes32 indexed subscriptionHash, uint256 nextWithdraw ); event OraclizedDenomination( bytes32 indexed subscriptionHash, uint256 dynPriceFormat, uint256 conversionRate, uint256 paymentTotal ); event StatusChanged( bytes32 indexed subscriptionHash, GEnum.SubscriptionStatus prev, GEnum.SubscriptionStatus next ); /// @dev Setup function sets manager function setup( address _oracleRegistry ) public { setManager(); require( domainSeparator == 0, "SubscriptionModule::setup: INVALID_STATE: DOMAIN_SEPARATOR_SET" ); domainSeparator = keccak256( abi.encode( DOMAIN_SEPARATOR_TYPEHASH, address(this) ) ); require( oracleRegistry == address(0), "SubscriptionModule::setup: INVALID_STATE: ORACLE_REGISTRY_SET" ); oracleRegistry = _oracleRegistry; } /// @dev Allows to execute a Safe transaction confirmed by required number of owners and then pays the account that submitted the transaction. /// Note: The fees are always transferred, even if the user transaction fails. /// @param to Destination address of Safe transaction. /// @param value Ether value of Safe transaction. /// @param data Data payload of Safe transaction. /// @param operation Operation type of Safe transaction. /// @param safeTxGas Gas that should be used for the Safe transaction. /// @param dataGas Gas costs for data used to trigger the safe transaction and to pay the payment transfer /// @param gasPrice Gas price that should be used for the payment calculation. /// @param gasToken Token address (or 0 if ETH) that is used for the payment. /// @param refundReceiver payout address or 0 if tx.origin /// @param meta Packed bytes data {address refundReceiver (required}, {uint256 period (required}, {uint256 offChainID (required}, {uint256 endDate (optional} /// @param signatures Packed signature data ({bytes32 r}{bytes32 s}{uint2568 v}) /// @return success boolean value of execution function execSubscription( address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 safeTxGas, uint256 dataGas, uint256 gasPrice, address gasToken, address payable refundReceiver, bytes memory meta, bytes memory signatures ) public returns ( bool ) { uint256 startGas = gasleft(); bytes memory subHashData = encodeSubscriptionData( to, value, data, operation, // Transaction info safeTxGas, dataGas, gasPrice, gasToken, refundReceiver, meta ); require( gasleft() >= safeTxGas, "SubscriptionModule::execSubscription: INVALID_DATA: WALLET_TX_GAS" ); require( _checkHash( keccak256(subHashData), signatures ), "SubscriptionModule::execSubscription: INVALID_DATA: SIGNATURES" ); _paySubscription( to, value, data, operation, keccak256(subHashData), meta ); // We transfer the calculated tx costs to the refundReceiver to avoid sending it to intermediate contracts that have made calls if (gasPrice > 0) { _handleTxPayment( startGas, dataGas, gasPrice, gasToken, refundReceiver ); } return true; } function _processMeta( bytes memory meta ) internal view returns ( uint256 conversionRate, uint256[4] memory outMeta ) { require( meta.length == 160, "SubscriptionModule::_processMeta: INVALID_DATA: META_LENGTH" ); ( uint256 oracle, uint256 period, uint256 offChainID, uint256 startDate, uint256 endDate ) = abi.decode( meta, (uint, uint, uint, uint, uint) //5 slots ); if (oracle != uint256(0)) { bytes32 rate = OracleRegistry(oracleRegistry).read(oracle); conversionRate = uint256(rate); } else { conversionRate = uint256(0); } return (conversionRate, [period, offChainID, startDate, endDate]); } function _paySubscription( address to, uint256 value, bytes memory data, Enum.Operation operation, bytes32 subscriptionHash, bytes memory meta ) internal { uint256 conversionRate; uint256[4] memory processedMetaData; (conversionRate, processedMetaData) = _processMeta(meta); bool processPayment = _processSub(subscriptionHash, processedMetaData); if (processPayment) { //Oracle Registry address data is in slot1 if (conversionRate != uint256(0)) { //when in priceFeed format, price feeds are denominated in Ether but converted to the feed pairing //ETHUSD, WBTC/USD require( value > 1.00 ether, "SubscriptionModule::_paySubscription: INVALID_FORMAT: DYNAMIC_PRICE_FORMAT" ); uint256 payment = value.wdiv(conversionRate); emit OraclizedDenomination( subscriptionHash, value, conversionRate, payment ); value = payment; } require( manager.execTransactionFromModule(to, value, data, operation), "SubscriptionModule::_paySubscription: INVALID_EXEC: PAY_SUB" ); } } function _handleTxPayment( uint256 gasUsed, uint256 dataGas, uint256 gasPrice, address gasToken, address payable refundReceiver ) internal { uint256 amount = gasUsed.sub(gasleft()).add(dataGas).mul(gasPrice); // solium-disable-next-line security/no-tx-origin address receiver = refundReceiver == address(0) ? tx.origin : refundReceiver; if (gasToken == address(0)) { // solium-disable-next-line security/no-send require( manager.execTransactionFromModule(receiver, amount, "0x", Enum.Operation.Call), "SubscriptionModule::_handleTxPayment: FAILED_EXEC: PAYMENT_ETH" ); } else { bytes memory data = abi.encodeWithSignature("transfer(address,uint256)", receiver, amount); // solium-disable-next-line security/no-inline-assembly require( manager.execTransactionFromModule(gasToken, 0, data, Enum.Operation.Call), "SubscriptionModule::_handleTxPayment: FAILED_EXEC: PAYMENT_GAS_TOKEN" ); } } function _checkHash( bytes32 hash, bytes memory signatures ) internal view returns ( bool valid ) { // There cannot be an owner with address 0. address lastOwner = address(0); address currentOwner; uint256 i; uint256 threshold = OwnerManager(address(manager)).getThreshold(); // Validate threshold is reached. valid = false; for (i = 0; i < threshold; i++) { currentOwner = recoverKey( hash, signatures, i ); require( OwnerManager(address(manager)).isOwner(currentOwner), "SubscriptionModule::_checkHash: INVALID_DATA: SIGNATURE_NOT_OWNER" ); require( currentOwner > lastOwner, "SubscriptionModule::_checkHash: INVALID_DATA: SIGNATURE_OUT_ORDER" ); lastOwner = currentOwner; } valid = true; } /// @dev Allows to execute a Safe transaction confirmed by required number of owners and then pays the account that submitted the transaction. /// Note: The fees are always transferred, even if the user transaction fails. /// @param subscriptionHash bytes32 hash of on chain sub /// @return bool isValid returns the validity of the subscription function isValidSubscription( bytes32 subscriptionHash, bytes memory signatures ) public view returns (bool isValid) { Meta storage sub = subscriptions[subscriptionHash]; //exit early if we can if (sub.status == GEnum.SubscriptionStatus.INIT) { return _checkHash( subscriptionHash, signatures ); } if (sub.status == GEnum.SubscriptionStatus.EXPIRED || sub.status == GEnum.SubscriptionStatus.CANCELLED) { require( sub.endDate != 0, "SubscriptionModule::isValidSubscription: INVALID_STATE: SUB_STATUS" ); isValid = (now <= sub.endDate); } else if ( (sub.status == GEnum.SubscriptionStatus.TRIAL && sub.nextWithdraw <= now) || (sub.status == GEnum.SubscriptionStatus.VALID) ) { isValid = true; } else { isValid = false; } } function cancelSubscriptionAsManager( bytes32 subscriptionHash ) authorized public returns (bool) { _cancelSubscription(subscriptionHash); return true; } function cancelSubscriptionAsRecipient( address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 safeTxGas, uint256 dataGas, uint256 gasPrice, address gasToken, address refundReceiver, bytes memory meta, bytes memory signatures ) public returns (bool) { bytes memory subHashData = encodeSubscriptionData( to, value, data, operation, // Transaction info safeTxGas, dataGas, gasPrice, gasToken, refundReceiver, meta ); require( _checkHash(keccak256(subHashData), signatures), "SubscriptionModule::cancelSubscriptionAsRecipient: INVALID_DATA: SIGNATURES" ); //if no value, assume its an ERC20 token, remove the to argument from the data if (value == uint(0)) { address recipient; // solium-disable-next-line security/no-inline-assembly assembly { recipient := div(mload(add(add(data, 0x20), 16)), 0x1000000000000000000000000) } require(msg.sender == recipient, "SubscriptionModule::isRecipient: MSG_SENDER_NOT_RECIPIENT_ERC"); } else { //we are sending ETH, so check the sender matches to argument require(msg.sender == to, "SubscriptionModule::isRecipient: MSG_SENDER_NOT_RECIPIENT_ETH"); } _cancelSubscription(keccak256(subHashData)); return true; } /// @dev Allows to execute a Safe transaction confirmed by required number of owners and then pays the account that /// submitted the transaction. /// @return bool hash of on sub to revoke or cancel function cancelSubscription( bytes32 subscriptionHash, bytes memory signatures ) public returns (bool) { bytes32 cancelHash = getSubscriptionActionHash(subscriptionHash, "cancel"); require( _checkHash(cancelHash, signatures), "SubscriptionModule::cancelSubscription: INVALID_DATA: SIGNATURES_INVALID" ); _cancelSubscription(subscriptionHash); return true; } function _cancelSubscription(bytes32 subscriptionHash) internal { Meta storage sub = subscriptions[subscriptionHash]; require( (sub.status != GEnum.SubscriptionStatus.CANCELLED && sub.status != GEnum.SubscriptionStatus.EXPIRED), "SubscriptionModule::_cancelSubscription: INVALID_STATE: SUB_STATUS" ); emit StatusChanged( subscriptionHash, sub.status, GEnum.SubscriptionStatus.CANCELLED ); sub.status = GEnum.SubscriptionStatus.CANCELLED; if (sub.status != GEnum.SubscriptionStatus.INIT) { sub.endDate = sub.nextWithdraw; } sub.nextWithdraw = 0; emit NextPayment( subscriptionHash, sub.nextWithdraw ); } /// @dev used to help mitigate stack issues /// @return bool function _processSub( bytes32 subscriptionHash, uint256[4] memory processedMeta ) internal returns (bool) { uint256 period = processedMeta[0]; uint256 offChainID = processedMeta[1]; uint256 startDate = processedMeta[2]; uint256 endDate = processedMeta[3]; uint256 withdrawHolder; Meta storage sub = subscriptions[subscriptionHash]; require( (sub.status != GEnum.SubscriptionStatus.EXPIRED && sub.status != GEnum.SubscriptionStatus.CANCELLED), "SubscriptionModule::_processSub: INVALID_STATE: SUB_STATUS" ); if (sub.status == GEnum.SubscriptionStatus.INIT) { if (endDate != 0) { require( endDate >= now, "SubscriptionModule::_processSub: INVALID_DATA: SUB_END_DATE" ); sub.endDate = endDate; } if (startDate != 0) { require( startDate >= now, "SubscriptionModule::_processSub: INVALID_DATA: SUB_START_DATE" ); sub.nextWithdraw = startDate; sub.status = GEnum.SubscriptionStatus.TRIAL; emit StatusChanged( subscriptionHash, GEnum.SubscriptionStatus.INIT, GEnum.SubscriptionStatus.TRIAL ); //emit here because of early method exit after trial setup emit NextPayment( subscriptionHash, sub.nextWithdraw ); return false; } else { sub.nextWithdraw = now; sub.status = GEnum.SubscriptionStatus.VALID; emit StatusChanged( subscriptionHash, GEnum.SubscriptionStatus.INIT, GEnum.SubscriptionStatus.VALID ); } } else if (sub.status == GEnum.SubscriptionStatus.TRIAL) { require( now >= startDate, "SubscriptionModule::_processSub: INVALID_STATE: SUB_START_DATE" ); sub.nextWithdraw = now; sub.status = GEnum.SubscriptionStatus.VALID; emit StatusChanged( subscriptionHash, GEnum.SubscriptionStatus.TRIAL, GEnum.SubscriptionStatus.VALID ); } require( sub.status == GEnum.SubscriptionStatus.VALID, "SubscriptionModule::_processSub: INVALID_STATE: SUB_STATUS" ); require( now >= sub.nextWithdraw && sub.nextWithdraw != 0, "SubscriptionModule::_processSub: INVALID_STATE: SUB_NEXT_WITHDRAW" ); if ( period == uint256(GEnum.Period.DAY) ) { withdrawHolder = BokkyPooBahsDateTimeLibrary.addDays(sub.nextWithdraw, 1); } else if ( period == uint256(GEnum.Period.WEEK) ) { withdrawHolder = BokkyPooBahsDateTimeLibrary.addDays(sub.nextWithdraw, 7); } else if ( period == uint256(GEnum.Period.MONTH) ) { withdrawHolder = BokkyPooBahsDateTimeLibrary.addMonths(sub.nextWithdraw, 1); } else if ( period == uint256(GEnum.Period.YEAR) ) { withdrawHolder = BokkyPooBahsDateTimeLibrary.addYears(sub.nextWithdraw, 1); } else { revert("SubscriptionModule::_processSub: INVALID_DATA: PERIOD"); } //if a subscription is expiring and its next withdraw timeline is beyond hte time of the expiration //modify the status if (sub.endDate != 0 && withdrawHolder >= sub.endDate) { sub.nextWithdraw = 0; emit StatusChanged( subscriptionHash, sub.status, GEnum.SubscriptionStatus.EXPIRED ); sub.status = GEnum.SubscriptionStatus.EXPIRED; } else { sub.nextWithdraw = withdrawHolder; } emit NextPayment( subscriptionHash, sub.nextWithdraw ); return true; } function getSubscriptionMetaBytes( uint256 oracle, uint256 period, uint256 offChainID, uint256 startDate, uint256 endDate ) public pure returns (bytes memory) { return abi.encodePacked( oracle, period, offChainID, startDate, endDate ); } /// @dev Returns hash to be signed by owners. /// @param to Destination address. /// @param value Ether value. /// @param data Data payload. /// @param operation Operation type. /// @param safeTxGas Gas that should be used for the safe transaction. /// @param dataGas Gas costs for data used to trigger the safe transaction. /// @param gasPrice Maximum gas price that should be used for this transaction. /// @param gasToken Token address (or 0 if ETH) that is used for the payment. /// @param meta bytes refundReceiver / period / offChainID / endDate /// @return Subscription hash. function getSubscriptionHash( address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 safeTxGas, uint256 dataGas, uint256 gasPrice, address gasToken, address refundReceiver, bytes memory meta ) public view returns (bytes32) { return keccak256( encodeSubscriptionData( to, value, data, operation, safeTxGas, dataGas, gasPrice, gasToken, refundReceiver, meta ) ); } /// @dev Returns hash to be signed by owners for cancelling a subscription function getSubscriptionActionHash( bytes32 subscriptionHash, string memory action ) public view returns (bytes32) { bytes32 safeSubCancelTxHash = keccak256( abi.encode( SAFE_SUB_CANCEL_TX_TYPEHASH, subscriptionHash, keccak256(abi.encodePacked(action)) ) ); return keccak256( abi.encodePacked( byte(0x19), byte(0x01), domainSeparator, safeSubCancelTxHash ) ); } /// @dev Returns the bytes that are hashed to be signed by owners. /// @param to Destination address. /// @param value Ether value. /// @param data Data payload. /// @param operation Operation type. /// @param safeTxGas Fas that should be used for the safe transaction. /// @param gasToken Token address (or 0 if ETH) that is used for the payment. /// @param meta bytes packed data(refund address, period, offChainID, endDate /// @return Subscription hash bytes. function encodeSubscriptionData( address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 safeTxGas, uint256 dataGas, uint256 gasPrice, address gasToken, address refundReceiver, bytes memory meta ) public view returns (bytes memory) { bytes32 safeSubTxHash = keccak256( abi.encode( SAFE_SUB_TX_TYPEHASH, to, value, keccak256(data), operation, safeTxGas, dataGas, gasPrice, gasToken, refundReceiver, keccak256(meta) ) ); return abi.encodePacked( byte(0x19), byte(0x01), domainSeparator, safeSubTxHash ); } /// @dev Allows to estimate a Safe transaction. /// This method is only meant for estimation purpose, therfore two different protection mechanism against execution in a transaction have been made: /// 1.) The method can only be called from the safe itself /// 2.) The response is returned with a revert /// When estimating set `from` to the address of the safe. /// Since the `estimateGas` function includes refunds, call this method to get an estimated of the costs that are deducted from the safe with `execTransaction` /// @param to Destination address of Safe transaction. /// @param value Ether value of Safe transaction. /// @param data Data payload of Safe transaction. /// @param operation Operation type of Safe transaction. /// @param meta meta data of subscription agreement /// @return Estimate without refunds and overhead fees (base transaction and payload data gas costs). function requiredTxGas( address to, uint256 value, bytes memory data, Enum.Operation operation, bytes memory meta ) public returns (uint256) { //check to ensure this method doesn't actually get executed outside of a call function require( msg.sender == address(this), "SubscriptionModule::requiredTxGas: INVALID_DATA: MSG_SENDER" ); uint256 startGas = gasleft(); // We don't provide an error message here, as we use it to return the estimate // solium-disable-next-line error-reason (uint256 conversionRate, uint256[4] memory pMeta) = _processMeta(meta); //Oracle Registry address data is in slot1 if (conversionRate != uint256(0)) { require( value > 1.00 ether, "SubscriptionModule::requiredTxGas: INVALID_FORMAT: DYNAMIC_PRICE_FORMAT" ); uint256 payment = value.wdiv(conversionRate); value = payment; } require( manager.execTransactionFromModule(to, value, data, operation), "SubscriptionModule::requiredTxGas: INVALID_EXEC: SUB_PAY" ); uint256 requiredGas = startGas.sub(gasleft()); // Convert response to string and return via error message revert(string(abi.encodePacked(requiredGas))); } }
we are sending ETH, so check the sender matches to argument
require(msg.sender == to, "SubscriptionModule::isRecipient: MSG_SENDER_NOT_RECIPIENT_ETH");
13,063,689
[ 1, 1814, 854, 5431, 512, 2455, 16, 1427, 866, 326, 5793, 1885, 358, 1237, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5411, 2583, 12, 3576, 18, 15330, 422, 358, 16, 315, 6663, 3120, 2866, 291, 18241, 30, 13771, 67, 1090, 18556, 67, 4400, 67, 862, 7266, 1102, 2222, 67, 1584, 44, 8863, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xc9A690f3415ecc9b8e90010961E7178083932CD3/sources/rwgs11i.sol
Anti-bot and anti-whale mappings and variables Seller Map Blacklist Map block number of opened trading exclude from fees and max transaction amount store addresses that a automatic market maker pairs. Any transfer *to* these addresses could be subject to a maximum transfer amount
contract rwgs11i is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; address public constant deadAddress = address(0x000000000000000000000000000000000000dEaD); bool private swapping; address public marketingWallet; address public devWallet; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; bool public lpBurnEnabled = true; uint256 public lpBurnFrequency = 7200 seconds; uint256 public lastLpBurnTime; uint256 public manualBurnFrequency = 30 minutes; uint256 public lastManualLpBurnTime; bool public limitsInEffect = true; bool public tradingActive = false; bool public swapEnabled = false; bool public enableEarlySellTax = true; mapping (address => uint256) private _holderFirstBuyTimestamp; mapping (address => bool) private _blacklist; 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 earlySellLiquidityFee; uint256 public earlySellMarketingFee; uint256 public tokensForMarketing; uint256 public tokensForLiquidity; uint256 public tokensForDev; uint256 launchedAt; mapping (address => bool) private _isExcludedFromFees; mapping (address => bool) public _isExcludedMaxTransactionAmount; 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("RonWeasleyGenslerSpyro11Inu", "ETH") { 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 = 0; uint256 _buyLiquidityFee = 0; uint256 _buyDevFee = 10; uint256 _sellMarketingFee = 0; uint256 _sellLiquidityFee = 0; uint256 _sellDevFee = 25; uint256 _earlySellLiquidityFee = 0; uint256 _earlySellMarketingFee = 0; uint256 totalSupply = 420 * 1e9 * 1e18; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; earlySellLiquidityFee = _earlySellLiquidityFee; earlySellMarketingFee = _earlySellMarketingFee; 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 { } function enableTrading() external onlyOwner { tradingActive = true; swapEnabled = true; lastLpBurnTime = block.timestamp; launchedAt = block.number; } function removeLimits() external onlyOwner returns (bool){ limitsInEffect = false; return true; } function disableTransferDelay() external onlyOwner returns (bool){ transferDelayEnabled = false; return true; } function setEarlySellTax(bool onoff) external onlyOwner { enableEarlySellTax = onoff; } 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() * 5 / 1000)/1e18, "Cannot set maxTransactionAmount lower than 0.5%"); maxTransactionAmount = newNum * (10**18); } function updateMaxWalletAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 15 / 1000)/1e18, "Cannot set maxWallet lower than 1.5%"); maxWallet = newNum * (10**18); } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } 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 <= 1, "Must keep fees at 1% or less"); } function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee, uint256 _earlySellLiquidityFee, uint256 _earlySellMarketingFee) external onlyOwner { sellMarketingFee = _marketingFee; sellLiquidityFee = _liquidityFee; sellDevFee = _devFee; earlySellLiquidityFee = _earlySellLiquidityFee; earlySellMarketingFee = _earlySellMarketingFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; require(sellTotalFees <= 99, "Must keep fees at 99% or less"); } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function blacklistAccount (address account, bool isBlacklisted) public onlyOwner { _blacklist[account] = isBlacklisted; } 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"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); 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."); } 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; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } 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"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = false; } 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(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } 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 _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"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); 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."); } 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; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } 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"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = false; } 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(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } 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 _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"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); 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."); } 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; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } 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"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = false; } 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(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } 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 _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"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); 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."); } 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; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } 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"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = false; } 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(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } 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 _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"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); 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."); } 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; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } 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"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = false; } 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(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } 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 _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"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); 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."); } 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; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } 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"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = false; } 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(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } 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 _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"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); 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."); } 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; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } 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"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = false; } 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(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } 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 _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"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); 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."); } 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; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } 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"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = false; } 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(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } 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 _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"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); 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."); } 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; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } 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"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = false; } 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(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } 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 _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"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); 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."); } 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; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } 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"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = false; } 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(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } 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); } if (block.number <= (launchedAt + 0) && 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"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); 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."); } 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; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } 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"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = false; } 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(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } 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 _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"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); 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."); } 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; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } 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"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = false; } 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(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } 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 _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"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); 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."); } 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; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } 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"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = false; } 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(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } 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 _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"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); 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."); } 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; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } 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"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = false; } 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(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } 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 _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"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); 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."); } 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; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } 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"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = false; } 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(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } 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 _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"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); 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."); } 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; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } 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"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = false; } 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(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } 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 _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"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); 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."); } 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; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } 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"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = false; } 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(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } 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 _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"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); 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."); } 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; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } 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"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = false; } 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(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } 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 { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { _approve(address(this), address(uniswapV2Router), tokenAmount); address(this), tokenAmount, deadAddress, block.timestamp ); } uniswapV2Router.addLiquidityETH{value: ethAmount}( function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if(contractBalance > swapTokensAtAmount * 20){ contractBalance = swapTokensAtAmount * 20; } 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; if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } } if(contractBalance == 0 || totalTokensToSwap == 0) {return;} function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if(contractBalance > swapTokensAtAmount * 20){ contractBalance = swapTokensAtAmount * 20; } 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; if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } } (success,) = address(devWallet).call{value: ethForDev}(""); function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if(contractBalance > swapTokensAtAmount * 20){ contractBalance = swapTokensAtAmount * 20; } 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; 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; uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div(10000); if (amountToBurn > 0){ super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit AutoNukeLP(); return true; } 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); } 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; uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000); if (amountToBurn > 0){ super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit ManualNukeLP(); 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; uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000); if (amountToBurn > 0){ super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit ManualNukeLP(); return true; } }
9,199,726
[ 1, 14925, 77, 17, 4819, 471, 30959, 17, 3350, 5349, 7990, 471, 3152, 4352, 749, 1635, 22467, 1098, 1635, 1203, 1300, 434, 10191, 1284, 7459, 4433, 628, 1656, 281, 471, 943, 2492, 3844, 1707, 6138, 716, 279, 5859, 13667, 312, 6388, 5574, 18, 5502, 7412, 358, 4259, 6138, 3377, 506, 3221, 358, 279, 4207, 7412, 3844, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 7985, 564, 2499, 77, 353, 4232, 39, 3462, 16, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 7010, 565, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 1071, 11732, 640, 291, 91, 438, 58, 22, 8259, 31, 203, 565, 1758, 1071, 11732, 640, 291, 91, 438, 58, 22, 4154, 31, 203, 565, 1758, 1071, 5381, 8363, 1887, 273, 1758, 12, 20, 92, 12648, 12648, 12648, 12648, 2787, 72, 41, 69, 40, 1769, 203, 7010, 565, 1426, 3238, 7720, 1382, 31, 203, 7010, 565, 1758, 1071, 13667, 310, 16936, 31, 203, 565, 1758, 1071, 4461, 16936, 31, 203, 7010, 565, 2254, 5034, 1071, 943, 3342, 6275, 31, 203, 565, 2254, 5034, 1071, 7720, 5157, 861, 6275, 31, 203, 565, 2254, 5034, 1071, 943, 16936, 31, 203, 7010, 565, 1426, 1071, 12423, 38, 321, 1526, 273, 638, 31, 203, 565, 2254, 5034, 1071, 12423, 38, 321, 13865, 273, 2371, 6976, 3974, 31, 203, 565, 2254, 5034, 1071, 1142, 48, 84, 38, 321, 950, 31, 203, 7010, 565, 2254, 5034, 1071, 11297, 38, 321, 13865, 273, 5196, 6824, 31, 203, 565, 2254, 5034, 1071, 1142, 25139, 48, 84, 38, 321, 950, 31, 203, 7010, 565, 1426, 1071, 8181, 382, 12477, 273, 638, 31, 203, 565, 1426, 1071, 1284, 7459, 3896, 273, 629, 31, 203, 565, 1426, 1071, 7720, 1526, 273, 629, 31, 203, 565, 1426, 1071, 4237, 41, 20279, 55, 1165, 7731, 273, 638, 31, 203, 7010, 7010, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 4505, 3759, 2 ]
./full_match/43113/0xB720928c767dbd20ca56BD49A0c80ECA44C3Faad/sources/contracts/KeeperEnabledCellSub.sol
---------- Constructor ---------- */
constructor(uint256 updateInterval, uint256 subsidy) public { owner = msg.sender; interval = updateInterval; amount = subsidy; lastTimeStamp = block.timestamp; }
13,177,215
[ 1, 15392, 11417, 12181, 342, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 12, 11890, 5034, 1089, 4006, 16, 2254, 5034, 720, 7453, 93, 13, 1071, 288, 203, 3639, 3410, 273, 1234, 18, 15330, 31, 203, 3639, 3673, 273, 1089, 4006, 31, 203, 3639, 3844, 273, 720, 7453, 93, 31, 203, 3639, 1142, 21536, 273, 1203, 18, 5508, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "./interfaces/AggregatorV3Interface.sol"; library SafeDiv { /** * @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, "SafeMath: division by zero"); int256 c = a / b; return c; } } contract PriceConsumerV3 { using SafeDiv for int256; AggregatorV3Interface internal priceFeedEth; AggregatorV3Interface internal priceFeedJPY; /** * Network: Rinkeby * Aggregator: ETH/USD * Address: 0x8A753747A1Fa494EC906cE90E9f37563A8AF630e */ /** * Network: Rinkeby * Aggregator: JPY/USD * Address: 0x3Ae2F46a2D84e3D5590ee6Ee5116B80caF77DeCA */ constructor() public { priceFeedEth = AggregatorV3Interface(address(0x8A753747A1Fa494EC906cE90E9f37563A8AF630e)); priceFeedJPY = AggregatorV3Interface(address(0x3Ae2F46a2D84e3D5590ee6Ee5116B80caF77DeCA)); } /** * Returns the latest price */ function getLatestPrice() public view returns (int) { ( uint80 roundID1, int price1, uint startedAt1, uint timeStamp1, uint80 answeredInRound1 ) = priceFeedEth.latestRoundData(); ( uint80 roundID2, int price2, uint startedAt2, uint timeStamp2, uint80 answeredInRound2 ) = priceFeedJPY.latestRoundData(); return price1.div(price2); } }
* @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, "SafeMath: division by zero"); int256 c = a / b; return c; }
12,618,529
[ 1, 1356, 326, 3571, 16536, 434, 2795, 6726, 12321, 18, 868, 31537, 603, 16536, 635, 3634, 18, 1021, 563, 353, 16729, 23248, 3634, 18, 9354, 2680, 358, 348, 7953, 560, 1807, 1375, 19, 68, 3726, 18, 3609, 30, 333, 445, 4692, 279, 1375, 266, 1097, 68, 11396, 261, 12784, 15559, 4463, 16189, 640, 869, 19370, 13, 1323, 348, 7953, 560, 4692, 392, 2057, 11396, 358, 15226, 261, 17664, 310, 777, 4463, 16189, 2934, 29076, 30, 300, 1021, 15013, 2780, 506, 3634, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 3739, 12, 474, 5034, 279, 16, 509, 5034, 324, 13, 2713, 16618, 1135, 261, 474, 5034, 13, 288, 203, 3639, 2583, 12, 70, 405, 374, 16, 315, 9890, 10477, 30, 16536, 635, 3634, 8863, 203, 3639, 509, 5034, 276, 273, 279, 342, 324, 31, 203, 203, 3639, 327, 276, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.11; // Part: OpenZeppelin/[email protected]/Address /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; 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); } } } } // Part: OpenZeppelin/[email protected]/Context /** * @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; } } // Part: OpenZeppelin/[email protected]/Counters /** * @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; } } // Part: OpenZeppelin/[email protected]/IAccessControl /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @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; } // Part: OpenZeppelin/[email protected]/IERC165 /** * @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); } // Part: OpenZeppelin/[email protected]/IERC721Receiver /** * @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); } // Part: OpenZeppelin/[email protected]/ReentrancyGuard /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // Part: OpenZeppelin/[email protected]/Strings /** * @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); } } // Part: OpenZeppelin/[email protected]/ERC165 /** * @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; } } // Part: OpenZeppelin/[email protected]/IERC721 /** * @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; } // Part: OpenZeppelin/[email protected]/Ownable /** * @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); } } // Part: OpenZeppelin/[email protected]/Pausable /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // Part: OpenZeppelin/[email protected]/AccessControl /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev 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(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{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 ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // Part: OpenZeppelin/[email protected]/Escrow /** * @title Escrow * @dev Base escrow contract, holds funds designated for a payee until they * withdraw them. * * Intended usage: This contract (and derived escrow contracts) should be a * standalone contract, that only interacts with the contract that instantiated * it. That way, it is guaranteed that all Ether will be handled according to * the `Escrow` rules, and there is no need to check for payable functions or * transfers in the inheritance tree. The contract that uses the escrow as its * payment method should be its owner, and provide public methods redirecting * to the escrow's deposit and withdraw. */ contract Escrow is Ownable { using Address for address payable; event Deposited(address indexed payee, uint256 weiAmount); event Withdrawn(address indexed payee, uint256 weiAmount); mapping(address => uint256) private _deposits; function depositsOf(address payee) public view returns (uint256) { return _deposits[payee]; } /** * @dev Stores the sent amount as credit to be withdrawn. * @param payee The destination address of the funds. */ function deposit(address payee) public payable virtual onlyOwner { uint256 amount = msg.value; _deposits[payee] += amount; emit Deposited(payee, amount); } /** * @dev Withdraw accumulated balance for a payee, forwarding all gas to the * recipient. * * WARNING: Forwarding all gas opens the door to reentrancy vulnerabilities. * Make sure you trust the recipient, or are either following the * checks-effects-interactions pattern or using {ReentrancyGuard}. * * @param payee The address whose funds will be withdrawn and transferred to. */ function withdraw(address payable payee) public virtual onlyOwner { uint256 payment = _deposits[payee]; _deposits[payee] = 0; payee.sendValue(payment); emit Withdrawn(payee, payment); } } // Part: OpenZeppelin/[email protected]/IERC721Enumerable /** * @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); } // Part: OpenZeppelin/[email protected]/IERC721Metadata /** * @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); } // Part: OpenZeppelin/[email protected]/ERC721 /** * @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 {} } // Part: OpenZeppelin/[email protected]/PullPayment /** * @dev Simple implementation of a * https://consensys.github.io/smart-contract-best-practices/recommendations/#favor-pull-over-push-for-external-calls[pull-payment] * strategy, where the paying contract doesn't interact directly with the * receiver account, which must withdraw its payments itself. * * Pull-payments are often considered the best practice when it comes to sending * Ether, security-wise. It prevents recipients from blocking execution, and * eliminates reentrancy concerns. * * 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]. * * To use, derive from the `PullPayment` contract, and use {_asyncTransfer} * instead of Solidity's `transfer` function. Payees can query their due * payments with {payments}, and retrieve them with {withdrawPayments}. */ abstract contract PullPayment { Escrow private immutable _escrow; constructor() { _escrow = new Escrow(); } /** * @dev Withdraw accumulated payments, forwarding all gas to the recipient. * * Note that _any_ account can call this function, not just the `payee`. * This means that contracts unaware of the `PullPayment` protocol can still * receive funds this way, by having a separate account call * {withdrawPayments}. * * WARNING: Forwarding all gas opens the door to reentrancy vulnerabilities. * Make sure you trust the recipient, or are either following the * checks-effects-interactions pattern or using {ReentrancyGuard}. * * @param payee Whose payments will be withdrawn. */ function withdrawPayments(address payable payee) public virtual { _escrow.withdraw(payee); } /** * @dev Returns the payments owed to an address. * @param dest The creditor's address. */ function payments(address dest) public view returns (uint256) { return _escrow.depositsOf(dest); } /** * @dev Called by the payer to store the sent amount as credit to be pulled. * Funds sent in this way are stored in an intermediate {Escrow} contract, so * there is no danger of them being spent before withdrawal. * * @param dest The destination address of the funds. * @param amount The amount to transfer. */ function _asyncTransfer(address dest, uint256 amount) internal virtual { _escrow.deposit{value: amount}(dest); } } // Part: OpenZeppelin/[email protected]/ERC721Burnable /** * @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); } } // Part: OpenZeppelin/[email protected]/ERC721Enumerable /** * @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(); } } // Part: OpenZeppelin/[email protected]/ERC721URIStorage /** * @dev ERC721 token with storage based token URI management. */ abstract contract ERC721URIStorage is ERC721 { using Strings for uint256; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = _baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } return super.tokenURI(tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @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 override { super._burn(tokenId); if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } } // Part: RPSCollectible /// @title Scissors Contract. /// Contract by RpsNft_Art /// Contract created by: (SHA-256) d735dfa8fa552fcb02c42894edebb4652d44697d1636b6125d2367caf2ade334 abstract contract RPSCollectible is ERC721, ERC721URIStorage, ERC721Enumerable, ERC721Burnable, Ownable, Pausable, AccessControl, PullPayment, ReentrancyGuard { // Events Declaration event preSales(bool on_off); event preSalesCompleted(); event baseURIChanged(string _baseURI); event maxPreSalesReached(uint256 _maxPresales); event maxWhiteListReached(uint256 _maxWhiteList); event maxPublicSalesReached(uint256 _maxDrop); // Usings using Counters for Counters.Counter; using Address for address; // isContract() using Strings for uint256; // toString() // Counters Counters.Counter internal _tokenIdCounter; Counters.Counter internal _presalesCounter; // Keep track of per-wallet minting amounts during pre-sales mapping(address => uint256) internal _preSalesMinted; // Keep track of per-wallet minting amounts for white lists mapping(address => uint256) internal _whiteListMinted; // WhiteList controls uint256 private wlAllocatedAmount = 0; bool private wlAllocated = false; string internal _baseTokenURI; uint256 internal maxDrop;// = eg. 10000; uint256 internal preSalesMintPrice; // = In Weis e.g 55000000000000000; uint256 internal mintPrice; // = In Weis e.g. 75000000000000000; uint256 internal maxPresales; // = e.g 3000 uint256 internal maxPresalesNFTAmount; // = e.g 2 uint256 internal maxWhiteListNFTAmount; // = e.g 5 uint256 internal maxSalesNFTAmount; // e.g 25 uint256 internal maxWhiteListAmount; // e.g 150; bool internal _inPresalesMode = false; bool internal _preSalesFinished = false; bool internal _publicSalesFinished = false; // List Roles bytes32 public constant PRESALES_ROLE = keccak256("RPS_PRESALES"); bytes32 public constant WHITELIST_ROLE = keccak256("RPS_WHITELIST"); /** * * Constructor : Owner created * */ constructor(string memory _name, string memory _symbol) ERC721(_name,_symbol) AccessControl() { // super constructors require(!(msg.sender.isContract())); // dev: The address is not an account // set initial flags as false // (not in presales, presales not finished and public sales not finished) _inPresalesMode = false; _preSalesFinished = false; _publicSalesFinished = false; // do not allow minting to begin with preSalesOff(); pause(); // msg.sender (owner) is the root and admin _presalesCounter.reset(); _tokenIdCounter.reset(); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); // Init white list wlAllocatedAmount = 0; wlAllocated = false; } /** ---- ANYONE CAN CALL, SOME EXTERNAL ONLY ---- */ /** * Returns number of white list allocated */ function getWlAllocatedAmount() public view returns(uint256) { return(wlAllocatedAmount); } /** * * Returns whether or not the contract is in preSales mode * */ function inPresales() public view returns(bool) { return (_inPresalesMode && !_preSalesFinished); } /** * * Returns whether or not the contract is in public Sales mode * */ function inPublicSales() public view returns(bool) { return _preSalesFinished && !paused() && !_publicSalesFinished; } /** * * Returns whether or not preSales has finished * */ function preSalesFinished() public view returns(bool) { return _preSalesFinished; } /** * * Returns whether or not public Sales has finished * */ function publicSalesFinished() public view returns(bool) { return _publicSalesFinished; } /** * * Returns whether or not an address is in the presales list * */ function AddrInPresales(address _account) public view returns (bool){ return _inPresalesMode && !_preSalesFinished && hasRole(PRESALES_ROLE,_account) && (_preSalesMinted[_account]) < maxPresalesNFTAmount; } /** * * Returns whether or not an address is in the white list * */ function AddrInWhiteList(address _account) public view returns (bool){ return hasRole(WHITELIST_ROLE,_account) && (_whiteListMinted[_account]) < maxWhiteListNFTAmount; } /** * * Returns whether or not caller function is in the presales list * */ function AmIinPresales() external view returns (bool) { return AddrInPresales(msg.sender); } /** * * Returns max drop * */ function getMaxDrop() external view returns(uint256) { return maxDrop; } /** * * Returns tokenURI for the provider token id * */ function tokenURI(uint256 tokenId) public view override(ERC721, ERC721URIStorage) returns (string memory) { require(_exists(tokenId)); // dev: ERC721Metadata, URI query for nonexistent token string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString(),".json")) : ""; } /** * * Payable mint during pre-sales * */ function preSalesMint(uint256 amount) public payable onlyRole(PRESALES_ROLE) { require(!(msg.sender.isContract())); // dev: The address is not an account require(totalSupply() + amount <= maxPresales); // dev: Pre-sales SOLD-OUT require(!_preSalesFinished || msg.sender == owner()); // dev: Pre-sales has already finished require(_inPresalesMode || msg.sender == owner()); // dev: Pre-sales has not started yet require(!paused() || msg.sender == owner()); // dev: Minting is paused require(msg.value == preSalesMintPrice*amount || msg.sender == owner()); // dev: Wrong price provided require(hasRole(PRESALES_ROLE, msg.sender) || msg.sender == owner()); // dev: Wallet not elligible require(amount <= maxPresalesNFTAmount); // dev: Cannot mint the specified amount in pre-sales require((_preSalesMinted[msg.sender] + amount) <= maxPresalesNFTAmount); // dev: Total pre-sales amount exceeded for wallet // Mint the amount of tokens! _coreMint(amount); // this was the last pre-sales minting based on the max presales allowed if(totalSupply() == maxPresales) { _preSalesFinished = true; _inPresalesMode = false; emit maxPreSalesReached(maxPresales); } // Keep track of wallet's pre-mint amount _preSalesMinted[msg.sender] += amount; } /** * To allow owners to reserve some collectibles at the begginning */ function initialMint(uint256 amount) external onlyOwner { require(msg.sender == owner()); // dev: not owner require(!(msg.sender.isContract())); // dev: The address is not an account require(!wlAllocated); // dev: initial amount already allocated require((wlAllocatedAmount + amount) <= maxWhiteListAmount); // dev: the initial amount is exceeded require((totalSupply() + amount) <= maxDrop); // dev: SOLD OUT! // Mint the amount! _coreMint(amount); wlAllocatedAmount += amount; if(wlAllocatedAmount == maxWhiteListAmount) { wlAllocated = true; emit maxWhiteListReached(maxWhiteListAmount); } } /** * * Not Payable mint * */ function whiteListMint(uint256 amount) public onlyRole(WHITELIST_ROLE) { require(!wlAllocated); // dev: initial amount already allocated require(!(msg.sender.isContract())); // dev: The address is not an account require((wlAllocatedAmount + amount) <= maxWhiteListAmount); // dev: the initial amount is exceeded require(hasRole(WHITELIST_ROLE, msg.sender) || msg.sender == owner()); // dev: Wallet not elligible require(totalSupply() + amount <= maxDrop); // dev: SOLD OUT! require((_whiteListMinted[msg.sender] + amount) <= maxWhiteListNFTAmount); // dev: Total amount exceeded for white-listed wallet // Mint the amount of tokens! _coreMint(amount); wlAllocatedAmount += amount; if(wlAllocatedAmount >= maxWhiteListAmount) { wlAllocated = true; emit maxWhiteListReached(maxWhiteListAmount); } // Keep track of wallet's white list amount _whiteListMinted[msg.sender] += amount; } /** * * Payable Public Sales mint version * */ function mint(uint256 amount) public payable { require(!(msg.sender.isContract())); // dev: The address is not an account require(_preSalesFinished || msg.sender == owner()); // dev: Pre-sales has not finished yet require(!paused() || msg.sender == owner()); // dev: Minting is paused require(msg.value == mintPrice*amount || msg.sender == owner()); // dev: Wrong price provided require(totalSupply() + amount <= maxDrop); // dev: SOLD OUT! require(amount <= maxSalesNFTAmount); // dev: Specified amount exceeds per-wallet maximum mint // Mint the amount! _coreMint(amount); // this was the last pre-sales minting based on the max presales allowed if(totalSupply() == maxDrop) { _publicSalesFinished = true; emit maxPublicSalesReached(maxDrop); } // Reserve in TH as per Roadmap _accumulateTH(); } /** ---------- ONLY OWNER CAN CALL EXTERNALLY ------------ */ /** * * Change baseURI * */ function setBaseURI(string memory baseURI) external onlyOwner { _baseTokenURI = baseURI; emit baseURIChanged(_baseTokenURI); } /** * * External function to allow to provide a list of addresses to be white listed * */ function addToWhiteList(address[] memory whiteListAddr) external onlyOwner { uint256 numAddrs = whiteListAddr.length; for(uint256 i=0;i<numAddrs;i++) { addToWhiteList(whiteListAddr[i]); } } /** * * External function to allow to provide a list of addresses to be white listed * fo presales * */ function addToPresalesList(address[] memory presalesAddr) external onlyOwner { require(!_preSalesFinished); // dev: Pre-sales period has already finished uint256 numAddrs = presalesAddr.length; for(uint256 i=0;i<numAddrs;i++) { addToPresalesList(presalesAddr[i]); } } /** ---------- ONLY OWNER CAN CALL, EVERYWHERE ------------ */ /** * * Allow to pause minting * */ function pause() public onlyOwner { _pause(); } /** * * Allow to unpause minting * */ function unpause() public onlyOwner { _unpause(); } /** * * Allow to enable or disable pre-sales * */ function preSalesOn() public onlyOwner { _inPresalesMode = true; _preSalesFinished = false; emit preSales(_inPresalesMode); } /** * * Stop presales * */ function preSalesOff() public onlyOwner { _inPresalesMode = false; emit preSales(_inPresalesMode); } /** * * Complete preSales * */ function preSalesComplete() public onlyOwner { _preSalesFinished = true; preSalesOff(); pause(); emit preSalesCompleted(); } /** ------- INTERNAL CALLS ONLY, SOME ONLY BY OWNER -------- */ /** * * Returns baseURI for tokens * */ function _baseURI() internal view virtual override returns (string memory) { return _baseTokenURI; } /** * * Internal: adds the individual provided wallet to the white list list * */ function addToWhiteList(address whiteListAddr) internal onlyOwner { require(!whiteListAddr.isContract()); // dev: The address is not an account require(!hasRole(WHITELIST_ROLE, whiteListAddr)); // dev: Already in list grantRole(WHITELIST_ROLE,whiteListAddr); } /** * * Internal: adds the individual provided wallet to the presales list * */ function addToPresalesList(address presalesAddr) internal onlyOwner { require(!presalesAddr.isContract()); // dev: The address is not an account require(_presalesCounter.current() < maxPresales); // dev: Maximum number of presales reached require(!hasRole(PRESALES_ROLE, presalesAddr)); // dev: Already in list require(!_preSalesFinished); // dev: Pre-sales period has already finished grantRole(PRESALES_ROLE,presalesAddr); _presalesCounter.increment(); } /** * * Internal mint function * */ function _coreMint(uint256 amount) internal { uint256 tokenId; for(uint256 i = 0; i < amount; i++) { // Generate new tokenId _tokenIdCounter.increment(); tokenId = _tokenIdCounter.current(); // mint the tokenId for caller _safeMint(msg.sender, tokenId); } } /** ------- OVERRIDES NEEDED BY SOLIDITY -------- */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal whenNotPaused override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); } function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable, AccessControl) returns (bool) { return super.supportsInterface(interfaceId); } function _burn(uint256 tokenId) internal override(ERC721, ERC721URIStorage) { require(maxDrop>0); // dev: cannot burn more maxDrop = maxDrop-1; super._burn(tokenId); } /** ------- VIRTUAL FUNCTIONS -------- */ function emitMintEvent(uint256 number) internal virtual; function _accumulateTH() internal virtual; /** ------- HELPER FUNCTIONS DURING UNIT TEST, ONLY BY OWNER -------- */ function setMaxDrop(uint256 _maxPresales,uint256 _maxDrop,uint256 _maxWhiteListAmount) public onlyOwner { require(_maxWhiteListAmount <= _maxDrop); // dev: max presales cannot be greater than maxDrop require((_maxWhiteListAmount + _maxPresales) <= _maxDrop); // dev: whitelist and presales sum more than maxdrop require(_maxDrop >= totalSupply()); // dev: cannot set maxDrop below already supply require(_maxPresales <= _maxDrop); // dev: max presales cannot be greater than maxDrop maxDrop = _maxDrop; maxPresales = _maxPresales; maxWhiteListAmount = _maxWhiteListAmount; _accumulateTH(); } function setMaxDrop(uint256 _maxDrop) public onlyOwner { require(_maxDrop >= totalSupply()); // dev: cannot set maxDrop below already supply maxDrop = _maxDrop; _accumulateTH(); } function setMaxSalesNFTAmount(uint256 _maxSalesNFTAmount) public onlyOwner { maxSalesNFTAmount = _maxSalesNFTAmount; } function setMaxWhiteListAmount(uint256 _maxWhiteListAmount) public onlyOwner { maxWhiteListAmount = _maxWhiteListAmount; } /** * Prizes related */ // To avoid reentrancy function withdrawPayments(address payable payee) public override nonReentrant whenNotPaused { super.withdrawPayments(payee); } function sendGiveAway(uint256 _giveAwayId, address[] memory _winners) external onlyOwner virtual whenNotPaused { } /** Semi-random function to allow selection of winner for giveaways*/ function rand(uint256 div) public view returns(uint256) { uint256 seed = uint256(keccak256(abi.encodePacked( block.timestamp + block.difficulty + ((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (block.timestamp)) + block.gaslimit + ((uint256(keccak256(abi.encodePacked(msg.sender)))) / (block.timestamp)) + block.number ))); return (seed - ((seed / div) * div)); } } // File: Scissors.sol // // .,,,,,,,,,,,,,,,,,,,,, // ,,,,,,,,,,,,,,,,,,,,. .,,,, // ,,,, ,,, // ,,,, ((((( , , (( (( ,, // ,,, ((((/(((( ,,,,,,,, (((( ((( ,,, // ,,. (((( (((. ,,,, ,(((((( ,,, // ,,. (((( (((. ,,,,,, ,(((((( ,,, // ,,, ((((((((( .,,, ,,, (((( ,,, // ,,, ,,, // .,, @@@@@@@@@ @@@@@@@@@ @@@@@@@@ ,,, // ,,, @@ @@ @@ @@ @@ ,,, // ,,, @@ @ @@ @@ @@@ ,,, // ,,, @@@@@@@@@ @@@@@@@@@ @@@@@ ,,, // ,,, @@ @ @@ @@@ ,,, // ,,, @@ @@ @@ @@@@@@@@@ ,,,. // ,,, ,,,, // ,,,,. ,,,,,,,,,,,,,,,,,,,,,, // ,,,,,,,,,,,,,,,,,,,,. // // /// @title Scissors Contract. /// Contract by RpsNft_Art /// Contract created by: (SHA-256) d735dfa8fa552fcb02c42894edebb4652d44697d1636b6125d2367caf2ade334 contract Scissors is RPSCollectible { // List of public ETH addresses of RPSNft_Art cofounders and other related participants address private NGOAddress = 0x633b7218644b83D57d90e7299039ebAb19698e9C; // UkraineDAO address private ScissorsSisterAddress = 0x92dd828AF04277f1ae6A4b7B25b5fFfc69f3A677; address private RockbiosaAddress = 0x521A4b1A8A968A232ca2BeCfF66713b209Bca2d7; address private PaperJamAddress = 0x57032e15279f520cb98365138533793dfA32d214; address private RoseLizardAddress = 0x502f9198E63D1EEa55C8Bd62e134d8c04CB66B73; address private SpockAddress = 0xBF2117339eD7A9039D9B996a61876150DDcc6b37; address private MarketingAddress = 0x09870346A435E6Eb14887742824BBC7dAd066776; address private FirstPrizeAddress = 0xD0f5C2aD5abA241A18D8E95e761982D911Ed1B20; address private DreamOnAddress = 0xFfFaBC56a346929f925ddF2dEEc86332CC1Ce437; // Token Ids that will determine the VIPs (using ownerof) uint256 [] private VIPTokens; bool private VIPTokensSet=false; // Events for NFT event CreateScissors(uint256 indexed id); event ReleaseTH(uint256 indexed _pct, uint256 _amount); event AmountWithdrawn(address _target, uint256 _amount); // Events for Prizes event FirstGiveAwayCharged(); event SecondGiveAwayCharged(address[]); event ThirdGiveAwayCharged(string _teamName,address[]); // Number of MAX_VIP_TOKENS uint256 public constant MAX_VIP_TOKENS = 20; // ETHs to acummulate in Treasure Hunt account uint256 public constant TH_POOL = 50000000000000000000; // 50 ETH uint256 public constant TH_FIRST = 5000000000000000000; // 5 ETH uint256 public constant TH_SECOND = 10000000000000000000; // 10 ETH uint256 public constant TH_THIRD = 15000000000000000000; // 15 ETH uint256 public constant TH_FOURTH = 20000000000000000000; // 20 ETH // PCT distributions uint256 public constant COFOUNDER_PCT = 16; // 16 PCT uint256 public constant FIVE_PCT = 5; // 5 PCT // Prizes uint256 public constant TH_PRIZE_PER_WALLET = 5000000000000000000; // 5 ETH uint256 public constant FIRST_PRIZE = 1; uint256 public constant SECOND_PRIZE = 2; uint256 public constant THIRD_PRIZE = 3; uint256 public constant FIRST_PRIZE_TOTAL_ETH_AMOUNT = 4000000000000000000; // 4 ETH uint256 public constant FIRST_PRIZE_FIRST_ETH_AMOUNT = 2500000000000000000; // 2.5 ETH uint256 public constant FIRST_PRIZE_SECOND_ETH_AMOUNT = 1000000000000000000; // 1 ETH uint256 public constant FIRST_PRIZE_THIRD_ETH_AMOUNT = 500000000000000000; // 0.5 ETH uint256 public constant SECOND_PRIZE_TOTAL_ETH_AMOUNT = 5000000000000000000; // 5 ETH uint256 public constant SECOND_PRIZE_PER_WALLET_ETH_AMOUNT = 250000000000000000; // 0.25 ETH uint256 public constant TH_SECOND_PRIZE_MAX_WINNERS = 20; uint256 public constant TH_THIRD_PRIZE_MAX_WINNERS = 10; // track if prizes have been released bool public first_prize_released = false; bool public second_prize_released = false; bool public third_prize_released = false; // Store the TH Secret - Winner will provide the team 50 ETH uint256 private accumulatedTHPrize = 0; bytes32 private th_secret = 0x0; bool private th_secret_set = false; // Usings using Address for address; // Keep track of percentages achieved and accumulation for TH accomplished bool _allocatedTH_25 = false; bool _allocatedTH_50 = false; bool _allocatedTH_75 = false; bool _allocatedTH_100 = false; // table for 2nd prize winners address[] public second_prize_winners; // mapping to register potential 3rd prize winners. Each array of tokenids must be // max of TH_THIRD_PRIZE_MAX_WINNERS. Address index is who represents a given group and who calls // payable function to register group mapping(string => address[]) public third_prize_players; // keep track of team where addresses are registered against mapping(address => string) public registered_th_addresses; string public th_team_winner = ''; /** * RPS = Rock Paper Scissors * MWSA = Mintable Scissors Art */ constructor() RPSCollectible("RPS Scissors", "MSA") { require(!(msg.sender.isContract())); // dev: The address is not an account // So far, to get the metadata from web but soon replace from // pre-loaded IPFS //_baseTokenURI = "ipfs://QmT9Qb3tQfvKC1bnXPqGo5UnBgdU2WK4kq5SzVo4zPcWig/"; maxDrop = 10000; VIPTokensSet = false; preSalesMintPrice = 55000000000000000; // 0.055 ETH mintPrice = 70000000000000000; // 0.070 ETH maxPresales = 3500; // 1750 (250+1500) Max accts, each 2 max so max 3500 NFTs maxPresalesNFTAmount = 2; // Max number of NFTs per wallet to mint during pre-sales maxWhiteListNFTAmount = 2; // Max number of NFTs per wallet to mint per whitelisted account maxSalesNFTAmount = 25; // Max number of NFTs per wallet to mint during sales (no other control per account) maxWhiteListAmount = 150; // Max allowance for whitelisted tokens (including contract owners) accumulatedTHPrize = 0; // to keep track of accumulated TH balance as per roadmap th_secret_set = false; // to be set when secret is resolved } /** ---- ANYONE CAN CALL, SOME EXTERNAL ONLY ---- */ /*** * * Maximum balance that can be withdrawn to secure future prices * */ function maxBalanceToWithdraw() public view returns(uint256) { uint256 balance = address(this).balance; int256 max_balance = int256(balance); // Do not transfer TH pool and prizes part if(!_allocatedTH_25) { // 25% has not been reached so do not allow to withdraw that part max_balance = max_balance - int256 (TH_FIRST) - int256(FIRST_PRIZE_TOTAL_ETH_AMOUNT); } else if(!_allocatedTH_50) { // 50% has not been reached so do not allow to withdraw the TH part (5+10) and 1st prize max_balance = max_balance - int256 (accumulatedTHPrize + TH_SECOND) - int256(FIRST_PRIZE_TOTAL_ETH_AMOUNT); } else if(!_allocatedTH_75) { // 75% has not been reached so do not allow to withdraw the TH part (5+10+15) and 2nd prize max_balance = max_balance - int256 (accumulatedTHPrize + TH_THIRD) - int256(SECOND_PRIZE_TOTAL_ETH_AMOUNT); } else if(!_allocatedTH_100 || !third_prize_released) { // 100% has not been reached, do not allow to release the TH_POOL // OR // 100% reached BUT TH_POOL has not been released yet, do not allow to withdraw it max_balance = max_balance - int256 (TH_POOL); } // if max_balance is positive after ensuring Treasure Hunt // payments, then we can distribute if(max_balance > 0) { balance = uint256(max_balance); } else { balance = 0; } return balance; } /** * * Charging the contract for test purposes: it is just fine by calling this empty payable method * */ function chargeContract() external payable { } /** ---------- ONLY OWNER CAN CALL ------------ */ /** * * Allow to withdraw the accumulated balance among founders, always prioritizing * Treasure Hunt payments * */ function withdraw() external onlyOwner { require(VIPTokensSet); // dev: VIP tokens unknown // Keep amount for prizes uint256 balance = maxBalanceToWithdraw(); require(balance > 0); // dev: nothing to withdraw after securing prizes // Calc stakes from max to withdraw // Solidity missing floats -> first mul then div uint256 cofounder_stk = (balance*COFOUNDER_PCT)/100; // Co-founders uint256 VIP_stk = cofounder_stk / VIPTokens.length; // VIPs participation // Early investor pct, NGO steak, For future marketing campaings, Participation of Dream On uint256 five_pct = (balance*FIVE_PCT)/100; // Transfer for founders transferFounders(cofounder_stk); // Transfer to VIPs transferVIPs(VIP_stk); // Transfer to believer payable(SpockAddress).transfer(five_pct); emit AmountWithdrawn(SpockAddress, five_pct); // Transfer to dream_on payable(DreamOnAddress).transfer(five_pct); emit AmountWithdrawn(DreamOnAddress, five_pct); // Transfer to NGO payable(NGOAddress).transfer(five_pct); emit AmountWithdrawn(NGOAddress, five_pct); // Pool for new marketing investment payable(MarketingAddress).transfer(five_pct); emit AmountWithdrawn(MarketingAddress, five_pct); } /** * * Sets the tokens for cofounding benefits * */ function setVIPTokens(uint256 [] memory _tokens) external onlyOwner { uint256 len = _tokens.length; require(len > 0); // dev: no tokens of VIPs provided require(len <= MAX_VIP_TOKENS); // dev: max number of VIPs is 20 VIPTokens = new uint256[](_tokens.length); for(uint256 i=0;i < len;i++) { VIPTokens[i] = _tokens[i]; } VIPTokensSet = true; } /** * * Allow changing addresses for cofounders * */ function setFounderAddresses(address _ss, address _rb, address _pj, address _rl,address _sp, address _ngo, address _ds, address _do) external onlyOwner { ScissorsSisterAddress = _ss; RockbiosaAddress = _rb; PaperJamAddress = _pj; RoseLizardAddress = _rl; SpockAddress = _sp; NGOAddress = _ngo; MarketingAddress = _ds; DreamOnAddress = _do; } /** * Set First and Second Prize addresses */ function setPrizesAccounts(address _first) external onlyOwner { require(!_first.isContract()); // dev: the address is not an account FirstPrizeAddress = _first; } /** ---------- INTERNAL FUNCTIONS, SOME ONLY OWNER ------------ */ /** * * Specific event created when Scissor mints * */ function emitMintEvent(uint256 collectibleId) internal override { emit CreateScissors(collectibleId); } /** * * Function that is called per every mint and allocates treasure hunt * as per roadmap * * It also accumulates for 1st and 2nd prize * */ function _accumulateTH() internal override { // Everything already allocated in TH if(_allocatedTH_100) return; // Transfer amount of ETHs as per roadmap to TreasureHunt account (25%) if(!_allocatedTH_25 && pctReached(25) && address(this).balance>TH_FIRST) { _allocatedTH_25 = true; accumulatedTHPrize += TH_FIRST; emit ReleaseTH(25, TH_FIRST); } // Transfer amount of ETHs as per roadmap to TreasureHunt account (50%) if(!_allocatedTH_50 && pctReached(50) && address(this).balance>(TH_SECOND + FIRST_PRIZE_TOTAL_ETH_AMOUNT)) { payable(FirstPrizeAddress).transfer(FIRST_PRIZE_TOTAL_ETH_AMOUNT); // Transfer 1st prize _allocatedTH_50 = true; accumulatedTHPrize += TH_SECOND; emit ReleaseTH(50, TH_SECOND); } // Transfer amount of ETHs as per roadmap to TreasureHunt account (75%) if(!_allocatedTH_75 && pctReached(75) && address(this).balance>(TH_THIRD + SECOND_PRIZE_TOTAL_ETH_AMOUNT)) { // send 2nd GiveAway to random owners _secondGiveAway(); _allocatedTH_75 = true; // Accumulate for TH accumulatedTHPrize += TH_THIRD; emit ReleaseTH(75, TH_THIRD); } // Transfer amount of ETHs as per roadmap to TreasureHunt account (100%) if(!_allocatedTH_100 && pctReached(100) && address(this).balance>TH_FOURTH) { _allocatedTH_100 = true; accumulatedTHPrize += TH_FOURTH; emit ReleaseTH(100,TH_FOURTH); } } /** * * Transfer for Founders * */ function transferFounders(uint256 _amount) internal onlyOwner { // divide remainder among founders payable(RockbiosaAddress).transfer(_amount); emit AmountWithdrawn(RockbiosaAddress, _amount); payable(PaperJamAddress).transfer(_amount); emit AmountWithdrawn(PaperJamAddress, _amount); payable(ScissorsSisterAddress).transfer(_amount); emit AmountWithdrawn(ScissorsSisterAddress, _amount); payable(RoseLizardAddress).transfer(_amount); emit AmountWithdrawn(RoseLizardAddress, _amount); } /** * * Transfer for VIPs * */ function transferVIPs(uint256 _amount) internal onlyOwner { require(VIPTokensSet); // dev: VIP tokens unknown // Pull payments of a 10th of the total for VIP // each VIP gets a pullpayment with proportional amount for(uint256 i=0;i < VIPTokens.length;i++) { // get the owner of the item to get payment address _ccfAddr = ownerOf(VIPTokens[i]); _asyncTransfer(_ccfAddr, _amount); emit AmountWithdrawn(_ccfAddr, _amount); } } /** * Prizes related functions */ /** * Returns whether a given percentage has been reached or not */ function pctReached(uint256 pct) public view returns(bool) { bool ret = false; if(pct == 25) { ret = (totalSupply()>=(maxDrop / 4)); } else if(pct == 50) { ret=(totalSupply()>=(maxDrop / 2)); } else if(pct == 75) { ret=(totalSupply()>=((3*maxDrop) / 4)); } else if(pct == 100) { ret=(totalSupply()>=(maxDrop)); } return(ret); } /** * Sets the TH secret up */ function setSecret(bytes32 _secret) external onlyOwner { th_secret = _secret; th_secret_set = true; } function reservedTHPrize() external view returns(uint256) { return accumulatedTHPrize; } function sendGiveAway(uint256 _giveAwayId, address[] memory _winners) public override onlyOwner { uint256[3] memory _prizes = [FIRST_PRIZE_FIRST_ETH_AMOUNT, // 2.5 ETH FIRST_PRIZE_SECOND_ETH_AMOUNT, // 1 ETH FIRST_PRIZE_THIRD_ETH_AMOUNT]; //0.5 ETH if(_giveAwayId == FIRST_PRIZE) { // send first GiveAway _firstGiveAway(_winners,_prizes); } } // Drop 1, once we have achieved 50% of the sales during first drop, // the 3 community members from community members list, who have brought more new members // to the community, will be rewarded with 2.5 ETH the first 1, 1 ETH the second, and 0.5 ETH the third. // Total: 4 ETH function _firstGiveAway(address[] memory _winners,uint256[3] memory _prizes) private onlyOwner { require(pctReached(50)); // dev: 50% not achieved yet require(!first_prize_released); // dev: 1st prize already released require(_winners.length <= 3); // dev: winners array greater than 3 require(address(this).balance >= FIRST_PRIZE_TOTAL_ETH_AMOUNT); // dev: not enough balance in contract for(uint256 i=0;i<_winners.length;i++) { if(_winners[i] != address(0x0)) { _asyncTransfer(_winners[i],_prizes[i]); // 2.5 ETH, 1 ETH, 0.5 ETH // Flag prize as released first_prize_released = true; emit FirstGiveAwayCharged(); } } } // Drop 1, after 75% minting 5 ETH are transferred to 20 random scissors owners (pull payment, 0.5 ETH each) function _secondGiveAway() internal { require(!second_prize_released); // dev: 2nd prize already released require(pctReached(75)); // dev: 75% not achieved yet require(address(this).balance >= SECOND_PRIZE_PER_WALLET_ETH_AMOUNT); // dev: not enough balance in contract uint256 top_75_pct = (3*maxDrop)/4; // calc the 75% of the maxDrop second_prize_winners = new address[](TH_SECOND_PRIZE_MAX_WINNERS); // Get 20 random tokenId numbers from 0...(maxDrop*3)/4 uint256 div = top_75_pct / TH_SECOND_PRIZE_MAX_WINNERS; uint256 seed = rand(div) + 1; // Add payment in escrow contract for(uint256 i = 0; i < TH_SECOND_PRIZE_MAX_WINNERS; i++) { second_prize_winners[i] = ownerOf(seed); _asyncTransfer(second_prize_winners[i],SECOND_PRIZE_PER_WALLET_ETH_AMOUNT); seed = seed + div; } second_prize_released = true; emit SecondGiveAwayCharged(second_prize_winners); } /** * Returns the addresses of token owners (max of TH_THIRD_PRIZE_MAX_WINNERS) * internally called by owner of the tokens */ function getAddressesFromTokens(uint256 [] memory _tokens) internal returns (address [] memory) { address [] memory ret = new address[](_tokens.length); for(uint256 i=0;i<_tokens.length;i++) { address _tokenOwner = ownerOf(_tokens[i]); require(msg.sender == _tokenOwner); // dev: caller is not the owner ret[i] = _tokenOwner; } return ret; } /** * Helper function to determine if one of the addresses is already registered in a team */ function addressesNotRegisteredInTeamYet(address[] memory _addrs) internal returns (bool) { bool ret = true; for(uint256 i=0;i<_addrs.length;i++) { if(bytes(registered_th_addresses[_addrs[i]]).length != 0) { // Address already registered in a team ret = false; break; } } return ret; } function addAddrToTeam(address _addr, string memory _teamName, uint256 _amount) internal returns(uint256) { registered_th_addresses[_addr] = _teamName; return _amount + 1; } /** * Registers a new Team for TH prize * - caller of this function will provide list of tokens he/she owns to include his address * in this team and to create the team * - caller of this function is free of charge (only gas) * - Returns: number of shares in the team (max of TH_THIRD_PRIZE_MAX_WINNERS-1) */ function registerTHTeam(string memory _teamName, uint256[] memory _tokensTeam) external returns(uint256) { require(_tokensTeam.length < TH_THIRD_PRIZE_MAX_WINNERS); // dev: tokens list size exceed maximum to create list require(third_prize_players[_teamName].length == 0); // dev: team name already taken uint256 ret = 0; // Get addresses for tokens provided to create this team address [] memory _addrs = getAddressesFromTokens(_tokensTeam); // Caller must but owner of the tokens or exception // if some address already registered in another team, exception require(addressesNotRegisteredInTeamYet(_addrs)); // Flag address as registered under _teamName so it cannot be registered in another team for(uint256 i=0;i<_addrs.length;i++) { ret = addAddrToTeam(_addrs[i],_teamName,ret); } // Finally, we can register the team third_prize_players[_teamName] = _addrs; return ret; } /** * Caller calls this function if he/she wants to join a TH team */ function joinTHTeam(string memory _teamName, uint256[] memory _tokensTeam) external returns(uint256) { require(third_prize_players[_teamName].length != 0); // dev: team name does not exist require(third_prize_players[_teamName].length != TH_THIRD_PRIZE_MAX_WINNERS); // dev: team full uint256 ret = 0; // Get addresses for tokens provided to create this team // Caller must but owner of the tokens or exception address [] memory _addrs = getAddressesFromTokens(_tokensTeam); // if some address already registered in another team, exception require(addressesNotRegisteredInTeamYet(_addrs)); // dev: caller not in a team yet for(uint256 i=0;i<_addrs.length;i++) { // if there still some room left, add new joiner if(third_prize_players[_teamName].length < TH_THIRD_PRIZE_MAX_WINNERS) { // Finally, we can register the team third_prize_players[_teamName].push(_addrs[i]); ret = addAddrToTeam(_addrs[i],_teamName,ret); } } return ret; } /** * Function that registered users need to call to provide decrypted message _plaintext * If text matches the encrypted message, TH prize will be distributed to owners of scissors * registered in the team from the caller attending to their participation * */ function decryptForTHPrize(string memory _plaintext) external returns(bool) { require(th_secret_set); // dev: secret not set require(pctReached(100)); // dev: 100% not achieved yet require(!third_prize_released); // dev: 3rd prize already released require(accumulatedTHPrize == TH_POOL); // dev: not enough balance in contract require(address(this).balance >= TH_POOL); // dev: not enough balance in contract require(bytes(registered_th_addresses[msg.sender]).length != 0); // dev: caller not registered in any team if(keccak256(abi.encodePacked(_plaintext)) == th_secret) { // Secret message found, release prize to winners in team // Get the team name th_team_winner = registered_th_addresses[msg.sender]; // Access the addresses list address [] memory _winnersAddrs = third_prize_players[th_team_winner]; // Congrats winners _charge3rdGiveAway(th_team_winner,_winnersAddrs); return true; } else { revert("RPS - Wrong, keep trying."); } return false; } /** * Returns addresses of TH winners */ function getTHWinnerAddrs() external view returns(address[] memory) { require(third_prize_released); // dev: TH prize not relased yet return third_prize_players[th_team_winner]; } /** * Returns TH winner team name */ function getTHTeamName() external view returns(string memory) { require(third_prize_released); // dev: TH prize not relased yet return th_team_winner; } // The 50 ETH accumulated in the treasure account will be equally distributed among the winner group // and the corresponding will be made available to them through pullpayment. // Example if the group was formed by 10 people with 10 corresponding accounts, // 5 ETH will be made available to them through pull payment. function _charge3rdGiveAway(string memory _teamName, address[] memory _winners) internal { // We transfer amount in the contract and from the contract to payees // using pullpayment method for(uint256 i=0;i<_winners.length;i++) { _asyncTransfer(_winners[i],TH_PRIZE_PER_WALLET); // 5 ETH per wallet accumulatedTHPrize -= TH_PRIZE_PER_WALLET; } third_prize_released = true; emit ThirdGiveAwayCharged(_teamName,_winners); } /** * We will transfer any accumulated prize not provided to NGO account */ function sendRemainderToNGO() external onlyOwner { require(third_prize_released && accumulatedTHPrize > 0); // dev: prizes not released yet or no remaining // All prizes have been released, potential remainder to be sent to NGO uint256 amount = accumulatedTHPrize; payable(NGOAddress).transfer(amount); emit AmountWithdrawn(NGOAddress, amount); } }
dev: Maximum number of presales reached
require(_presalesCounter.current() < maxPresales);
586,397
[ 1, 5206, 30, 18848, 1300, 434, 4075, 5408, 8675, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2583, 24899, 12202, 5408, 4789, 18, 2972, 1435, 411, 943, 12236, 5408, 1769, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// Sources flattened with hardhat v2.3.0 https://hardhat.org // File @openzeppelin/contracts/utils/[email protected] // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File @openzeppelin/contracts/access/[email protected] /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File @openzeppelin/contracts/introspection/[email protected] /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File @openzeppelin/contracts/token/ERC721/[email protected] /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // File @openzeppelin/contracts/token/ERC721/[email protected] /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File @openzeppelin/contracts/token/ERC721/[email protected] /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File @openzeppelin/contracts/token/ERC721/[email protected] /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // File @openzeppelin/contracts/introspection/[email protected] /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // File @openzeppelin/contracts/math/[email protected] /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File @openzeppelin/contracts/utils/[email protected] /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @openzeppelin/contracts/utils/[email protected] /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File @openzeppelin/contracts/utils/[email protected] /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key) return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); } } // File @openzeppelin/contracts/utils/[email protected] /** * @dev String operations. */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } // File @openzeppelin/contracts/token/ERC721/[email protected] /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(base, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view virtual returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _tokenOwners.contains(tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); // internal owner _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } /** * @dev Approve `to` to operate on `tokenId` * * Emits an {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } // File hardhat/[email protected] 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)); } } // File contracts/Anon.sol contract Anon is Ownable, ERC721 { using SafeMath for uint256; /** Tile related configurations */ // Token IDs are from 0 to 10132 uint256 internal constant ALL_TOKEN_NUM = 10133; /** Draw related configurations */ // proof of state of all tiles string public constant SHA256 = "253762fe521a835df8726d8c614f0f7bbb86e67690b422e0c3556d7b4d5e146d"; // Have 3 different draws uint256 internal constant ALL_DRAW_NUM = 3; // can draw 1 token, 5 tokens or 10 tokens together enum DrawLevel {One, Five, Ten} struct Draw { DrawLevel level; // the total price uint256 price; // how many tokens to get uint256 number; } Draw[ALL_DRAW_NUM] internal allDraws; /** Draw & Mint related stats */ // how many tokens are sold uint256 internal soldNumber; // The user actions are enabled or not, default true bool internal enabled = true; // withdraw splits uint256 internal constant ALL_SLICE_NUM = 6; struct Slice { string name; address to; uint256 share; // percentage } Slice[ALL_SLICE_NUM] internal slices; // gift fund uint256 internal giftFund; // the remaining fund needs to send to giftFundAddress address internal giftFundAddress; /** Events */ // Emit the event when user play the game event PlayRequestReceived( address indexed toAddress, uint256 indexed gameId, uint256 indexed encrypted ); // Emit the event when user draw event TokenDrawn(string indexed uuid, uint256[] tokens); /** constructor */ constructor( string memory _name, string memory _symbol ) public ERC721(_name, _symbol) { // init draw conf allDraws[0] = Draw({level: DrawLevel.One, price: 0.1 ether, number: 1}); allDraws[1] = Draw({ level: DrawLevel.Five, price: 0.45 ether, number: 5 }); allDraws[2] = Draw({level: DrawLevel.Ten, price: 0.8 ether, number: 10}); // init withdraw splits slices[0] = Slice({name: "Anna", to: address(0x31ee1e6A5adf01d86CB5835c1FC08b8D3D547b4e), share: 27}); slices[1] = Slice({name: "Elsa", to: address(0x8ee2DAdEfd72f17e35FDC85136C244f7EE05Dfa5), share: 20}); slices[2] = Slice({name: "Mickey", to: address(0xa652b59F2b685564563556B54F8aD1F8Bec9Ea7b), share: 20}); slices[3] = Slice({name: "Belle", to: address(0x0Cc7eb98B12E8483C3a5d64995d1543B22a9a9dB), share: 20}); slices[4] = Slice({name: "Dumbo", to: address(0xb680073B79eFFcdf6F599B5614DCAC54568612fa), share: 12}); slices[5] = Slice({name: "Goofy", to: address(0xE10012bC19838f43ee54CfD6a44293A2667b7F44), share: 1}); // init gift funds giftFund = 60 ether; giftFundAddress = address(0x31C423e089EdF3748697408456EfA98836816AA7); } /** user facing functions */ modifier onlyWhenEnabled() { require(enabled, "Contract is disabled, please come back later"); _; } // user call this function to draw function draw(string memory uuid) public onlyWhenEnabled payable { uint256 number; for (uint256 i = 0; i < ALL_DRAW_NUM; i++) { if (allDraws[i].price == msg.value) { number = allDraws[i].number; break; } } require( number > 0, "Invalid price, please pay either 0.1 ETH for 1 draw or 0.45 ETH for 5 draws or 0.8 ETH for 10 draws" ); uint256 newSoldNumber = soldNumber + number; require(newSoldNumber <= ALL_TOKEN_NUM, "Not enough supply"); uint256[] memory tokens = new uint256[](number); for (uint256 i = 0; i < number; i++) { // tokenId is taken sequential uint256 tokenId = soldNumber + i; // mint the token immediately _mint(msg.sender, tokenId); tokens[i] = tokenId; } // update the sold number soldNumber = newSoldNumber; // Emit token drawn event emit TokenDrawn(uuid, tokens); } // user call this function to play function play(uint256 gameId, uint256 encrypted) public onlyWhenEnabled { emit PlayRequestReceived(msg.sender, gameId, encrypted); } /** OpenSea facing functions */ function contractURI() public view returns (string memory) { string memory base = baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return ""; } return string(abi.encodePacked(base, "opensea-metadata")); } /** admin facing functions */ function setEnabled(bool _enabled) public onlyOwner { enabled = _enabled; } function _payout(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(""); require(success, "Payout failed"); } function withdraw() public onlyOwner { uint256 amount = address(this).balance; // always payout to gift fund first if (giftFund > 0) { uint256 value; if (amount > giftFund) { value = giftFund; giftFund = 0; } else { value = amount; giftFund -= amount; } _payout(giftFundAddress, value); return; } // payout to slices if gift fund has already paid out uint256 paid = 0; // loop except the last one for (uint256 i = 0; i < ALL_SLICE_NUM - 1; i++) { uint256 value = amount * slices[i].share / 100; _payout(slices[i].to, value); paid += value; } // payout the remaining to the last slice // - sum of percentages is 100, paying the remaining fund is the same // - paying the remaining to avoid potential rounding bug _payout(slices[ALL_SLICE_NUM - 1].to, amount - paid); } function setBaseURI(string memory baseURI_) public onlyOwner { _setBaseURI(baseURI_); } } // File @openzeppelin/contracts/token/ERC20/[email protected] /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File @openzeppelin/contracts/token/ERC20/[email protected] /** * @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 { } } // File contracts/DummyERC20.sol contract DummyERC20 is ERC20 { constructor () public ERC20("Dummy ERC20", "DUMMY") { _mint(msg.sender, 10 * 10**6 * 10**18); } } // File contracts/DummyLINK.sol contract DummyLINK is ERC20 { constructor () public ERC20("Dummy LINK", "DUMMYLINK") { _mint(msg.sender, 10 * 10**6 * 10**18); } function decreaseApproval(address spender, uint256 subtractedValue) external returns (bool success) { return decreaseAllowance(spender, subtractedValue); } function increaseApproval(address spender, uint256 addedValue) external { increaseAllowance(spender, addedValue); } function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool success) { transfer(to, value); return true; } } // File @chainlink/contracts/src/v0.6/interfaces/[email protected] 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); } // File @chainlink/contracts/src/v0.6/vendor/[email protected] /** * @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 SafeMathChainlink { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } // File @chainlink/contracts/src/v0.6/[email protected] 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)); } } // File @chainlink/contracts/src/v0.6/[email protected] /** **************************************************************************** * @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 { using SafeMathChainlink for uint256; /** * @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; /** * @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 * @param _seed seed mixed into the input of the VRF. * * @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, uint256 _seed) internal returns (bytes32 requestId) { LINK.transferAndCall(vrfCoordinator, _fee, abi.encode(_keyHash, _seed)); // 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, _seed, 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].add(1); return makeRequestId(_keyHash, vRFSeed); } LinkTokenInterface immutable internal LINK; address immutable private vrfCoordinator; // Nonces for each VRF key from which randomness has been requested. // // Must stay in sync with VRFCoordinator[_keyHash][this] mapping(bytes32 /* keyHash */ => uint256 /* 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) public { 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); } } // File contracts/DummyVRF.sol contract DummyVRF { LinkTokenInterface public LINK; event RandomnessRequest(address indexed sender, bytes32 indexed keyHash, uint256 indexed seed); constructor(address linkAddress) public { LINK = LinkTokenInterface(linkAddress); } function onTokenTransfer(address sender, uint256 fee, bytes memory _data) public { (bytes32 keyHash, uint256 seed) = abi.decode(_data, (bytes32, uint256)); emit RandomnessRequest(sender, keyHash, seed); } function callBackWithRandomness( bytes32 requestId, uint256 randomness, address consumerContract ) public { VRFConsumerBase v; bytes memory resp = abi.encodeWithSelector(v.rawFulfillRandomness.selector, requestId, randomness); uint256 b = 206000; require(gasleft() >= b, "not enough gas for consumer"); (bool success,) = consumerContract.call(resp); } } // File contracts/OpenSeaMatic.sol /** * https://github.com/maticnetwork/pos-portal/blob/master/contracts/common/ContextMixin.sol */ abstract contract ContextMixin { function msgSender() internal view returns (address payable sender) { if (msg.sender == address(this)) { bytes memory array = msg.data; uint256 index = msg.data.length; assembly { // Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those. sender := and( mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff ) } } else { sender = msg.sender; } return sender; } } /** * https://github.com/maticnetwork/pos-portal/blob/master/contracts/common/Initializable.sol */ contract Initializable { bool inited = false; modifier initializer() { require(!inited, "already inited"); _; inited = true; } } /** * https://github.com/maticnetwork/pos-portal/blob/master/contracts/common/EIP712Base.sol */ contract EIP712Base is Initializable { struct EIP712Domain { string name; string version; address verifyingContract; bytes32 salt; } string constant public ERC712_VERSION = "1"; bytes32 internal constant EIP712_DOMAIN_TYPEHASH = keccak256( bytes( "EIP712Domain(string name,string version,address verifyingContract,bytes32 salt)" ) ); bytes32 internal domainSeperator; // supposed to be called once while initializing. // one of the contractsa that inherits this contract follows proxy pattern // so it is not possible to do this in a constructor function _initializeEIP712( string memory name ) internal initializer { _setDomainSeperator(name); } function _setDomainSeperator(string memory name) internal { domainSeperator = keccak256( abi.encode( EIP712_DOMAIN_TYPEHASH, keccak256(bytes(name)), keccak256(bytes(ERC712_VERSION)), address(this), bytes32(getChainId()) ) ); } function getDomainSeperator() public view returns (bytes32) { return domainSeperator; } function getChainId() public pure returns (uint256) { uint256 id; assembly { id := chainid() } return id; } /** * Accept message hash and returns hash message in EIP712 compatible form * So that it can be used to recover signer from signature signed using EIP712 formatted data * https://eips.ethereum.org/EIPS/eip-712 * "\\x19" makes the encoding deterministic * "\\x01" is the version byte to make it compatible to EIP-191 */ function toTypedMessageHash(bytes32 messageHash) internal view returns (bytes32) { return keccak256( abi.encodePacked("\x19\x01", getDomainSeperator(), messageHash) ); } } /** * https://github.com/maticnetwork/pos-portal/blob/master/contracts/common/NativeMetaTransaction.sol */ contract NativeMetaTransaction is EIP712Base { using SafeMath for uint256; bytes32 private constant META_TRANSACTION_TYPEHASH = keccak256( bytes( "MetaTransaction(uint256 nonce,address from,bytes functionSignature)" ) ); event MetaTransactionExecuted( address userAddress, address payable relayerAddress, bytes functionSignature ); mapping(address => uint256) nonces; /* * Meta transaction structure. * No point of including value field here as if user is doing value transfer then he has the funds to pay for gas * He should call the desired function directly in that case. */ struct MetaTransaction { uint256 nonce; address from; bytes functionSignature; } function executeMetaTransaction( address userAddress, bytes memory functionSignature, bytes32 sigR, bytes32 sigS, uint8 sigV ) public payable returns (bytes memory) { MetaTransaction memory metaTx = MetaTransaction({ nonce: nonces[userAddress], from: userAddress, functionSignature: functionSignature }); require( verify(userAddress, metaTx, sigR, sigS, sigV), "Signer and signature do not match" ); // increase nonce for user (to avoid re-use) nonces[userAddress] = nonces[userAddress].add(1); emit MetaTransactionExecuted( userAddress, msg.sender, functionSignature ); // Append userAddress and relayer address at the end to extract it from calling context (bool success, bytes memory returnData) = address(this).call( abi.encodePacked(functionSignature, userAddress) ); require(success, "Function call not successful"); return returnData; } function hashMetaTransaction(MetaTransaction memory metaTx) internal pure returns (bytes32) { return keccak256( abi.encode( META_TRANSACTION_TYPEHASH, metaTx.nonce, metaTx.from, keccak256(metaTx.functionSignature) ) ); } function getNonce(address user) public view returns (uint256 nonce) { nonce = nonces[user]; } function verify( address signer, MetaTransaction memory metaTx, bytes32 sigR, bytes32 sigS, uint8 sigV ) internal view returns (bool) { require(signer != address(0), "NativeMetaTransaction: INVALID_SIGNER"); return signer == ecrecover( toTypedMessageHash(hashMetaTransaction(metaTx)), sigV, sigR, sigS ); } }
user call this function to draw tokenId is taken sequential mint the token immediately
function draw(string memory uuid) public onlyWhenEnabled payable { uint256 number; for (uint256 i = 0; i < ALL_DRAW_NUM; i++) { if (allDraws[i].price == msg.value) { number = allDraws[i].number; break; } } require( number > 0, "Invalid price, please pay either 0.1 ETH for 1 draw or 0.45 ETH for 5 draws or 0.8 ETH for 10 draws" ); uint256 newSoldNumber = soldNumber + number; require(newSoldNumber <= ALL_TOKEN_NUM, "Not enough supply"); uint256[] memory tokens = new uint256[](number); for (uint256 i = 0; i < number; i++) { uint256 tokenId = soldNumber + i; _mint(msg.sender, tokenId); tokens[i] = tokenId; } }
7,288,337
[ 1, 1355, 745, 333, 445, 358, 3724, 1147, 548, 353, 9830, 21210, 312, 474, 326, 1147, 7636, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 3724, 12, 1080, 3778, 3822, 13, 1071, 1338, 9434, 1526, 8843, 429, 288, 203, 3639, 2254, 5034, 1300, 31, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 8061, 67, 40, 10821, 67, 6069, 31, 277, 27245, 288, 203, 5411, 309, 261, 454, 25113, 63, 77, 8009, 8694, 422, 1234, 18, 1132, 13, 288, 203, 7734, 1300, 273, 777, 25113, 63, 77, 8009, 2696, 31, 203, 7734, 898, 31, 203, 5411, 289, 203, 3639, 289, 203, 203, 3639, 2583, 12, 203, 5411, 1300, 405, 374, 16, 203, 5411, 315, 1941, 6205, 16, 9582, 8843, 3344, 374, 18, 21, 512, 2455, 364, 404, 3724, 578, 374, 18, 7950, 512, 2455, 364, 1381, 30013, 578, 374, 18, 28, 512, 2455, 364, 1728, 30013, 6, 203, 3639, 11272, 203, 203, 3639, 2254, 5034, 30826, 1673, 1854, 273, 272, 1673, 1854, 397, 1300, 31, 203, 203, 3639, 2583, 12, 2704, 55, 1673, 1854, 1648, 8061, 67, 8412, 67, 6069, 16, 315, 1248, 7304, 14467, 8863, 203, 203, 3639, 2254, 5034, 8526, 3778, 2430, 273, 394, 2254, 5034, 8526, 12, 2696, 1769, 203, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 1300, 31, 277, 27245, 288, 203, 5411, 2254, 5034, 1147, 548, 273, 272, 1673, 1854, 397, 277, 31, 203, 5411, 389, 81, 474, 12, 3576, 18, 15330, 16, 1147, 548, 1769, 203, 203, 5411, 2430, 63, 77, 65, 273, 1147, 548, 31, 203, 3639, 289, 203, 203, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0x1eC582Dd21c4cCaA7B9719D5dbFbD0f9d49ddcAe/sources/contracts/MintPass.sol
verify contract is not pausedvalidate all tokens being claimed and aggregate a total cost due
) external payable { require(!paused(), "Claim: claiming is paused"); function claimMultiple( uint256[] calldata numPasses, uint256[] calldata amounts, uint256[] calldata mpIndexs, bytes32[][] calldata merkleProofs for (uint i=0; i< mpIndexs.length; i++) { require(isValidClaim(numPasses[i],amounts[i],mpIndexs[i],merkleProofs[i]), "One or more claims are invalid"); } for (uint i=0; i< mpIndexs.length; i++) { mintPasses[mpIndexs[i]].claimedMPs[msg.sender] = mintPasses[mpIndexs[i]].claimedMPs[msg.sender].add(numPasses[i]); } _mintBatch(msg.sender, mpIndexs, numPasses, ""); emit ClaimedMultiple(mpIndexs, msg.sender, numPasses); }
12,280,876
[ 1, 8705, 6835, 353, 486, 17781, 5662, 777, 2430, 3832, 7516, 329, 471, 7047, 279, 2078, 6991, 6541, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 262, 3903, 8843, 429, 288, 203, 203, 3639, 2583, 12, 5, 8774, 3668, 9334, 315, 9762, 30, 7516, 310, 353, 17781, 8863, 203, 203, 3639, 203, 565, 445, 7516, 8438, 12, 203, 3639, 2254, 5034, 8526, 745, 892, 818, 6433, 281, 16, 203, 3639, 2254, 5034, 8526, 745, 892, 30980, 16, 203, 3639, 2254, 5034, 8526, 745, 892, 6749, 1016, 87, 16, 203, 3639, 1731, 1578, 63, 6362, 65, 745, 892, 30235, 20439, 87, 203, 3639, 364, 261, 11890, 277, 33, 20, 31, 277, 32, 6749, 1016, 87, 18, 2469, 31, 277, 27245, 288, 203, 6647, 2583, 12, 26810, 9762, 12, 2107, 6433, 281, 63, 77, 6487, 8949, 87, 63, 77, 6487, 1291, 1016, 87, 63, 77, 6487, 6592, 15609, 20439, 87, 63, 77, 65, 3631, 315, 3335, 578, 1898, 11955, 854, 2057, 8863, 203, 3639, 289, 203, 203, 3639, 364, 261, 11890, 277, 33, 20, 31, 277, 32, 6749, 1016, 87, 18, 2469, 31, 277, 27245, 288, 203, 5411, 312, 474, 6433, 281, 63, 1291, 1016, 87, 63, 77, 65, 8009, 14784, 329, 4566, 87, 63, 3576, 18, 15330, 65, 273, 312, 474, 6433, 281, 63, 1291, 1016, 87, 63, 77, 65, 8009, 14784, 329, 4566, 87, 63, 3576, 18, 15330, 8009, 1289, 12, 2107, 6433, 281, 63, 77, 19226, 203, 3639, 289, 203, 203, 3639, 389, 81, 474, 4497, 12, 3576, 18, 15330, 16, 6749, 1016, 87, 16, 818, 6433, 281, 16, 1408, 1769, 203, 203, 3639, 3626, 18381, 329, 8438, 12, 1291, 1016, 87, 16, 1234, 18, 15330, 16, 818, 2 ]
// SPDX-License-Identifier: Apache-2.0 // Copyright 2017 Loopring Technology Limited. pragma solidity ^0.7.0; /// @title Wallet /// @dev Base contract for smart wallets. /// Sub-contracts must NOT use non-default constructor to initialize /// wallet states, instead, `init` shall be used. This is to enable /// proxies to be deployed in front of the real wallet contract for /// saving gas. /// /// @author Daniel Wang - <[email protected]> /// /// The design of this contract is inspired by Argent's contract codebase: /// https://github.com/argentlabs/argent-contracts interface Wallet { function version() external pure returns (string memory); function owner() external view returns (address); /// @dev Set a new owner. function setOwner(address newOwner) external; /// @dev Adds a new module. The `init` method of the module /// will be called with `address(this)` as the parameter. /// This method must throw if the module has already been added. /// @param _module The module's address. function addModule(address _module) external; /// @dev Removes an existing module. This method must throw if the module /// has NOT been added or the module is the wallet's only module. /// @param _module The module's address. function removeModule(address _module) external; /// @dev Checks if a module has been added to this wallet. /// @param _module The module to check. /// @return True if the module exists; False otherwise. function hasModule(address _module) external view returns (bool); /// @dev Binds a method from the given module to this /// wallet so the method can be invoked using this wallet's default /// function. /// Note that this method must throw when the given module has /// not been added to this wallet. /// @param _method The method's 4-byte selector. /// @param _module The module's address. Use address(0) to unbind the method. function bindMethod(bytes4 _method, address _module) external; /// @dev Returns the module the given method has been bound to. /// @param _method The method's 4-byte selector. /// @return _module The address of the bound module. If no binding exists, /// returns address(0) instead. function boundMethodModule(bytes4 _method) external view returns (address _module); /// @dev Performs generic transactions. Any module that has been added to this /// wallet can use this method to transact on any third-party contract with /// msg.sender as this wallet itself. /// /// This method will emit `Transacted` event if it doesn't throw. /// /// Note: this method must ONLY allow invocations from a module that has /// been added to this wallet. The wallet owner shall NOT be permitted /// to call this method directly. /// /// @param mode The transaction mode, 1 for CALL, 2 for DELEGATECALL. /// @param to The desitination address. /// @param value The amount of Ether to transfer. /// @param data The data to send over using `to.call{value: value}(data)` /// @return returnData The transaction's return value. function transact( uint8 mode, address to, uint value, bytes calldata data ) external returns (bytes memory returnData); } // Copyright 2017 Loopring Technology Limited. /// @title Ownable /// @author Brecht Devos - <[email protected]> /// @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. constructor() { owner = msg.sender; } /// @dev Throws if called by any account other than the owner. modifier onlyOwner() { require(msg.sender == owner, "UNAUTHORIZED"); _; } /// @dev Allows the current owner to transfer control of the contract to a /// new owner. /// @param newOwner The address to transfer ownership to. function transferOwnership( address newOwner ) public virtual onlyOwner { require(newOwner != address(0), "ZERO_ADDRESS"); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } function renounceOwnership() public onlyOwner { emit OwnershipTransferred(owner, address(0)); owner = address(0); } } /* * @title String & slice utility library for Solidity contracts. * @author Nick Johnson <[email protected]> * * @dev Functionality in this library is largely implemented using an * abstraction called a 'slice'. A slice represents a part of a string - * anything from the entire string to a single character, or even no * characters at all (a 0-length slice). Since a slice only has to specify * an offset and a length, copying and manipulating slices is a lot less * expensive than copying and manipulating the strings they reference. * * To further reduce gas costs, most functions on slice that need to return * a slice modify the original one instead of allocating a new one; for * instance, `s.split(".")` will return the text up to the first '.', * modifying s to only contain the remainder of the string after the '.'. * In situations where you do not want to modify the original slice, you * can make a copy first with `.copy()`, for example: * `s.copy().split(".")`. Try and avoid using this idiom in loops; since * Solidity has no memory management, it will result in allocating many * short-lived slices that are later discarded. * * Functions that return two slices come in two versions: a non-allocating * version that takes the second slice as an argument, modifying it in * place, and an allocating version that allocates and returns the second * slice; see `nextRune` for example. * * Functions that have to copy string data will return strings rather than * slices; these can be cast back to slices for further processing if * required. * * For convenience, some functions are provided with non-modifying * variants that create a new slice and return both; for instance, * `s.splitNew('.')` leaves s unmodified, and returns two values * corresponding to the left and right parts of the string. */ /* solium-disable */ library strings { struct slice { uint _len; uint _ptr; } 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 uint 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 Returns a slice containing the entire string. * @param self The string to make a slice from. * @return A newly allocated slice containing the entire string. */ function toSlice(string memory self) internal pure returns (slice memory) { uint ptr; assembly { ptr := add(self, 0x20) } return slice(bytes(self).length, ptr); } /* * @dev Returns the length of a null-terminated bytes32 string. * @param self The value to find the length of. * @return The length of the string, from 0 to 32. */ function len(bytes32 self) internal pure returns (uint) { uint ret; if (self == 0) return 0; if (uint256(self) & 0xffffffffffffffffffffffffffffffff == 0) { ret += 16; self = bytes32(uint(self) / 0x100000000000000000000000000000000); } if (uint256(self) & 0xffffffffffffffff == 0) { ret += 8; self = bytes32(uint(self) / 0x10000000000000000); } if (uint256(self) & 0xffffffff == 0) { ret += 4; self = bytes32(uint(self) / 0x100000000); } if (uint256(self) & 0xffff == 0) { ret += 2; self = bytes32(uint(self) / 0x10000); } if (uint256(self) & 0xff == 0) { ret += 1; } return 32 - ret; } /* * @dev Returns a slice containing the entire bytes32, interpreted as a * null-terminated utf-8 string. * @param self The bytes32 value to convert to a slice. * @return A new slice containing the value of the input argument up to the * first null. */ function toSliceB32(bytes32 self) internal pure returns (slice memory ret) { // Allocate space for `self` in memory, copy it there, and point ret at it assembly { let ptr := mload(0x40) mstore(0x40, add(ptr, 0x20)) mstore(ptr, self) mstore(add(ret, 0x20), ptr) } ret._len = len(self); } /* * @dev Returns a new slice containing the same data as the current slice. * @param self The slice to copy. * @return A new slice containing the same data as `self`. */ function copy(slice memory self) internal pure returns (slice memory) { return slice(self._len, self._ptr); } /* * @dev Copies a slice to a new string. * @param self The slice to copy. * @return A newly allocated string containing the slice's text. */ function toString(slice memory self) internal pure returns (string memory) { string memory ret = new string(self._len); uint retptr; assembly { retptr := add(ret, 32) } memcpy(retptr, self._ptr, self._len); return ret; } /* * @dev Returns the length in runes of the slice. Note that this operation * takes time proportional to the length of the slice; avoid using it * in loops, and call `slice.empty()` if you only need to kblock.timestamp whether * the slice is empty or not. * @param self The slice to operate on. * @return The length of the slice in runes. */ function len(slice memory self) internal pure returns (uint l) { // Starting at ptr-31 means the LSB will be the byte we care about uint ptr = self._ptr - 31; uint end = ptr + self._len; for (l = 0; ptr < end; l++) { uint8 b; assembly { b := and(mload(ptr), 0xFF) } if (b < 0x80) { ptr += 1; } else if(b < 0xE0) { ptr += 2; } else if(b < 0xF0) { ptr += 3; } else if(b < 0xF8) { ptr += 4; } else if(b < 0xFC) { ptr += 5; } else { ptr += 6; } } } /* * @dev Returns true if the slice is empty (has a length of 0). * @param self The slice to operate on. * @return True if the slice is empty, False otherwise. */ function empty(slice memory self) internal pure returns (bool) { return self._len == 0; } /* * @dev Returns a positive number if `other` comes lexicographically after * `self`, a negative number if it comes before, or zero if the * contents of the two slices are equal. Comparison is done per-rune, * on unicode codepoints. * @param self The first slice to compare. * @param other The second slice to compare. * @return The result of the comparison. */ function compare(slice memory self, slice memory other) internal pure returns (int) { uint shortest = self._len; if (other._len < self._len) shortest = other._len; uint selfptr = self._ptr; uint otherptr = other._ptr; for (uint idx = 0; idx < shortest; idx += 32) { uint a; uint b; assembly { a := mload(selfptr) b := mload(otherptr) } if (a != b) { // Mask out irrelevant bytes and check again uint256 mask = uint256(-1); // 0xffff... if(shortest < 32) { mask = ~(2 ** (8 * (32 - shortest + idx)) - 1); } uint256 diff = (a & mask) - (b & mask); if (diff != 0) return int(diff); } selfptr += 32; otherptr += 32; } return int(self._len) - int(other._len); } /* * @dev Returns true if the two slices contain the same text. * @param self The first slice to compare. * @param self The second slice to compare. * @return True if the slices are equal, false otherwise. */ function equals(slice memory self, slice memory other) internal pure returns (bool) { return compare(self, other) == 0; } /* * @dev Extracts the first rune in the slice into `rune`, advancing the * slice to point to the next rune and returning `self`. * @param self The slice to operate on. * @param rune The slice that will contain the first rune. * @return `rune`. */ function nextRune(slice memory self, slice memory rune) internal pure returns (slice memory) { rune._ptr = self._ptr; if (self._len == 0) { rune._len = 0; return rune; } uint l; uint b; // Load the first byte of the rune into the LSBs of b assembly { b := and(mload(sub(mload(add(self, 32)), 31)), 0xFF) } if (b < 0x80) { l = 1; } else if(b < 0xE0) { l = 2; } else if(b < 0xF0) { l = 3; } else { l = 4; } // Check for truncated codepoints if (l > self._len) { rune._len = self._len; self._ptr += self._len; self._len = 0; return rune; } self._ptr += l; self._len -= l; rune._len = l; return rune; } /* * @dev Returns the first rune in the slice, advancing the slice to point * to the next rune. * @param self The slice to operate on. * @return A slice containing only the first rune from `self`. */ function nextRune(slice memory self) internal pure returns (slice memory ret) { nextRune(self, ret); } /* * @dev Returns the number of the first codepoint in the slice. * @param self The slice to operate on. * @return The number of the first codepoint in the slice. */ function ord(slice memory self) internal pure returns (uint ret) { if (self._len == 0) { return 0; } uint word; uint length; uint divisor = 2 ** 248; // Load the rune into the MSBs of b assembly { word:= mload(mload(add(self, 32))) } uint b = word / divisor; if (b < 0x80) { ret = b; length = 1; } else if(b < 0xE0) { ret = b & 0x1F; length = 2; } else if(b < 0xF0) { ret = b & 0x0F; length = 3; } else { ret = b & 0x07; length = 4; } // Check for truncated codepoints if (length > self._len) { return 0; } for (uint i = 1; i < length; i++) { divisor = divisor / 256; b = (word / divisor) & 0xFF; if (b & 0xC0 != 0x80) { // Invalid UTF-8 sequence return 0; } ret = (ret * 64) | (b & 0x3F); } return ret; } /* * @dev Returns the keccak-256 hash of the slice. * @param self The slice to hash. * @return The hash of the slice. */ function keccak(slice memory self) internal pure returns (bytes32 ret) { assembly { ret := keccak256(mload(add(self, 32)), mload(self)) } } /* * @dev Returns true if `self` starts with `needle`. * @param self The slice to operate on. * @param needle The slice to search for. * @return True if the slice starts with the provided text, false otherwise. */ function startsWith(slice memory self, slice memory needle) internal pure returns (bool) { if (self._len < needle._len) { return false; } if (self._ptr == needle._ptr) { return true; } bool equal; assembly { let length := mload(needle) let selfptr := mload(add(self, 0x20)) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } return equal; } /* * @dev If `self` starts with `needle`, `needle` is removed from the * beginning of `self`. Otherwise, `self` is unmodified. * @param self The slice to operate on. * @param needle The slice to search for. * @return `self` */ function beyond(slice memory self, slice memory needle) internal pure returns (slice memory) { if (self._len < needle._len) { return self; } bool equal = true; if (self._ptr != needle._ptr) { assembly { let length := mload(needle) let selfptr := mload(add(self, 0x20)) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } } if (equal) { self._len -= needle._len; self._ptr += needle._len; } return self; } /* * @dev Returns true if the slice ends with `needle`. * @param self The slice to operate on. * @param needle The slice to search for. * @return True if the slice starts with the provided text, false otherwise. */ function endsWith(slice memory self, slice memory needle) internal pure returns (bool) { if (self._len < needle._len) { return false; } uint selfptr = self._ptr + self._len - needle._len; if (selfptr == needle._ptr) { return true; } bool equal; assembly { let length := mload(needle) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } return equal; } /* * @dev If `self` ends with `needle`, `needle` is removed from the * end of `self`. Otherwise, `self` is unmodified. * @param self The slice to operate on. * @param needle The slice to search for. * @return `self` */ function until(slice memory self, slice memory needle) internal pure returns (slice memory) { if (self._len < needle._len) { return self; } uint selfptr = self._ptr + self._len - needle._len; bool equal = true; if (selfptr != needle._ptr) { assembly { let length := mload(needle) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } } if (equal) { self._len -= needle._len; } return self; } // Returns the memory address of the first byte of the first occurrence of // `needle` in `self`, or the first byte after `self` if not found. function findPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) { uint ptr = selfptr; uint idx; if (needlelen <= selflen) { if (needlelen <= 32) { bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1)); bytes32 needledata; assembly { needledata := and(mload(needleptr), mask) } uint end = selfptr + selflen - needlelen; bytes32 ptrdata; assembly { ptrdata := and(mload(ptr), mask) } while (ptrdata != needledata) { if (ptr >= end) return selfptr + selflen; ptr++; assembly { ptrdata := and(mload(ptr), mask) } } return ptr; } else { // For long needles, use hashing bytes32 hash; assembly { hash := keccak256(needleptr, needlelen) } for (idx = 0; idx <= selflen - needlelen; idx++) { bytes32 testHash; assembly { testHash := keccak256(ptr, needlelen) } if (hash == testHash) return ptr; ptr += 1; } } } return selfptr + selflen; } // Returns the memory address of the first byte after the last occurrence of // `needle` in `self`, or the address of `self` if not found. function rfindPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) { uint ptr; if (needlelen <= selflen) { if (needlelen <= 32) { bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1)); bytes32 needledata; assembly { needledata := and(mload(needleptr), mask) } ptr = selfptr + selflen - needlelen; bytes32 ptrdata; assembly { ptrdata := and(mload(ptr), mask) } while (ptrdata != needledata) { if (ptr <= selfptr) return selfptr; ptr--; assembly { ptrdata := and(mload(ptr), mask) } } return ptr + needlelen; } else { // For long needles, use hashing bytes32 hash; assembly { hash := keccak256(needleptr, needlelen) } ptr = selfptr + (selflen - needlelen); while (ptr >= selfptr) { bytes32 testHash; assembly { testHash := keccak256(ptr, needlelen) } if (hash == testHash) return ptr + needlelen; ptr -= 1; } } } return selfptr; } /* * @dev Modifies `self` to contain everything from the first occurrence of * `needle` to the end of the slice. `self` is set to the empty slice * if `needle` is not found. * @param self The slice to search and modify. * @param needle The text to search for. * @return `self`. */ function find(slice memory self, slice memory needle) internal pure returns (slice memory) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr); self._len -= ptr - self._ptr; self._ptr = ptr; return self; } /* * @dev Modifies `self` to contain the part of the string from the start of * `self` to the end of the first occurrence of `needle`. If `needle` * is not found, `self` is set to the empty slice. * @param self The slice to search and modify. * @param needle The text to search for. * @return `self`. */ function rfind(slice memory self, slice memory needle) internal pure returns (slice memory) { uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr); self._len = ptr - self._ptr; return self; } /* * @dev Splits the slice, setting `self` to everything after the first * occurrence of `needle`, and `token` to everything before it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and `token` is set to the entirety of `self`. * @param self The slice to split. * @param needle The text to search for in `self`. * @param token An output parameter to which the first token is written. * @return `token`. */ function split(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr); token._ptr = self._ptr; token._len = ptr - self._ptr; if (ptr == self._ptr + self._len) { // Not found self._len = 0; } else { self._len -= token._len + needle._len; self._ptr = ptr + needle._len; } return token; } /* * @dev Splits the slice, setting `self` to everything after the first * occurrence of `needle`, and returning everything before it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and the entirety of `self` is returned. * @param self The slice to split. * @param needle The text to search for in `self`. * @return The part of `self` up to the first occurrence of `delim`. */ function split(slice memory self, slice memory needle) internal pure returns (slice memory token) { split(self, needle, token); } /* * @dev Splits the slice, setting `self` to everything before the last * occurrence of `needle`, and `token` to everything after it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and `token` is set to the entirety of `self`. * @param self The slice to split. * @param needle The text to search for in `self`. * @param token An output parameter to which the first token is written. * @return `token`. */ function rsplit(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) { uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr); token._ptr = ptr; token._len = self._len - (ptr - self._ptr); if (ptr == self._ptr) { // Not found self._len = 0; } else { self._len -= token._len + needle._len; } return token; } /* * @dev Splits the slice, setting `self` to everything before the last * occurrence of `needle`, and returning everything after it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and the entirety of `self` is returned. * @param self The slice to split. * @param needle The text to search for in `self`. * @return The part of `self` after the last occurrence of `delim`. */ function rsplit(slice memory self, slice memory needle) internal pure returns (slice memory token) { rsplit(self, needle, token); } /* * @dev Counts the number of nonoverlapping occurrences of `needle` in `self`. * @param self The slice to search. * @param needle The text to search for in `self`. * @return The number of occurrences of `needle` found in `self`. */ function count(slice memory self, slice memory needle) internal pure returns (uint cnt) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr) + needle._len; while (ptr <= self._ptr + self._len) { cnt++; ptr = findPtr(self._len - (ptr - self._ptr), ptr, needle._len, needle._ptr) + needle._len; } } /* * @dev Returns True if `self` contains `needle`. * @param self The slice to search. * @param needle The text to search for in `self`. * @return True if `needle` is found in `self`, false otherwise. */ function contains(slice memory self, slice memory needle) internal pure returns (bool) { return rfindPtr(self._len, self._ptr, needle._len, needle._ptr) != self._ptr; } /* * @dev Returns a newly allocated string containing the concatenation of * `self` and `other`. * @param self The first slice to concatenate. * @param other The second slice to concatenate. * @return The concatenation of the two strings. */ function concat(slice memory self, slice memory other) internal pure returns (string memory) { string memory ret = new string(self._len + other._len); uint retptr; assembly { retptr := add(ret, 32) } memcpy(retptr, self._ptr, self._len); memcpy(retptr + self._len, other._ptr, other._len); return ret; } /* * @dev Joins an array of slices, using `self` as a delimiter, returning a * newly allocated string. * @param self The delimiter to use. * @param parts A list of slices to join. * @return A newly allocated string containing all the slices in `parts`, * joined with `self`. */ function join(slice memory self, slice[] memory parts) internal pure returns (string memory) { if (parts.length == 0) return ""; uint length = self._len * (parts.length - 1); for(uint i = 0; i < parts.length; i++) length += parts[i]._len; string memory ret = new string(length); uint retptr; assembly { retptr := add(ret, 32) } for(uint i = 0; i < parts.length; i++) { memcpy(retptr, parts[i]._ptr, parts[i]._len); retptr += parts[i]._len; if (i < parts.length - 1) { memcpy(retptr, self._ptr, self._len); retptr += self._len; } } return ret; } } // Taken from Argent's code base - https://github.com/argentlabs/argent-contracts/blob/develop/contracts/ens/ENS.sol // with few modifications. /** * ENS Registry interface. */ interface ENSRegistry { // Logged when the owner of a node assigns a new owner to a subnode. event NewOwner(bytes32 indexed node, bytes32 indexed label, address owner); // Logged when the owner of a node transfers ownership to a new account. event Transfer(bytes32 indexed node, address owner); // Logged when the resolver for a node changes. event NewResolver(bytes32 indexed node, address resolver); // Logged when the TTL of a node changes event NewTTL(bytes32 indexed node, uint64 ttl); function setSubnodeOwner(bytes32 node, bytes32 label, address owner) external; function setResolver(bytes32 node, address resolver) external; function setOwner(bytes32 node, address owner) external; function setTTL(bytes32 node, uint64 ttl) external; function owner(bytes32 node) external view returns (address); function resolver(bytes32 node) external view returns (address); function ttl(bytes32 node) external view returns (uint64); } /** * ENS Resolver interface. */ abstract contract ENSResolver { function addr(bytes32 _node) public view virtual returns (address); function setAddr(bytes32 _node, address _addr) public virtual; function name(bytes32 _node) public view virtual returns (string memory); function setName(bytes32 _node, string memory _name) public virtual; } /** * ENS Reverse Registrar interface. */ abstract contract ENSReverseRegistrar { function claim(address _owner) public virtual returns (bytes32 _node); function claimWithResolver(address _owner, address _resolver) public virtual returns (bytes32); function setName(string memory _name) public virtual returns (bytes32); function node(address _addr) public view virtual returns (bytes32); } // Taken from Argent's code base - https://github.com/argentlabs/argent-contracts/blob/develop/contracts/ens/ENSConsumer.sol // with few modifications. /** * @title ENSConsumer * @dev Helper contract to resolve ENS names. * @author Julien Niset - <[email protected]> */ contract ENSConsumer { using strings for *; // namehash('addr.reverse') bytes32 constant public ADDR_REVERSE_NODE = 0x91d1777781884d03a6757a803996e38de2a42967fb37eeaca72729271025a9e2; // the address of the ENS registry address ensRegistry; /** * @dev No address should be provided when deploying on Mainnet to avoid storage cost. The * contract will use the hardcoded value. */ constructor(address _ensRegistry) { ensRegistry = _ensRegistry; } /** * @dev Resolves an ENS name to an address. * @param _node The namehash of the ENS name. */ function resolveEns(bytes32 _node) public view returns (address) { address resolver = getENSRegistry().resolver(_node); return ENSResolver(resolver).addr(_node); } /** * @dev Gets the official ENS registry. */ function getENSRegistry() public view returns (ENSRegistry) { return ENSRegistry(ensRegistry); } /** * @dev Gets the official ENS reverse registrar. */ function getENSReverseRegistrar() public view returns (ENSReverseRegistrar) { return ENSReverseRegistrar(getENSRegistry().owner(ADDR_REVERSE_NODE)); } } // Copyright 2017 Loopring Technology Limited. /// @title AddressSet /// @author Daniel Wang - <[email protected]> contract AddressSet { struct Set { address[] addresses; mapping (address => uint) positions; uint count; } mapping (bytes32 => Set) private sets; function addAddressToSet( bytes32 key, address addr, bool maintainList ) internal { Set storage set = sets[key]; require(set.positions[addr] == 0, "ALREADY_IN_SET"); if (maintainList) { require(set.addresses.length == set.count, "PREVIOUSLY_NOT_MAINTAILED"); set.addresses.push(addr); } else { require(set.addresses.length == 0, "MUST_MAINTAIN"); } set.count += 1; set.positions[addr] = set.count; } function removeAddressFromSet( bytes32 key, address addr ) internal { Set storage set = sets[key]; uint pos = set.positions[addr]; require(pos != 0, "NOT_IN_SET"); delete set.positions[addr]; set.count -= 1; if (set.addresses.length > 0) { address lastAddr = set.addresses[set.count]; if (lastAddr != addr) { set.addresses[pos - 1] = lastAddr; set.positions[lastAddr] = pos; } set.addresses.pop(); } } function removeSet(bytes32 key) internal { delete sets[key]; } function isAddressInSet( bytes32 key, address addr ) internal view returns (bool) { return sets[key].positions[addr] != 0; } function numAddressesInSet(bytes32 key) internal view returns (uint) { Set storage set = sets[key]; return set.count; } function addressesInSet(bytes32 key) internal view returns (address[] memory) { Set storage set = sets[key]; require(set.count == set.addresses.length, "NOT_MAINTAINED"); return sets[key].addresses; } } // Copyright 2017 Loopring Technology Limited. /// @title DataStore /// @dev Modules share states by accessing the same storage instance. /// Using ModuleStorage will achieve better module decoupling. /// /// @author Daniel Wang - <[email protected]> /// /// The design of this contract is inspired by Argent's contract codebase: /// https://github.com/argentlabs/argent-contracts abstract contract DataStore { modifier onlyWalletModule(address wallet) { require(Wallet(wallet).hasModule(msg.sender), "UNAUTHORIZED"); _; } } // Taken from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/SafeCast.sol /** * @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 uint40 from uint256, reverting on * overflow (when the input is greater than largest uint40). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 40 bits */ function toUint40(uint256 value) internal pure returns (uint40) { require(value < 2**40, "SafeCast: value doesn\'t fit in 40 bits"); return uint40(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 2017 Loopring Technology Limited. /// @title Claimable /// @author Brecht Devos - <[email protected]> /// @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, "UNAUTHORIZED"); _; } /// @dev Allows the current owner to set the pendingOwner address. /// @param newOwner The address to transfer ownership to. function transferOwnership( address newOwner ) public override onlyOwner { require(newOwner != address(0) && newOwner != owner, "INVALID_ADDRESS"); pendingOwner = newOwner; } /// @dev Allows the pendingOwner address to finalize the transfer. function claimOwnership() public onlyPendingOwner { emit OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } } // Copyright 2017 Loopring Technology Limited. /// @title Utility Functions for uint /// @author Daniel Wang - <[email protected]> library MathUint { function mul( uint a, uint b ) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b, "MUL_OVERFLOW"); } function sub( uint a, uint b ) internal pure returns (uint) { require(b <= a, "SUB_UNDERFLOW"); return a - b; } function add( uint a, uint b ) internal pure returns (uint c) { c = a + b; require(c >= a, "ADD_OVERFLOW"); } } //Mainly taken from https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol library BytesUtil { function slice( bytes memory _bytes, uint _start, uint _length ) internal pure returns (bytes memory) { require(_bytes.length >= (_start + _length)); bytes memory tempBytes; assembly { switch iszero(_length) case 0 { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // The first word of the slice result is potentially a partial // word read from the original array. To read it, we calculate // the length of that partial word and start copying that many // bytes into the array. The first word we copy will start with // data we don't care about, but the last `lengthmod` bytes will // land at the beginning of the contents of the new array. When // we're done copying, we overwrite the full first word with // the actual length of the slice. let lengthmod := and(_length, 31) // The multiplication in the next line is necessary // because when slicing multiples of 32 bytes (lengthmod == 0) // the following copy loop was copying the origin's length // and then ending prematurely not copying everything it should. let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod))) let end := add(mc, _length) for { // The multiplication in the next line has the same exact purpose // as the one above. let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(tempBytes, _length) //update free-memory pointer //allocating the array padded to 32 bytes like the compiler does now mstore(0x40, and(add(mc, 31), not(31))) } //if we want a zero-length slice let's just return a zero-length array default { tempBytes := mload(0x40) mstore(0x40, add(tempBytes, 0x20)) } } return tempBytes; } function toAddress(bytes memory _bytes, uint _start) internal pure returns (address) { require(_bytes.length >= (_start + 20)); address tempAddress; assembly { tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000) } return tempAddress; } function toUint8(bytes memory _bytes, uint _start) internal pure returns (uint8) { require(_bytes.length >= (_start + 1)); uint8 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x1), _start)) } return tempUint; } function toUint16(bytes memory _bytes, uint _start) internal pure returns (uint16) { require(_bytes.length >= (_start + 2)); uint16 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x2), _start)) } return tempUint; } function toUint24(bytes memory _bytes, uint _start) internal pure returns (uint24) { require(_bytes.length >= (_start + 3)); uint24 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x3), _start)) } return tempUint; } function toUint32(bytes memory _bytes, uint _start) internal pure returns (uint32) { require(_bytes.length >= (_start + 4)); uint32 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x4), _start)) } return tempUint; } function toUint64(bytes memory _bytes, uint _start) internal pure returns (uint64) { require(_bytes.length >= (_start + 8)); uint64 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x8), _start)) } return tempUint; } function toUint96(bytes memory _bytes, uint _start) internal pure returns (uint96) { require(_bytes.length >= (_start + 12)); uint96 tempUint; assembly { tempUint := mload(add(add(_bytes, 0xc), _start)) } return tempUint; } function toUint128(bytes memory _bytes, uint _start) internal pure returns (uint128) { require(_bytes.length >= (_start + 16)); uint128 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x10), _start)) } return tempUint; } function toUint(bytes memory _bytes, uint _start) internal pure returns (uint256) { require(_bytes.length >= (_start + 32)); uint256 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x20), _start)) } return tempUint; } function toBytes4(bytes memory _bytes, uint _start) internal pure returns (bytes4) { require(_bytes.length >= (_start + 4)); bytes4 tempBytes4; assembly { tempBytes4 := mload(add(add(_bytes, 0x20), _start)) } return tempBytes4; } function toBytes32(bytes memory _bytes, uint _start) internal pure returns (bytes32) { require(_bytes.length >= (_start + 32)); bytes32 tempBytes32; assembly { tempBytes32 := mload(add(add(_bytes, 0x20), _start)) } return tempBytes32; } function fastSHA256( bytes memory data ) internal view returns (bytes32) { bytes32[] memory result = new bytes32[](1); bool success; assembly { let ptr := add(data, 32) success := staticcall(sub(gas(), 2000), 2, ptr, mload(data), add(result, 32), 32) } require(success, "SHA256_FAILED"); return result[0]; } } // Copyright 2017 Loopring Technology Limited. /// @title Utility Functions for addresses /// @author Daniel Wang - <[email protected]> /// @author Brecht Devos - <[email protected]> library AddressUtil { using AddressUtil for *; function isContract( address addr ) 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; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(addr) } return (codehash != 0x0 && codehash != 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470); } function toPayable( address addr ) internal pure returns (address payable) { return address(uint160(addr)); } // Works like address.send but with a customizable gas limit // Make sure your code is safe for reentrancy when using this function! function sendETH( address to, uint amount, uint gasLimit ) internal returns (bool success) { if (amount == 0) { return true; } address payable recipient = to.toPayable(); /* solium-disable-next-line */ (success,) = recipient.call{value: amount, gas: gasLimit}(""); } // Works like address.transfer but with a customizable gas limit // Make sure your code is safe for reentrancy when using this function! function sendETHAndVerify( address to, uint amount, uint gasLimit ) internal returns (bool success) { success = to.sendETH(amount, gasLimit); require(success, "TRANSFER_FAILURE"); } } // Copyright 2017 Loopring Technology Limited. /// @title ERC20 Token Interface /// @dev see https://github.com/ethereum/EIPs/issues/20 /// @author Daniel Wang - <[email protected]> abstract contract ERC20 { function totalSupply() public view virtual returns (uint); function balanceOf( address who ) public view virtual returns (uint); function allowance( address owner, address spender ) public view virtual returns (uint); function transfer( address to, uint value ) public virtual returns (bool); function transferFrom( address from, address to, uint value ) public virtual returns (bool); function approve( address spender, uint value ) public virtual returns (bool); } // Copyright 2017 Loopring Technology Limited. library Data { // Optimized to fit into 32 bytes (1 slot) struct Guardian { address addr; uint16 group; uint40 validSince; uint40 validUntil; } } // Copyright 2017 Loopring Technology Limited. /// @title WalletRegistry /// @dev A registry for wallets. /// @author Daniel Wang - <[email protected]> interface WalletRegistry { function registerWallet(address wallet) external; function isWalletRegistered(address addr) external view returns (bool); function numOfWallets() external view returns (uint); } // Copyright 2017 Loopring Technology Limited. /// @title PriceOracle interface PriceOracle { // @dev Return's the token's value in ETH function tokenValue(address token, uint amount) external view returns (uint value); } // Copyright 2017 Loopring Technology Limited. // Copyright 2017 Loopring Technology Limited. /// @title ModuleRegistry /// @dev A registry for modules. /// /// @author Daniel Wang - <[email protected]> interface ModuleRegistry { /// @dev Registers and enables a new module. function registerModule(address module) external; /// @dev Disables a module function disableModule(address module) external; /// @dev Returns true if the module is registered and enabled. function isModuleEnabled(address module) external view returns (bool); /// @dev Returns the list of enabled modules. function enabledModules() external view returns (address[] memory _modules); /// @dev Returns the number of enbaled modules. function numOfEnabledModules() external view returns (uint); /// @dev Returns true if the module is ever registered. function isModuleRegistered(address module) external view returns (bool); } /// @title Controller /// /// @author Daniel Wang - <[email protected]> abstract contract Controller { ModuleRegistry public moduleRegistry; WalletRegistry public walletRegistry; address public walletFactory; } // Copyright 2017 Loopring Technology Limited. pragma experimental ABIEncoderV2; library EIP712 { struct Domain { string name; string version; address verifyingContract; } bytes32 constant internal EIP712_DOMAIN_TYPEHASH = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ); string constant internal EIP191_HEADER = "\x19\x01"; function hash(Domain memory domain) internal pure returns (bytes32) { uint _chainid; assembly { _chainid := chainid() } return keccak256( abi.encode( EIP712_DOMAIN_TYPEHASH, keccak256(bytes(domain.name)), keccak256(bytes(domain.version)), _chainid, domain.verifyingContract ) ); } function hashPacked( bytes32 domainSeperator, bytes memory encodedData ) internal pure returns (bytes32) { return keccak256( abi.encodePacked(EIP191_HEADER, domainSeperator, keccak256(encodedData)) ); } } // Copyright 2017 Loopring Technology Limited. // Copyright 2017 Loopring Technology Limited. /// @title SecurityStore /// /// @author Daniel Wang - <[email protected]> /// /// The design of this contract is inspired by Argent's contract codebase: /// https://github.com/argentlabs/argent-contracts contract SecurityStore is DataStore { using MathUint for uint; using SafeCast for uint; struct Wallet { address inheritor; uint64 lastActive; // the latest timestamp the owner is considered to be active address lockedBy; // the module that locked the wallet. uint64 lock; Data.Guardian[] guardians; mapping (address => uint) guardianIdx; } mapping (address => Wallet) public wallets; constructor() DataStore() {} function isGuardian( address wallet, address addr ) public view returns (bool) { Data.Guardian memory guardian = getGuardian(wallet, addr); return guardian.addr != address(0) && isGuardianActive(guardian); } function isGuardianOrPendingAddition( address wallet, address addr ) public view returns (bool) { Data.Guardian memory guardian = getGuardian(wallet, addr); return guardian.addr != address(0) && (isGuardianActive(guardian) || isGuardianPendingAddition(guardian)); } function getGuardian( address wallet, address guardianAddr ) public view returns (Data.Guardian memory) { uint index = wallets[wallet].guardianIdx[guardianAddr]; if (index > 0) { return wallets[wallet].guardians[index-1]; } } // @dev Returns active guardians. function guardians(address wallet) public view returns (Data.Guardian[] memory _guardians) { Wallet storage w = wallets[wallet]; _guardians = new Data.Guardian[](w.guardians.length); uint index = 0; for (uint i = 0; i < w.guardians.length; i++) { Data.Guardian memory g = w.guardians[i]; if (isGuardianActive(g)) { _guardians[index] = g; index ++; } } assembly { mstore(_guardians, index) } } // @dev Returns the number of active guardians. function numGuardians(address wallet) public view returns (uint count) { Wallet storage w = wallets[wallet]; for (uint i = 0; i < w.guardians.length; i++) { if (isGuardianActive(w.guardians[i])) { count ++; } } } // @dev Returns guardians who are either active or pending addition. function guardiansWithPending(address wallet) public view returns (Data.Guardian[] memory _guardians) { Wallet storage w = wallets[wallet]; _guardians = new Data.Guardian[](w.guardians.length); uint index = 0; for (uint i = 0; i < w.guardians.length; i++) { Data.Guardian memory g = w.guardians[i]; if (isGuardianActive(g) || isGuardianPendingAddition(g)) { _guardians[index] = g; index ++; } } assembly { mstore(_guardians, index) } } // @dev Returns the number of guardians who are active or pending addition. function numGuardiansWithPending(address wallet) public view returns (uint count) { Wallet storage w = wallets[wallet]; for (uint i = 0; i < w.guardians.length; i++) { Data.Guardian memory g = w.guardians[i]; if (isGuardianActive(g) || isGuardianPendingAddition(g)) { count ++; } } } function addGuardian( address wallet, address guardianAddr, uint group, uint validSince ) public onlyWalletModule(wallet) { cleanRemovedGuardians(wallet); require(guardianAddr != address(0), "ZERO_ADDRESS"); Wallet storage w = wallets[wallet]; uint pos = w.guardianIdx[guardianAddr]; require(pos == 0, "GUARDIAN_EXISTS"); // Add the new guardian Data.Guardian memory g = Data.Guardian( guardianAddr, group.toUint16(), validSince.toUint40(), uint40(0) ); w.guardians.push(g); w.guardianIdx[guardianAddr] = w.guardians.length; } function cancelGuardianAddition( address wallet, address guardianAddr ) public onlyWalletModule(wallet) { cleanRemovedGuardians(wallet); Wallet storage w = wallets[wallet]; uint idx = w.guardianIdx[guardianAddr]; require(idx > 0, "GUARDIAN_NOT_EXISTS"); require( isGuardianPendingAddition(w.guardians[idx - 1]), "NOT_PENDING_ADDITION" ); Data.Guardian memory lastGuardian = w.guardians[w.guardians.length - 1]; if (guardianAddr != lastGuardian.addr) { w.guardians[idx - 1] = lastGuardian; w.guardianIdx[lastGuardian.addr] = idx; } w.guardians.pop(); delete w.guardianIdx[guardianAddr]; } function removeGuardian( address wallet, address guardianAddr, uint validUntil ) public onlyWalletModule(wallet) { cleanRemovedGuardians(wallet); Wallet storage w = wallets[wallet]; uint idx = w.guardianIdx[guardianAddr]; require(idx > 0, "GUARDIAN_NOT_EXISTS"); w.guardians[idx - 1].validUntil = validUntil.toUint40(); } function removeAllGuardians(address wallet) public onlyWalletModule(wallet) { Wallet storage w = wallets[wallet]; for (uint i = 0; i < w.guardians.length; i++) { delete w.guardianIdx[w.guardians[i].addr]; } delete w.guardians; } function cancelGuardianRemoval( address wallet, address guardianAddr ) public onlyWalletModule(wallet) { cleanRemovedGuardians(wallet); Wallet storage w = wallets[wallet]; uint idx = w.guardianIdx[guardianAddr]; require(idx > 0, "GUARDIAN_NOT_EXISTS"); require( isGuardianPendingRemoval(w.guardians[idx - 1]), "NOT_PENDING_REMOVAL" ); w.guardians[idx - 1].validUntil = 0; } function getLock(address wallet) public view returns (uint _lock, address _lockedBy) { _lock = wallets[wallet].lock; _lockedBy = wallets[wallet].lockedBy; } function setLock( address wallet, uint lock ) public onlyWalletModule(wallet) { require(lock == 0 || lock > block.timestamp, "INVALID_LOCK_TIME"); wallets[wallet].lock = lock.toUint64(); wallets[wallet].lockedBy = msg.sender; } function lastActive(address wallet) public view returns (uint) { return wallets[wallet].lastActive; } function touchLastActive(address wallet) public onlyWalletModule(wallet) { wallets[wallet].lastActive = uint64(block.timestamp); } function inheritor(address wallet) public view returns ( address _who, uint _lastActive ) { _who = wallets[wallet].inheritor; _lastActive = wallets[wallet].lastActive; } function setInheritor(address wallet, address who) public onlyWalletModule(wallet) { wallets[wallet].inheritor = who; wallets[wallet].lastActive = uint64(block.timestamp); } function cleanRemovedGuardians(address wallet) private { Wallet storage w = wallets[wallet]; for (int i = int(w.guardians.length) - 1; i >= 0; i--) { Data.Guardian memory g = w.guardians[uint(i)]; if (isGuardianExpired(g)) { Data.Guardian memory lastGuardian = w.guardians[w.guardians.length - 1]; if (g.addr != lastGuardian.addr) { w.guardians[uint(i)] = lastGuardian; w.guardianIdx[lastGuardian.addr] = uint(i) + 1; } w.guardians.pop(); delete w.guardianIdx[g.addr]; } } } function isGuardianActive(Data.Guardian memory guardian) private view returns (bool) { return guardian.validSince > 0 && guardian.validSince <= block.timestamp && !isGuardianExpired(guardian); } function isGuardianPendingAddition(Data.Guardian memory guardian) private view returns (bool) { return guardian.validSince > block.timestamp; } function isGuardianPendingRemoval(Data.Guardian memory guardian) private view returns (bool) { return guardian.validUntil > block.timestamp; } function isGuardianExpired(Data.Guardian memory guardian) private view returns (bool) { return guardian.validUntil > 0 && guardian.validUntil <= block.timestamp; } } /// @title GuardianUtils /// @author Brecht Devos - <[email protected]> library GuardianUtils { uint constant public MAX_NUM_GROUPS = 16; enum SigRequirement { OwnerNotAllowed, OwnerAllowed, OwnerRequired } function requireMajority( SecurityStore securityStore, address wallet, address[] memory signers, SigRequirement requirement ) internal view returns (bool) { // We always need at least one signer if (signers.length == 0) { return false; } // Calculate total group sizes Data.Guardian[] memory allGuardians = securityStore.guardians(wallet); uint[MAX_NUM_GROUPS] memory total = countGuardians(allGuardians); // Calculate how many signers are in each group bool walletOwnerSigned = false; Data.Guardian[] memory signingGuardians = new Data.Guardian[](signers.length); address walletOwner = Wallet(wallet).owner(); uint numGuardians = 0; address lastSigner; for (uint i = 0; i < signers.length; i++) { // Check for duplicates require(signers[i] > lastSigner, "INVALID_SIGNERS_ORDER"); lastSigner = signers[i]; if (signers[i] == walletOwner) { walletOwnerSigned = true; } else { require(securityStore.isGuardian(wallet, signers[i]), "SIGNER_NOT_GUARDIAN"); signingGuardians[numGuardians++] = securityStore.getGuardian(wallet, signers[i]); } } // Check owner requirements if (requirement == SigRequirement.OwnerRequired) { require(walletOwnerSigned, "WALLET_OWNER_SIGNATURE_REQUIRED"); } else if (requirement == SigRequirement.OwnerNotAllowed) { require(!walletOwnerSigned, "WALLET_OWNER_SIGNATURE_NOT_ALLOWED"); } // Update the signingGuardians array with the actual number of guardians that have signed // (could be 1 less than the length if the owner signed as well) assembly { mstore(signingGuardians, numGuardians) } uint[MAX_NUM_GROUPS] memory signed = countGuardians(signingGuardians); // Count the number of votes uint totalNumVotes = 0; uint numVotes = 0; if (requirement != SigRequirement.OwnerNotAllowed) { totalNumVotes += 1; numVotes += walletOwnerSigned ? 1 : 0; } if (total[0] > 0) { // Group 0: No grouping totalNumVotes += total[0]; numVotes += signed[0]; } for (uint i = 1; i < MAX_NUM_GROUPS; i++) { if (total[i] > 0) { totalNumVotes += 1; if (i < 6) { // Groups [1, 5]: Single guardian needed per group numVotes += signed[i] > 0 ? 1 : 0; } else if (i < 11) { // Groups [6, 10]: Half the guardians needed per group numVotes += hasHalf(signed[i], total[i]) ? 1 : 0; } else { // Groups [11, 15]: A majority of guardians needed per group numVotes += hasMajority(signed[i], total[i]) ? 1 : 0; } } } // We need a majority of votes require(hasMajority(numVotes, totalNumVotes), "NOT_ENOUGH_SIGNERS"); return true; } function hasHalf( uint count, uint total ) internal pure returns (bool) { return (count >= (total + 1) / 2); } function hasMajority( uint count, uint total ) internal pure returns (bool) { return (count >= (total / 2) + 1); } function countGuardians( Data.Guardian[] memory guardians ) internal pure returns (uint[MAX_NUM_GROUPS] memory total) { for (uint i = 0; i < guardians.length; i++) { total[guardians[i].group]++; } } } // Copyright 2017 Loopring Technology Limited. /// @title SignatureUtil /// @author Daniel Wang - <[email protected]> /// @dev This method supports multihash standard. Each signature's first byte indicates /// the signature's type, the second byte indicates the signature's length, therefore, /// each signature will have 2 extra bytes prefix. Mulitple signatures are concatenated /// together. library SignatureUtil { using BytesUtil for bytes; using MathUint for uint; using AddressUtil for address; enum SignatureType { ILLEGAL, INVALID, EIP_712, ETH_SIGN, WALLET // deprecated } bytes4 constant internal ERC1271_MAGICVALUE = 0x20c13b0b; bytes4 constant internal ERC1271_FUNCTION_WITH_BYTES_SELECTOR = bytes4( keccak256(bytes("isValidSignature(bytes,bytes)")) ); bytes4 constant internal ERC1271_FUNCTION_WITH_BYTES32_SELECTOR = bytes4( keccak256(bytes("isValidSignature(bytes32,bytes)")) ); function verifySignatures( bytes32 signHash, address[] memory signers, bytes[] memory signatures ) internal view returns (bool) { return verifySignatures(abi.encodePacked(signHash), signers, signatures); } function verifySignatures( bytes memory data, address[] memory signers, bytes[] memory signatures ) internal view returns (bool) { require(signers.length == signatures.length, "BAD_SIGNATURE_DATA"); address lastSigner; for (uint i = 0; i < signers.length; i++) { require(signers[i] > lastSigner, "INVALID_SIGNERS_ORDER"); lastSigner = signers[i]; if (!verifySignature(data, signers[i], signatures[i])) { return false; } } return true; } function verifySignature( bytes memory data, address signer, bytes memory signature ) internal view returns (bool) { return signer.isContract() ? verifyERC1271Signature(data, signer, signature) : verifyEOASignature(data, signer, signature); } function verifySignature( bytes32 signHash, address signer, bytes memory signature ) internal view returns (bool) { return verifySignature(abi.encodePacked(signHash), signer, signature); } function recoverECDSASigner( bytes32 signHash, bytes memory signature ) internal pure returns (address) { if (signature.length != 65) { return address(0); } bytes32 r; bytes32 s; uint8 v; // we jump 32 (0x20) as the first slot of bytes contains the length // we jump 65 (0x41) per signature // for v we load 32 bytes ending with v (the first 31 come from s) then apply a mask assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := and(mload(add(signature, 0x41)), 0xff) } // See https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/cryptography/ECDSA.sol if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return address(0); } if (v == 27 || v == 28) { return ecrecover(signHash, v, r, s); } else { return address(0); } } function recoverECDSASigner( bytes memory data, bytes memory signature ) internal pure returns (address addr1, address addr2) { if (data.length == 32) { addr1 = recoverECDSASigner(data.toBytes32(0), signature); } addr2 = recoverECDSASigner(keccak256(data), signature); } function verifyEOASignature( bytes memory data, address signer, bytes memory signature ) private pure returns (bool) { if (signer == address(0)) { return false; } uint signatureTypeOffset = signature.length.sub(1); SignatureType signatureType = SignatureType(signature.toUint8(signatureTypeOffset)); bytes memory stripped = signature.slice(0, signatureTypeOffset); if (signatureType == SignatureType.EIP_712) { (address addr1, address addr2) = recoverECDSASigner(data, stripped); return addr1 == signer || addr2 == signer; } else if (signatureType == SignatureType.ETH_SIGN) { if (data.length == 32) { bytes32 hash = keccak256( abi.encodePacked("\x19Ethereum Signed Message:\n32", data.toBytes32(0)) ); if (recoverECDSASigner(hash, stripped) == signer) { return true; } } bytes32 hash = keccak256( abi.encodePacked("\x19Ethereum Signed Message:\n32", keccak256(data)) ); return recoverECDSASigner(hash, stripped) == signer; } else { return false; } } function verifyERC1271Signature( bytes memory data, address signer, bytes memory signature ) private view returns (bool) { return data.length == 32 && verifyERC1271WithBytes32(data.toBytes32(0), signer, signature) || verifyERC1271WithBytes(data, signer, signature); } function verifyERC1271WithBytes( bytes memory data, address signer, bytes memory signature ) private view returns (bool) { bytes memory callData = abi.encodeWithSelector( ERC1271_FUNCTION_WITH_BYTES_SELECTOR, data, signature ); (bool success, bytes memory result) = signer.staticcall(callData); return ( success && result.length == 32 && result.toBytes4(0) == ERC1271_MAGICVALUE ); } function verifyERC1271WithBytes32( bytes32 hash, address signer, bytes memory signature ) private view returns (bool) { bytes memory callData = abi.encodeWithSelector( ERC1271_FUNCTION_WITH_BYTES32_SELECTOR, hash, signature ); (bool success, bytes memory result) = signer.staticcall(callData); return ( success && result.length == 32 && result.toBytes4(0) == ERC1271_MAGICVALUE ); } } // Copyright 2017 Loopring Technology Limited. // Copyright 2017 Loopring Technology Limited. // Copyright 2017 Loopring Technology Limited. // Copyright 2017 Loopring Technology Limited. // Copyright 2017 Loopring Technology Limited. // Copyright 2017 Loopring Technology Limited. /// @title Module /// @dev Base contract for all smart wallet modules. /// /// @author Daniel Wang - <[email protected]> /// /// The design of this contract is inspired by Argent's contract codebase: /// https://github.com/argentlabs/argent-contracts interface Module { /// @dev Activates the module for the given wallet (msg.sender) after the module is added. /// Warning: this method shall ONLY be callable by a wallet. function activate() external; /// @dev Deactivates the module for the given wallet (msg.sender) before the module is removed. /// Warning: this method shall ONLY be callable by a wallet. function deactivate() external; } // Copyright 2017 Loopring Technology Limited. /// @title ReentrancyGuard /// @author Brecht Devos - <[email protected]> /// @dev Exposes a modifier that guards a function against reentrancy /// Changing the value of the same storage value multiple times in a transaction /// is cheap (starting from Istanbul) so there is no need to minimize /// the number of times the value is changed contract ReentrancyGuard { //The default value must be 0 in order to work behind a proxy. uint private _guardValue; modifier nonReentrant() { require(_guardValue == 0, "REENTRANCY"); _guardValue = 1; _; _guardValue = 0; } } /// @title BaseModule /// @dev This contract implements some common functions that are likely /// be useful for all modules. /// /// @author Daniel Wang - <[email protected]> /// /// The design of this contract is inspired by Argent's contract codebase: /// https://github.com/argentlabs/argent-contracts abstract contract BaseModule is ReentrancyGuard, Module { using MathUint for uint; using AddressUtil for address; event Activated (address wallet); event Deactivated (address wallet); function logicalSender() internal view virtual returns (address payable) { return msg.sender; } modifier onlyWalletOwner(address wallet, address addr) virtual { require(Wallet(wallet).owner() == addr, "NOT_WALLET_OWNER"); _; } modifier notWalletOwner(address wallet, address addr) virtual { require(Wallet(wallet).owner() != addr, "IS_WALLET_OWNER"); _; } modifier eligibleWalletOwner(address addr) { require(addr != address(0) && !addr.isContract(), "INVALID_OWNER"); _; } function controller() internal view virtual returns(ControllerImpl); /// @dev This method will cause an re-entry to the same module contract. function activate() external override virtual { address wallet = logicalSender(); bindMethods(wallet); emit Activated(wallet); } /// @dev This method will cause an re-entry to the same module contract. function deactivate() external override virtual { address wallet = logicalSender(); unbindMethods(wallet); emit Deactivated(wallet); } ///.@dev Gets the list of methods for binding to wallets. /// Sub-contracts should override this method to provide methods for /// wallet binding. /// @return methods A list of method selectors for binding to the wallet /// when this module is activated for the wallet. function bindableMethods() public pure virtual returns (bytes4[] memory methods); // ===== internal & private methods ===== /// @dev Binds all methods to the given wallet. function bindMethods(address wallet) internal { Wallet w = Wallet(wallet); bytes4[] memory methods = bindableMethods(); for (uint i = 0; i < methods.length; i++) { w.bindMethod(methods[i], address(this)); } } /// @dev Unbinds all methods from the given wallet. function unbindMethods(address wallet) internal { Wallet w = Wallet(wallet); bytes4[] memory methods = bindableMethods(); for (uint i = 0; i < methods.length; i++) { w.bindMethod(methods[i], address(0)); } } function transactCall( address wallet, address to, uint value, bytes memory data ) internal returns (bytes memory) { return Wallet(wallet).transact(uint8(1), to, value, data); } // Special case for transactCall to support transfers on "bad" ERC20 tokens function transactTokenTransfer( address wallet, address token, address to, uint amount ) internal { if (token == address(0)) { transactCall(wallet, to, amount, ""); return; } bytes memory txData = abi.encodeWithSelector( ERC20.transfer.selector, to, amount ); bytes memory returnData = transactCall(wallet, token, 0, txData); // `transactCall` will revert if the call was unsuccessful. // The only extra check we have to do is verify if the return value (if there is any) is correct. bool success = returnData.length == 0 ? true : abi.decode(returnData, (bool)); require(success, "ERC20_TRANSFER_FAILED"); } // Special case for transactCall to support approvals on "bad" ERC20 tokens function transactTokenApprove( address wallet, address token, address spender, uint amount ) internal { require(token != address(0), "INVALID_TOKEN"); bytes memory txData = abi.encodeWithSelector( ERC20.approve.selector, spender, amount ); bytes memory returnData = transactCall(wallet, token, 0, txData); // `transactCall` will revert if the call was unsuccessful. // The only extra check we have to do is verify if the return value (if there is any) is correct. bool success = returnData.length == 0 ? true : abi.decode(returnData, (bool)); require(success, "ERC20_APPROVE_FAILED"); } function transactDelegateCall( address wallet, address to, uint value, bytes memory data ) internal returns (bytes memory) { return Wallet(wallet).transact(uint8(2), to, value, data); } function transactStaticCall( address wallet, address to, bytes memory data ) internal returns (bytes memory) { return Wallet(wallet).transact(uint8(3), to, 0, data); } function reimburseGasFee( address wallet, address recipient, address gasToken, uint gasPrice, uint gasAmount, bool skipQuota ) internal { uint gasCost = gasAmount.mul(gasPrice); if (!skipQuota) { uint value = controller().priceOracle().tokenValue(gasToken, gasCost); if (value > 0) { controller().quotaStore().checkAndAddToSpent(wallet, value); } } transactTokenTransfer(wallet, gasToken, recipient, gasCost); } } // Copyright 2017 Loopring Technology Limited. /// @title MetaTxAware /// @author Daniel Wang - <[email protected]> /// /// The design of this contract is inspired by GSN's contract codebase: /// https://github.com/opengsn/gsn/contracts /// /// @dev Inherit this abstract contract to make a module meta-transaction /// aware. `msgSender()` shall be used to replace `msg.sender` for /// verifying permissions. abstract contract MetaTxAware { using AddressUtil for address; using BytesUtil for bytes; address public trustedForwarder; constructor(address _trustedForwarder) { trustedForwarder = _trustedForwarder; } modifier txAwareHashNotAllowed() { require(txAwareHash() == 0, "INVALID_TX_AWARE_HASH"); _; } /// @dev Return's the function's logicial message sender. This method should be // used to replace `msg.sender` for all meta-tx enabled functions. function msgSender() internal view returns (address payable) { if (msg.data.length >= 56 && msg.sender == trustedForwarder) { return msg.data.toAddress(msg.data.length - 52).toPayable(); } else { return msg.sender; } } function txAwareHash() internal view returns (bytes32) { if (msg.data.length >= 56 && msg.sender == trustedForwarder) { return msg.data.toBytes32(msg.data.length - 32); } else { return 0; } } } /// @title MetaTxModule /// @dev Base contract for all modules that support meta-transactions. /// /// @author Daniel Wang - <[email protected]> /// /// The design of this contract is inspired by GSN's contract codebase: /// https://github.com/opengsn/gsn/contracts abstract contract MetaTxModule is MetaTxAware, BaseModule { using SignatureUtil for bytes32; constructor(address _trustedForwarder) MetaTxAware(_trustedForwarder) { } function logicalSender() internal view virtual override returns (address payable) { return msgSender(); } } // Copyright 2017 Loopring Technology Limited. // Copyright 2017 Loopring Technology Limited. // Copyright 2017 Loopring Technology Limited. // Copyright 2017 Loopring Technology Limited. contract OwnerManagable is Claimable, AddressSet { bytes32 internal constant MANAGER = keccak256("__MANAGED__"); event ManagerAdded (address manager); event ManagerRemoved(address manager); modifier onlyManager { require(isManager(msg.sender), "NOT_MANAGER"); _; } modifier onlyOwnerOrManager { require(msg.sender == owner || isManager(msg.sender), "NOT_OWNER_OR_MANAGER"); _; } constructor() Claimable() {} /// @dev Gets the managers. /// @return The list of managers. function managers() public view returns (address[] memory) { return addressesInSet(MANAGER); } /// @dev Gets the number of managers. /// @return The numer of managers. function numManagers() public view returns (uint) { return numAddressesInSet(MANAGER); } /// @dev Checks if an address is a manger. /// @param addr The address to check. /// @return True if the address is a manager, False otherwise. function isManager(address addr) public view returns (bool) { return isAddressInSet(MANAGER, addr); } /// @dev Adds a new manager. /// @param manager The new address to add. function addManager(address manager) public onlyOwner { addManagerInternal(manager); } /// @dev Removes a manager. /// @param manager The manager to remove. function removeManager(address manager) public onlyOwner { removeAddressFromSet(MANAGER, manager); emit ManagerRemoved(manager); } function addManagerInternal(address manager) internal { addAddressToSet(MANAGER, manager, true); emit ManagerAdded(manager); } } /// @title DappAddressStore /// @dev This store maintains global whitelist dapps. contract DappAddressStore is DataStore, OwnerManagable { bytes32 internal constant DAPPS = keccak256("__DAPPS__"); event Whitelisted( address addr, bool whitelisted ); constructor() DataStore() {} function addDapp(address addr) public onlyManager { addAddressToSet(DAPPS, addr, true); emit Whitelisted(addr, true); } function removeDapp(address addr) public onlyManager { removeAddressFromSet(DAPPS, addr); emit Whitelisted(addr, false); } function dapps() public view returns ( address[] memory addresses ) { return addressesInSet(DAPPS); } function isDapp( address addr ) public view returns (bool) { return isAddressInSet(DAPPS, addr); } function numDapps() public view returns (uint) { return numAddressesInSet(DAPPS); } } // Copyright 2017 Loopring Technology Limited. /// @title HashStore /// @dev This store maintains all hashes for SignedRequest. contract HashStore is DataStore { // wallet => hash => consumed mapping(address => mapping(bytes32 => bool)) public hashes; constructor() {} function verifyAndUpdate(address wallet, bytes32 hash) public onlyWalletModule(wallet) { require(!hashes[wallet][hash], "HASH_EXIST"); hashes[wallet][hash] = true; } } // Copyright 2017 Loopring Technology Limited. /// @title NonceStore /// @dev This store maintains all nonces for metaTx contract NonceStore is DataStore { mapping(address => uint) public nonces; constructor() DataStore() {} function lastNonce(address wallet) public view returns (uint) { return nonces[wallet]; } function isNonceValid(address wallet, uint nonce) public view returns (bool) { return nonce > nonces[wallet] && (nonce >> 128) <= block.number; } function verifyAndUpdate(address wallet, uint nonce) public onlyWalletModule(wallet) { require(isNonceValid(wallet, nonce), "INVALID_NONCE"); nonces[wallet] = nonce; } } // Copyright 2017 Loopring Technology Limited. /// @title QuotaStore /// @dev This store maintains daily spending quota for each wallet. /// A rolling daily limit is used. contract QuotaStore is DataStore, Claimable { using MathUint for uint; using SafeCast for uint; uint128 public defaultQuota; // Optimized to fit into 64 bytes (2 slots) struct Quota { uint128 currentQuota; // 0 indicates default uint128 pendingQuota; uint128 spentAmount; uint64 spentTimestamp; uint64 pendingUntil; } mapping (address => Quota) public quotas; event DefaultQuotaChanged( uint prevValue, uint currentValue ); event QuotaScheduled( address wallet, uint pendingQuota, uint64 pendingUntil ); constructor(uint128 _defaultQuota) DataStore() { defaultQuota = _defaultQuota; } function changeDefaultQuota(uint128 _defaultQuota) external onlyOwner { require( _defaultQuota != defaultQuota && _defaultQuota >= 1 ether && _defaultQuota <= 100 ether, "INVALID_DEFAULT_QUOTA" ); emit DefaultQuotaChanged(defaultQuota, _defaultQuota); defaultQuota = _defaultQuota; } function changeQuota( address wallet, uint newQuota, uint effectiveTime ) public onlyWalletModule(wallet) { quotas[wallet].currentQuota = currentQuota(wallet).toUint128(); quotas[wallet].pendingQuota = newQuota.toUint128(); quotas[wallet].pendingUntil = effectiveTime.toUint64(); emit QuotaScheduled( wallet, newQuota, quotas[wallet].pendingUntil ); } function checkAndAddToSpent( address wallet, uint amount ) public onlyWalletModule(wallet) { require(hasEnoughQuota(wallet, amount), "QUOTA_EXCEEDED"); addToSpent(wallet, amount); } function addToSpent( address wallet, uint amount ) public onlyWalletModule(wallet) { Quota storage q = quotas[wallet]; q.spentAmount = spentQuota(wallet).add(amount).toUint128(); q.spentTimestamp = uint64(block.timestamp); } function currentQuota(address wallet) public view returns (uint) { Quota storage q = quotas[wallet]; uint value = q.pendingUntil <= block.timestamp ? q.pendingQuota : q.currentQuota; return value == 0 ? defaultQuota : value; } function pendingQuota(address wallet) public view returns ( uint _pendingQuota, uint _pendingUntil ) { Quota storage q = quotas[wallet]; if (q.pendingUntil > 0 && q.pendingUntil > block.timestamp) { _pendingQuota = q.pendingQuota > 0 ? q.pendingQuota : defaultQuota; _pendingUntil = q.pendingUntil; } } function spentQuota(address wallet) public view returns (uint) { Quota storage q = quotas[wallet]; uint timeSinceLastSpent = block.timestamp.sub(q.spentTimestamp); if (timeSinceLastSpent < 1 days) { return uint(q.spentAmount).sub(timeSinceLastSpent.mul(q.spentAmount) / 1 days); } else { return 0; } } function availableQuota(address wallet) public view returns (uint) { uint quota = currentQuota(wallet); uint spent = spentQuota(wallet); return quota > spent ? quota - spent : 0; } function hasEnoughQuota( address wallet, uint requiredAmount ) public view returns (bool) { return availableQuota(wallet) >= requiredAmount; } } // Copyright 2017 Loopring Technology Limited. /// @title WhitelistStore /// @dev This store maintains a wallet's whitelisted addresses. contract WhitelistStore is DataStore, AddressSet { // wallet => whitelisted_addr => effective_since mapping(address => mapping(address => uint)) public effectiveTimeMap; event Whitelisted( address wallet, address addr, bool whitelisted, uint effectiveTime ); constructor() DataStore() {} function addToWhitelist( address wallet, address addr, uint effectiveTime ) public onlyWalletModule(wallet) { addAddressToSet(walletKey(wallet), addr, true); uint effective = effectiveTime >= block.timestamp ? effectiveTime : block.timestamp; effectiveTimeMap[wallet][addr] = effective; emit Whitelisted(wallet, addr, true, effective); } function removeFromWhitelist( address wallet, address addr ) public onlyWalletModule(wallet) { removeAddressFromSet(walletKey(wallet), addr); delete effectiveTimeMap[wallet][addr]; emit Whitelisted(wallet, addr, false, 0); } function whitelist(address wallet) public view returns ( address[] memory addresses, uint[] memory effectiveTimes ) { addresses = addressesInSet(walletKey(wallet)); effectiveTimes = new uint[](addresses.length); for (uint i = 0; i < addresses.length; i++) { effectiveTimes[i] = effectiveTimeMap[wallet][addresses[i]]; } } function isWhitelisted( address wallet, address addr ) public view returns ( bool isWhitelistedAndEffective, uint effectiveTime ) { effectiveTime = effectiveTimeMap[wallet][addr]; isWhitelistedAndEffective = effectiveTime > 0 && effectiveTime <= block.timestamp; } function whitelistSize(address wallet) public view returns (uint) { return numAddressesInSet(walletKey(wallet)); } function walletKey(address addr) public pure returns (bytes32) { return keccak256(abi.encodePacked("__WHITELIST__", addr)); } } // Taken from Argent's code base - https://github.com/argentlabs/argent-contracts/blob/develop/contracts/ens/ArgentENSManager.sol // with few modifications. /** * @dev Interface for an ENS Mananger. */ interface IENSManager { function changeRootnodeOwner(address _newOwner) external; function isAvailable(bytes32 _subnode) external view returns (bool); function resolveName(address _wallet) external view returns (string memory); function register( address _wallet, address _owner, string calldata _label, bytes calldata _approval ) external; } /** * @title BaseENSManager * @dev Implementation of an ENS manager that orchestrates the complete * registration of subdomains for a single root (e.g. argent.eth). * The contract defines a manager role who is the only role that can trigger the registration of * a new subdomain. * @author Julien Niset - <[email protected]> */ contract BaseENSManager is IENSManager, OwnerManagable, ENSConsumer { using strings for *; using BytesUtil for bytes; using MathUint for uint; // The managed root name string public rootName; // The managed root node bytes32 public rootNode; // The address of the ENS resolver address public ensResolver; // *************** Events *************************** // event RootnodeOwnerChange(bytes32 indexed _rootnode, address indexed _newOwner); event ENSResolverChanged(address addr); event Registered(address indexed _wallet, address _owner, string _ens); event Unregistered(string _ens); // *************** Constructor ********************** // /** * @dev Constructor that sets the ENS root name and root node to manage. * @param _rootName The root name (e.g. argentx.eth). * @param _rootNode The node of the root name (e.g. namehash(argentx.eth)). */ constructor(string memory _rootName, bytes32 _rootNode, address _ensRegistry, address _ensResolver) ENSConsumer(_ensRegistry) { rootName = _rootName; rootNode = _rootNode; ensResolver = _ensResolver; } // *************** External Functions ********************* // /** * @dev This function must be called when the ENS Manager contract is replaced * and the address of the new Manager should be provided. * @param _newOwner The address of the new ENS manager that will manage the root node. */ function changeRootnodeOwner(address _newOwner) external override onlyOwner { getENSRegistry().setOwner(rootNode, _newOwner); emit RootnodeOwnerChange(rootNode, _newOwner); } /** * @dev Lets the owner change the address of the ENS resolver contract. * @param _ensResolver The address of the ENS resolver contract. */ function changeENSResolver(address _ensResolver) external onlyOwner { require(_ensResolver != address(0), "WF: address cannot be null"); ensResolver = _ensResolver; emit ENSResolverChanged(_ensResolver); } /** * @dev Lets the manager assign an ENS subdomain of the root node to a target address. * Registers both the forward and reverse ENS. * @param _wallet The wallet which owns the subdomain. * @param _owner The wallet's owner. * @param _label The subdomain label. * @param _approval The signature of _wallet, _owner and _label by a manager. */ function register( address _wallet, address _owner, string calldata _label, bytes calldata _approval ) external override onlyManager { verifyApproval(_wallet, _owner, _label, _approval); bytes32 labelNode = keccak256(abi.encodePacked(_label)); bytes32 node = keccak256(abi.encodePacked(rootNode, labelNode)); address currentOwner = getENSRegistry().owner(node); require(currentOwner == address(0), "AEM: _label is alrealdy owned"); // Forward ENS getENSRegistry().setSubnodeOwner(rootNode, labelNode, address(this)); getENSRegistry().setResolver(node, ensResolver); getENSRegistry().setOwner(node, _wallet); ENSResolver(ensResolver).setAddr(node, _wallet); // Reverse ENS strings.slice[] memory parts = new strings.slice[](2); parts[0] = _label.toSlice(); parts[1] = rootName.toSlice(); string memory name = ".".toSlice().join(parts); bytes32 reverseNode = getENSReverseRegistrar().node(_wallet); ENSResolver(ensResolver).setName(reverseNode, name); emit Registered(_wallet, _owner, name); } // *************** Public Functions ********************* // /** * @dev Resolves an address to an ENS name * @param _wallet The ENS owner address */ function resolveName(address _wallet) public view override returns (string memory) { bytes32 reverseNode = getENSReverseRegistrar().node(_wallet); return ENSResolver(ensResolver).name(reverseNode); } /** * @dev Returns true is a given subnode is available. * @param _subnode The target subnode. * @return true if the subnode is available. */ function isAvailable(bytes32 _subnode) public view override returns (bool) { bytes32 node = keccak256(abi.encodePacked(rootNode, _subnode)); address currentOwner = getENSRegistry().owner(node); if(currentOwner == address(0)) { return true; } return false; } function verifyApproval( address _wallet, address _owner, string memory _label, bytes memory _approval ) internal view { bytes32 messageHash = keccak256( abi.encodePacked( _wallet, _owner, _label ) ); bytes32 hash = keccak256( abi.encodePacked( "\x19Ethereum Signed Message:\n32", messageHash ) ); address signer = SignatureUtil.recoverECDSASigner(hash, _approval); require(isManager(signer), "UNAUTHORIZED"); } } /// @title ControllerImpl /// @dev Basic implementation of a Controller. /// /// @author Daniel Wang - <[email protected]> contract ControllerImpl is Claimable, Controller { address public collectTo; uint public defaultLockPeriod; BaseENSManager public ensManager; PriceOracle public priceOracle; DappAddressStore public dappAddressStore; HashStore public hashStore; NonceStore public nonceStore; QuotaStore public quotaStore; SecurityStore public securityStore; WhitelistStore public whitelistStore; // Make sure this value if false in production env. // Ideally we can use chainid(), but there is a bug in truffle so testing is buggy: // https://github.com/trufflesuite/ganache/issues/1643 bool public allowChangingWalletFactory; event AddressChanged( string name, address addr ); constructor( ModuleRegistry _moduleRegistry, WalletRegistry _walletRegistry, uint _defaultLockPeriod, address _collectTo, BaseENSManager _ensManager, PriceOracle _priceOracle, bool _allowChangingWalletFactory ) { moduleRegistry = _moduleRegistry; walletRegistry = _walletRegistry; defaultLockPeriod = _defaultLockPeriod; require(_collectTo != address(0), "ZERO_ADDRESS"); collectTo = _collectTo; ensManager = _ensManager; priceOracle = _priceOracle; allowChangingWalletFactory = _allowChangingWalletFactory; } function initStores( DappAddressStore _dappAddressStore, HashStore _hashStore, NonceStore _nonceStore, QuotaStore _quotaStore, SecurityStore _securityStore, WhitelistStore _whitelistStore ) external onlyOwner { require( address(_dappAddressStore) != address(0), "ZERO_ADDRESS" ); // Make sure this function can only invoked once. require( address(dappAddressStore) == address(0), "INITIALIZED_ALREADY" ); dappAddressStore = _dappAddressStore; hashStore = _hashStore; nonceStore = _nonceStore; quotaStore = _quotaStore; securityStore = _securityStore; whitelistStore = _whitelistStore; } function initWalletFactory(address _walletFactory) external onlyOwner { require( allowChangingWalletFactory || walletFactory == address(0), "INITIALIZED_ALREADY" ); require(_walletFactory != address(0), "ZERO_ADDRESS"); walletFactory = _walletFactory; emit AddressChanged("WalletFactory", walletFactory); } function setCollectTo(address _collectTo) external onlyOwner { require(_collectTo != address(0), "ZERO_ADDRESS"); collectTo = _collectTo; emit AddressChanged("CollectTo", collectTo); } function setPriceOracle(PriceOracle _priceOracle) external onlyOwner { priceOracle = _priceOracle; emit AddressChanged("PriceOracle", address(priceOracle)); } } /// @title SignedRequest /// @dev Utilitiy library for better handling of signed wallet requests. /// This library must be deployed and link to other modules. /// /// @author Daniel Wang - <[email protected]> library SignedRequest { using SignatureUtil for bytes32; struct Request { address[] signers; bytes[] signatures; uint validUntil; address wallet; } function verifyRequest( ControllerImpl controller, bytes32 domainSeperator, bytes32 txAwareHash, GuardianUtils.SigRequirement sigRequirement, Request memory request, bytes memory encodedRequest ) public { require(block.timestamp <= request.validUntil, "EXPIRED_SIGNED_REQUEST"); bytes32 _txAwareHash = EIP712.hashPacked(domainSeperator, encodedRequest); // Save hash to prevent replay attacks controller.hashStore().verifyAndUpdate(request.wallet, _txAwareHash); // If txAwareHash from the mata-transaction is non-zero, // we must verify it matches the hash signed by the respective signers. require( txAwareHash == 0 || txAwareHash == _txAwareHash, "TX_INNER_HASH_MISMATCH" ); require( _txAwareHash.verifySignatures(request.signers, request.signatures), "INVALID_SIGNATURES" ); require( GuardianUtils.requireMajority( controller.securityStore(), request.wallet, request.signers, sigRequirement ), "PERMISSION_DENIED" ); } } /// @title SecurityStore /// /// @author Daniel Wang - <[email protected]> /// /// The design of this contract is inspired by Argent's contract codebase: /// https://github.com/argentlabs/argent-contracts abstract contract SecurityModule is MetaTxModule { using SignedRequest for ControllerImpl; // The minimal number of guardians for recovery and locking. uint constant public MIN_ACTIVE_GUARDIANS = 2; uint constant public MIN_TOUCH_INTERVAL = 7 days; event WalletLock( address indexed wallet, uint lock ); constructor(address _trustedForwarder) MetaTxModule(_trustedForwarder) { } modifier onlyFromWalletOrOwnerWhenUnlocked(address wallet) { address payable _logicalSender = logicalSender(); // If the wallet's signature verfication passes, the wallet must be unlocked. require( _logicalSender == wallet || (_logicalSender == Wallet(wallet).owner() && !isWalletLocked(wallet)), "NOT_FROM_WALLET_OR_OWNER_OR_WALLET_LOCKED" ); SecurityStore ss = controller().securityStore(); if (block.timestamp > ss.lastActive(wallet) + MIN_TOUCH_INTERVAL) { ss.touchLastActive(wallet); } _; } modifier onlyFromGuardian(address wallet) { require( controller().securityStore().isGuardian(wallet, logicalSender()), "NOT_FROM_GUARDIAN" ); _; } modifier onlyWhenWalletLocked(address wallet) { require(isWalletLocked(wallet), "NOT_LOCKED"); _; } modifier onlyWhenWalletUnlocked(address wallet) { require(!isWalletLocked(wallet), "LOCKED"); _; } modifier onlyWalletGuardian(address wallet, address guardian) { require(controller().securityStore().isGuardian(wallet, guardian), "NOT_GUARDIAN"); _; } modifier notWalletGuardian(address wallet, address guardian) { require(!controller().securityStore().isGuardian(wallet, guardian), "IS_GUARDIAN"); _; } modifier onlyHaveEnoughGuardians(address wallet) { require( controller().securityStore().numGuardians(wallet) >= MIN_ACTIVE_GUARDIANS, "NO_ENOUGH_ACTIVE_GUARDIANS" ); _; } // ----- internal methods ----- function quotaStore() internal view returns (address) { return address(controller().quotaStore()); } function lockWallet(address wallet) internal { lockWallet(wallet, controller().defaultLockPeriod()); } function lockWallet(address wallet, uint _lockPeriod) internal onlyWhenWalletUnlocked(wallet) { // cannot lock the wallet twice by different modules. require(_lockPeriod > 0, "ZERO_VALUE"); uint lock = block.timestamp + _lockPeriod; controller().securityStore().setLock(wallet, lock); emit WalletLock(wallet, lock); } function unlockWallet(address wallet, bool forceUnlock) internal { (uint _lock, address _lockedBy) = controller().securityStore().getLock(wallet); if (_lock > block.timestamp) { require(forceUnlock || _lockedBy == address(this), "UNABLE_TO_UNLOCK"); controller().securityStore().setLock(wallet, 0); } emit WalletLock(wallet, 0); } function getWalletLock(address wallet) internal view returns (uint _lock, address _lockedBy) { return controller().securityStore().getLock(wallet); } function isWalletLocked(address wallet) internal view returns (bool) { (uint _lock,) = controller().securityStore().getLock(wallet); return _lock > block.timestamp; } function updateQuota( address wallet, address token, uint amount ) internal { if (amount > 0 && quotaStore() != address(0)) { uint value = controller().priceOracle().tokenValue(token, amount); QuotaStore(quotaStore()).checkAndAddToSpent(wallet, value); } } } /// @title GuardianModule /// @author Brecht Devos - <[email protected]> /// @author Daniel Wang - <[email protected]> abstract contract GuardianModule is SecurityModule { using SignatureUtil for bytes32; using AddressUtil for address; using SignedRequest for ControllerImpl; bytes32 public GUARDIAN_DOMAIN_SEPERATOR; uint constant public MAX_GUARDIANS = 20; uint public recoveryPendingPeriod; event GuardianAdded (address indexed wallet, address guardian, uint group, uint effectiveTime); event GuardianAdditionCancelled (address indexed wallet, address guardian); event GuardianRemoved (address indexed wallet, address guardian, uint removalEffectiveTime); event GuardianRemovalCancelled (address indexed wallet, address guardian); event Recovered( address indexed wallet, address newOwner ); bytes32 public constant RECOVER_TYPEHASH = keccak256( "recover(address wallet,uint256 validUntil,address newOwner)" ); constructor(uint _recoveryPendingPeriod) { GUARDIAN_DOMAIN_SEPERATOR = EIP712.hash( EIP712.Domain("GuardianModule", "1.1.0", address(this)) ); require(_recoveryPendingPeriod > 0, "INVALID_DELAY"); recoveryPendingPeriod = _recoveryPendingPeriod; } function addGuardian( address wallet, address guardian, uint group ) external nonReentrant txAwareHashNotAllowed() onlyFromWalletOrOwnerWhenUnlocked(wallet) notWalletOwner(wallet, guardian) { require(guardian != wallet, "INVALID_ADDRESS"); require(guardian != address(0), "ZERO_ADDRESS"); require(group < GuardianUtils.MAX_NUM_GROUPS, "INVALID_GROUP"); uint numGuardians = controller().securityStore().numGuardiansWithPending(wallet); require(numGuardians < MAX_GUARDIANS, "TOO_MANY_GUARDIANS"); uint effectiveTime = block.timestamp; if (numGuardians >= MIN_ACTIVE_GUARDIANS) { effectiveTime = block.timestamp + recoveryPendingPeriod; } controller().securityStore().addGuardian(wallet, guardian, group, effectiveTime); emit GuardianAdded(wallet, guardian, group, effectiveTime); } function cancelGuardianAddition( address wallet, address guardian ) external nonReentrant txAwareHashNotAllowed() onlyFromWalletOrOwnerWhenUnlocked(wallet) { controller().securityStore().cancelGuardianAddition(wallet, guardian); emit GuardianAdditionCancelled(wallet, guardian); } function removeGuardian( address wallet, address guardian ) external nonReentrant txAwareHashNotAllowed() onlyFromWalletOrOwnerWhenUnlocked(wallet) onlyWalletGuardian(wallet, guardian) { controller().securityStore().removeGuardian(wallet, guardian, block.timestamp + recoveryPendingPeriod); emit GuardianRemoved(wallet, guardian, block.timestamp + recoveryPendingPeriod); } function cancelGuardianRemoval( address wallet, address guardian ) external nonReentrant txAwareHashNotAllowed() onlyFromWalletOrOwnerWhenUnlocked(wallet) { controller().securityStore().cancelGuardianRemoval(wallet, guardian); emit GuardianRemovalCancelled(wallet, guardian); } function lock(address wallet) external nonReentrant txAwareHashNotAllowed() onlyFromGuardian(wallet) onlyHaveEnoughGuardians(wallet) { lockWallet(wallet); } function unlock(address wallet) external nonReentrant txAwareHashNotAllowed() onlyFromGuardian(wallet) { unlockWallet(wallet, false); } /// @dev Recover a wallet by setting a new owner. /// @param request The general request object. /// @param newOwner The new owner address to set. /// The addresses must be sorted ascendently. function recover( SignedRequest.Request calldata request, address newOwner ) external nonReentrant notWalletOwner(request.wallet, newOwner) eligibleWalletOwner(newOwner) onlyHaveEnoughGuardians(request.wallet) { controller().verifyRequest( GUARDIAN_DOMAIN_SEPERATOR, txAwareHash(), GuardianUtils.SigRequirement.OwnerNotAllowed, request, abi.encode( RECOVER_TYPEHASH, request.wallet, request.validUntil, newOwner ) ); SecurityStore securityStore = controller().securityStore(); if (securityStore.isGuardianOrPendingAddition(request.wallet, newOwner)) { securityStore.removeGuardian(request.wallet, newOwner, block.timestamp); } Wallet(request.wallet).setOwner(newOwner); // solium-disable-next-line unlockWallet(request.wallet, true /*force*/); emit Recovered(request.wallet, newOwner); } function getLock(address wallet) public view returns (uint _lock, address _lockedBy) { return getWalletLock(wallet); } function isLocked(address wallet) public view returns (bool) { return isWalletLocked(wallet); } } // Copyright 2017 Loopring Technology Limited. /// @title InheritanceModule /// @author Brecht Devos - <[email protected]> /// @author Daniel Wang - <[email protected]> abstract contract InheritanceModule is SecurityModule { using AddressUtil for address; using SignatureUtil for bytes32; uint public inheritWaitingPeriod; event Inherited( address indexed wallet, address inheritor, address newOwner ); event InheritorChanged( address indexed wallet, address inheritor ); constructor(uint _inheritWaitingPeriod) { require(_inheritWaitingPeriod > 0, "INVALID_DELAY"); inheritWaitingPeriod = _inheritWaitingPeriod; } function inheritor(address wallet) public view returns (address _inheritor, uint lastActive) { return controller().securityStore().inheritor(wallet); } function inherit( address wallet, address newOwner ) external nonReentrant txAwareHashNotAllowed() eligibleWalletOwner(newOwner) notWalletOwner(wallet, newOwner) { (address _inheritor, uint lastActive) = controller().securityStore().inheritor(wallet); require(logicalSender() == _inheritor, "NOT_ALLOWED"); require(lastActive > 0 && block.timestamp >= lastActive + inheritWaitingPeriod, "NEED_TO_WAIT"); SecurityStore securityStore = controller().securityStore(); securityStore.removeAllGuardians(wallet); securityStore.setInheritor(wallet, address(0)); Wallet(wallet).setOwner(newOwner); // solium-disable-next-line unlockWallet(wallet, true /*force*/); emit Inherited(wallet, _inheritor, newOwner); } function setInheritor( address wallet, address _inheritor ) external nonReentrant txAwareHashNotAllowed() onlyFromWalletOrOwnerWhenUnlocked(wallet) { require(controller().walletRegistry().isWalletRegistered(_inheritor), "NOT_A_WALLET"); (address existingInheritor,) = controller().securityStore().inheritor(wallet); require(existingInheritor != _inheritor, "SAME_INHERITOR"); controller().securityStore().setInheritor(wallet, _inheritor); emit InheritorChanged(wallet, _inheritor); } } // Copyright 2017 Loopring Technology Limited. /// @title WhitelistModule /// @dev Manages whitelisted addresses. /// @author Daniel Wang - <[email protected]> abstract contract WhitelistModule is SecurityModule { using MathUint for uint; using SignedRequest for ControllerImpl; bytes32 public WHITELIST_DOMAIN_SEPERATOR; bytes32 public constant ADD_TO_WHITELIST_IMMEDIATELY_TYPEHASH = keccak256( "addToWhitelistImmediately(address wallet,uint256 validUntil,address addr)" ); uint public whitelistDelayPeriod; constructor(uint _whitelistDelayPeriod) { require(_whitelistDelayPeriod > 0, "INVALID_DELAY"); WHITELIST_DOMAIN_SEPERATOR = EIP712.hash( EIP712.Domain("WhitelistModule", "1.1.0", address(this)) ); whitelistDelayPeriod = _whitelistDelayPeriod; } function addToWhitelist( address wallet, address addr ) external nonReentrant txAwareHashNotAllowed() onlyFromWalletOrOwnerWhenUnlocked(wallet) { controller().whitelistStore().addToWhitelist(wallet, addr, block.timestamp.add(whitelistDelayPeriod)); } function addToWhitelistImmediately( SignedRequest.Request calldata request, address addr ) external nonReentrant onlyWhenWalletUnlocked(request.wallet) { controller().verifyRequest( WHITELIST_DOMAIN_SEPERATOR, txAwareHash(), GuardianUtils.SigRequirement.OwnerRequired, request, abi.encode( ADD_TO_WHITELIST_IMMEDIATELY_TYPEHASH, request.wallet, request.validUntil, addr ) ); controller().whitelistStore().addToWhitelist(request.wallet, addr, block.timestamp); } function removeFromWhitelist( address wallet, address addr ) external nonReentrant txAwareHashNotAllowed() onlyFromWalletOrOwnerWhenUnlocked(wallet) { controller().whitelistStore().removeFromWhitelist(wallet, addr); } function getWhitelist(address wallet) public view returns ( address[] memory addresses, uint[] memory effectiveTimes ) { return controller().whitelistStore().whitelist(wallet); } function isWhitelisted( address wallet, address addr) public view returns ( bool isWhitelistedAndEffective, uint effectiveTime ) { return controller().whitelistStore().isWhitelisted(wallet, addr); } } /// @title FinalSecurityModule /// @dev This module combines multiple small modules to /// minimize the number of modules to reduce gas used /// by wallet creation. contract FinalSecurityModule is GuardianModule, InheritanceModule, WhitelistModule { ControllerImpl private controller_; constructor( ControllerImpl _controller, address _trustedForwarder, uint _recoveryPendingPeriod, uint _inheritWaitingPeriod, uint _whitelistDelayPeriod ) SecurityModule(_trustedForwarder) GuardianModule(_recoveryPendingPeriod) InheritanceModule(_inheritWaitingPeriod) WhitelistModule(_whitelistDelayPeriod) { controller_ = _controller; } function controller() internal view override returns(ControllerImpl) { return ControllerImpl(controller_); } function bindableMethods() public pure override returns (bytes4[] memory methods) { } }
wallet => hash => consumed
{ mapping(address => mapping(bytes32 => bool)) public hashes; function verifyAndUpdate(address wallet, bytes32 hash) public onlyWalletModule(wallet) contract HashStore is DataStore constructor() {} { require(!hashes[wallet][hash], "HASH_EXIST"); hashes[wallet][hash] = true; } }
1,091,449
[ 1, 19177, 516, 1651, 516, 12393, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 95, 203, 565, 2874, 12, 2867, 516, 2874, 12, 3890, 1578, 516, 1426, 3719, 1071, 9869, 31, 203, 203, 203, 565, 445, 3929, 1876, 1891, 12, 2867, 9230, 16, 1731, 1578, 1651, 13, 203, 3639, 1071, 203, 3639, 1338, 16936, 3120, 12, 19177, 13, 203, 203, 16351, 2474, 2257, 353, 22961, 203, 565, 3885, 1435, 2618, 203, 565, 288, 203, 3639, 2583, 12, 5, 17612, 63, 19177, 6362, 2816, 6487, 315, 15920, 67, 11838, 8863, 203, 3639, 9869, 63, 19177, 6362, 2816, 65, 273, 638, 31, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.18; //pragma experimental ABIEncoderV2; contract reviewing { mapping(address => mapping(uint256 =>string)) public reviews; // This is for storing the review w.r.t address and review count from that address mapping(address => mapping(uint256 =>uint8)) public reviewlike; // This is for storing if a particular person has liked a comment for not using that person's account address and review count and liked or not(0 for not liked and 1 for liked) mapping(address=>mapping(string=>uint8)) likerlimit; // An address can like a review only once. Storing if that address has already liked. mapping(address => uint256) YourCounter; // Total reviews mapping(uint256 =>string) searchreview; // Unique Id for each review. mapping(uint256=>address)uniquereview; // Unique Id's w.r.t addresses. address owner; uint256 countVar=0; constructor() public { owner = msg.sender; } // function to write the review function WriteReview(string tell) public returns (uint256,address,bool) { address reviewer=msg.sender; YourCounter[reviewer] +=1; reviews[reviewer][YourCounter[reviewer]] = tell; reviewlike[reviewer][YourCounter[reviewer]] =0; countVar++; searchreview[countVar] = tell; uniquereview[countVar] = msg.sender; return (YourCounter[reviewer],reviewer,true); } // function to delete the review function RemoveReview(uint256 RemoveId,address RemoveAddress) public returns(bool) { if(msg.sender==owner) { delete reviews[RemoveAddress][RemoveId]; countVar--; return true; YourCounter[RemoveAddress] -=1; } return false; } // function to see the review function SeeReview(address getting, uint256 __id) public view returns(string) { return(reviews[getting][__id]); } // function to get total reviews function YourCount(address _add) public view returns(uint256) { return (YourCounter[_add]); } // function to like the review function LikeReview(address likeadd,uint256 __id) public returns(string say){ if(likerlimit[msg.sender][reviews[likeadd][__id]] ==0) { reviewlike[likeadd][__id] +=1; likerlimit[msg.sender][reviews[likeadd][__id]] =1; say= "Either you like his review or You must be really liking that Person :p"; return say; } return "oops"; } // function to search for the review function SearchComment(string str) public view returns(uint256,address) { for(uint i=0;i<=countVar;i++) { if(keccak256(abi.encodePacked((searchreview[i]))) == keccak256(abi.encodePacked((str)))){ return (i,uniquereview[i]); } } } }
function to get total reviews
function YourCount(address _add) public view returns(uint256) { return (YourCounter[_add]); }
12,938,891
[ 1, 915, 358, 336, 2078, 283, 7061, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 377, 445, 20471, 1380, 12, 2867, 389, 1289, 13, 1071, 1476, 1135, 12, 11890, 5034, 13, 288, 203, 540, 327, 261, 15446, 4789, 63, 67, 1289, 19226, 203, 377, 289, 203, 1377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.12; import "./interface/StakingARMInterface.sol"; contract StakingARM is StakingARMInterface{ //Owner address address owner; //User variables mapping(address => uint256) stakingBalance; //User's staked ARM token mapping(address => uint256) rewardBalanceOf; //User's distributed reward from vault which 'NOT YET' claim mapping(address => bool) hasStaked; //this variable check if the user used to stake in the vault to prevent duplication of 'stakers[]'. mapping(address => bool) isStaking; //Staking status of individual address, FALSE if balance = 0 address[] stakers; //Address of stakers for rewarding reason //Vault variables manipulation uint256 accRewardPerShare; // spending reward RATE per share :: calculate from TotalRewardRemaining / TotalStakingToken / rewardSpendingDuration uint256 rewardSpendingDuration; // Duration in days that the reward will be distributed // RewardSpendingDuration is the CONSTANT that indicate the RATE of the current reward will be distributed if no-one is updating the vault // Everytime that users stake/unstake/claimReward, the spending rate (accRewardPerShare) will be re-calculated uint256 lastRewardTimestamp; //Index of current updated rewardblock (blocktime) //This code is modified from Masterchef contract // Whenever a user stake or unstake to the vault. // 1. The 'rewardBalance' (and `lastRewardTimestamp`) gets updated. // 2. User receives the 'rewardBalanceOf' sent to his/her address. (rewardBalanceOf then set to 0) // 3. User's `stakingBalance` gets updated. // 4. User's `rewardBalanceOf` gets updated. IERC20 public armToken; // ARM token OR LP-token to be staked IERC20 public rewardToken; // BUSD token //Set object of ARM to armToken and object of BUSD to rewardToken when the contract is deployed. constructor(IERC20 importARMToken, IERC20 importRewardToken){ armToken = importARMToken; // This can be LP token when deploying contract rewardToken = importRewardToken; owner = msg.sender; rewardSpendingDuration = 30 days; // set default is 30 days lastRewardTimestamp = block.timestamp; locked = false; } error TransferFail(); event Stake(address _staker, uint _amount); event Unstake(address _unstaker, uint _amount); event ClaimReward(address _claimer, uint _amount); event EmergencyWithdraw(address _withdrawer, uint _amount); event SetRewardSpendingDuration(uint OldDuration, uint NewDuration); event SetNewOwner(address OldOwner, address NewOwner); modifier onlyOwner { require(msg.sender == owner); _; } bool internal locked; modifier reentrancyGuard { require(!locked); locked = true; // lock the re-entrancy before contract execution _; locked = false; // unlock when finish } //-------------------------------------- //------Reading parameters function----- //-------------------------------------- //Get the ARM staking for each requested address function manualGetStakingBalance(address _staker) view public returns(uint256) { return stakingBalance[_staker]; } //Get the reward balance of each requested address (this included the pending update reward) function manualGetRewardBalance(address _staker) view public returns(uint256) { uint256 deltaTime = block.timestamp - lastRewardTimestamp; if(deltaTime > rewardSpendingDuration){ deltaTime = rewardSpendingDuration; } uint256 pendingReward = deltaTime * accRewardPerShare * stakingBalance[_staker]; uint256 totalReward = rewardBalanceOf[_staker] + pendingReward; return totalReward; } //Get the owner address function getOwner() view public returns(address){ return owner; } function getAccRewardPerShare() view public returns(uint) { return accRewardPerShare; } function getLastRewardTimestamp() view public returns(uint){ return lastRewardTimestamp; } function getStakingBalance(address user) view public returns(uint){ return stakingBalance[user]; } //Get the BUSD balance in vault function getVaultBalance() public view returns(uint256){ return rewardToken.balanceOf(address(this)); } //Get the ARM balance in vault function getTotalStakedARM() public view returns(uint256){ return armToken.balanceOf(address(this)); } //Get Total reward pending to be claim function getTotalRewardPending() internal view returns(uint256){ address[] memory varsStaker = stakers; //get stakers to local memory vars to minimalize gas spend in for loop uint256 numberUser = varsStaker.length; uint256 totalreward; for(uint i = 0; i< numberUser; i++){ totalreward += rewardBalanceOf[varsStaker[i]]; } return totalreward; } //Get remaining reward function getRewardRemaining() public view returns(uint256) { return (getVaultBalance() - getTotalRewardPending()); } //Reward spending duration return in blocktime function getRewardSpendingDuration() public view returns(uint256) { return rewardSpendingDuration; } function getRewardBalanceOf(address user) public view returns(uint256) { return rewardBalanceOf[user]; } //------------------------------------------------- //--------------Action function-------------------- //------------------------------------------------- function updateRewardBlock() internal{ //If the lastRewardTimestamp is updated. No need for update if(block.timestamp <= lastRewardTimestamp){ return; } uint256 totalStakedARM = getTotalStakedARM(); //The ARM balance in vault contract //Check if this is the first staker then start the block reward here if(totalStakedARM == 0){ lastRewardTimestamp = block.timestamp; return; } uint256 remainingReward = getRewardRemaining(); //Check if rewardPool is empty if(remainingReward == 0){ return; } //Check if the reward block not update for long time (more than the rewardSpendingDuration) //then deltaTime to be calculate should be equal to MAX (rewardSpendingDuration) uint256 deltaTime = block.timestamp - lastRewardTimestamp; if(deltaTime > rewardSpendingDuration){ deltaTime = rewardSpendingDuration; } uint i; uint gainReward; address[] memory varsStaker = stakers; // gas optimization for (i=0 ; i< varsStaker.length ; i++){ //gainReward is 1e18 :: e18*e18*uint / 1e18 gainReward = stakingBalance[varsStaker[i]] * accRewardPerShare * deltaTime / 1e18; rewardBalanceOf[varsStaker[i]] += gainReward; } lastRewardTimestamp = block.timestamp; } function manualUpdateRewardBlock() external reentrancyGuard{ updateRewardBlock(); } function stakeARM(uint _amount) external reentrancyGuard { //Check the amount and balance of staker require(_amount > 0, "Staking amount must greater than zero"); require(armToken.balanceOf(msg.sender)>=_amount, "Not enough ARM token to be deposited."); //1. update the reward vault to get lastRewardTimestamp //2. claim the pending reward //3. stake the ARM token //4. update accRewardPerShare = totalRemainingBalance / totalStakingBalance / rewardSpendingDuration updateRewardBlock(); bool success; if(rewardBalanceOf[msg.sender]>0){ uint256 toBePaid = rewardBalanceOf[msg.sender]; rewardBalanceOf[msg.sender]=0; success = rewardToken.transfer(msg.sender, toBePaid); if(!success){ revert TransferFail(); } emit ClaimReward(msg.sender, toBePaid); } //Transfer ARM to contract address then update balance success = armToken.transferFrom(msg.sender,address(this),_amount); if(!success){ revert TransferFail(); } stakingBalance[msg.sender] += _amount; //add staker address to the arrays for rewarding reasons if(!hasStaked[msg.sender]){ stakers.push(msg.sender); hasStaked[msg.sender] = true; } //Currently staking isStaking[msg.sender] = true; //Update accRewardPerShare uint256 totalRemainingBalance = getRewardRemaining(); uint256 totalStakingBalance = getTotalStakedARM(); // newAccRewardPerShare is 1e18 :: e18 * 1e18 / e18 / uint uint256 newAccRewardPerShare = (totalRemainingBalance * 1e18 / totalStakingBalance) / rewardSpendingDuration; accRewardPerShare = newAccRewardPerShare; emit Stake(msg.sender, _amount); } function manualClaimReward() external reentrancyGuard{ updateRewardBlock(); require(getRewardRemaining() >= rewardBalanceOf[msg.sender],"Not enough reward in pool."); if(rewardBalanceOf[msg.sender]>0){ uint256 toBePaid = rewardBalanceOf[msg.sender]; rewardBalanceOf[msg.sender]=0; //set balance to 0 before transfer to double prevent reentrancy guard bool success = rewardToken.transfer(msg.sender, toBePaid); if(!success){ revert TransferFail(); } emit ClaimReward(msg.sender, toBePaid); } } function unstakeARM(uint _amount) external reentrancyGuard{ //Check the amount and balancer of unstaker require(_amount > 0, "Unstaking amount must greater than zero"); require(stakingBalance[msg.sender] >= _amount, "Not enough ARM token to be withdrawed."); //1. update the reward vault to get lastRewardTimestamp //2. claim the pending reward //3. unstake the ARM token //4. update accRewardPerShare = totalRemainingBalance / totalStakingBalance / rewardSpendingDuration updateRewardBlock(); bool success; if(rewardBalanceOf[msg.sender]>0){ success = rewardToken.transfer(msg.sender, rewardBalanceOf[msg.sender]); if(!success){ revert TransferFail(); } emit ClaimReward(msg.sender, rewardBalanceOf[msg.sender]); rewardBalanceOf[msg.sender]=0; } //Transfer ARM to unstaker success = armToken.transfer(msg.sender,_amount); //calculate balance after transfer stakingBalance[msg.sender] -= _amount; if(stakingBalance[msg.sender]==0){ isStaking[msg.sender] = false; } //Update accRewardPerShare uint256 totalRemainingBalance = getRewardRemaining(); uint256 totalStakingBalance = getTotalStakedARM(); //if totalStakiingBalance = 0 --> no ARM in vault = no reward then accRewardPerShare = 0 if(totalStakingBalance==0) { accRewardPerShare = 0; } else { // accRewardPerShare is 1e18 :: e18 * 1e18 / e18 / uint accRewardPerShare = (totalRemainingBalance * 1e18 /totalStakingBalance) / rewardSpendingDuration; } emit Unstake(msg.sender,_amount); } //Set reward duration only Owner can access function _setRewardDurationSpending (uint hour) external onlyOwner { updateRewardBlock(); //update distribute reward before uint OldDuration = rewardSpendingDuration; uint NewDuration = hour * 60 * 60; // Input in 'hour', Stored in Seconds rewardSpendingDuration = NewDuration; accRewardPerShare = (getRewardRemaining() * 1e18 / getTotalStakedARM()) / NewDuration; // update the distribution RATE emit SetRewardSpendingDuration(OldDuration, NewDuration); } //Set new admin function _transferOwnership (address newOwner) external onlyOwner { address oldOwner = owner; owner = newOwner; emit SetNewOwner(oldOwner, newOwner); } //Withdraw ARM token without caring reward function emergencyWithdraw() external reentrancyGuard { uint withdrawBl = stakingBalance[msg.sender]; isStaking[msg.sender] = false; rewardBalanceOf[msg.sender] = 0; stakingBalance[msg.sender] = 0; armToken.transfer(msg.sender, withdrawBl); emit EmergencyWithdraw(msg.sender, withdrawBl); } }
Withdraw ARM token without caring reward
function emergencyWithdraw() external reentrancyGuard { uint withdrawBl = stakingBalance[msg.sender]; isStaking[msg.sender] = false; rewardBalanceOf[msg.sender] = 0; stakingBalance[msg.sender] = 0; armToken.transfer(msg.sender, withdrawBl); emit EmergencyWithdraw(msg.sender, withdrawBl); }
1,086,216
[ 1, 1190, 9446, 6052, 49, 1147, 2887, 5926, 310, 19890, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 801, 24530, 1190, 9446, 1435, 3903, 283, 8230, 12514, 16709, 288, 203, 3639, 2254, 598, 9446, 4802, 273, 384, 6159, 13937, 63, 3576, 18, 15330, 15533, 203, 3639, 353, 510, 6159, 63, 3576, 18, 15330, 65, 273, 629, 31, 203, 3639, 19890, 13937, 951, 63, 3576, 18, 15330, 65, 273, 374, 31, 203, 3639, 384, 6159, 13937, 63, 3576, 18, 15330, 65, 273, 374, 31, 203, 3639, 23563, 1345, 18, 13866, 12, 3576, 18, 15330, 16, 598, 9446, 4802, 1769, 203, 3639, 3626, 512, 6592, 75, 2075, 1190, 9446, 12, 3576, 18, 15330, 16, 598, 9446, 4802, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0x307a878307Eb5dc973c6081a403F96B1FB1b0681/sources/contracts/CrowdFunding.sol
numRequests starts from zero
function createRequest(string calldata _description, address payable _recipient, uint _value) public onlyAdmin { Request storage newRequest = requests[numRequests]; numRequests++; newRequest.description = _description; newRequest.recipient = _recipient; newRequest.value = _value; newRequest.completed = false; newRequest.noOfVoters = 0; emit CreateRequestEvent(_description, _recipient, _value); }
12,401,467
[ 1, 2107, 6421, 2542, 628, 3634, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 15798, 12, 1080, 745, 892, 389, 3384, 16, 1758, 8843, 429, 389, 20367, 16, 2254, 389, 1132, 13, 1071, 1338, 4446, 288, 203, 3639, 1567, 2502, 7428, 273, 3285, 63, 2107, 6421, 15533, 203, 3639, 818, 6421, 9904, 31, 203, 540, 203, 3639, 7428, 18, 3384, 273, 389, 3384, 31, 203, 3639, 7428, 18, 20367, 273, 389, 20367, 31, 203, 3639, 7428, 18, 1132, 273, 389, 1132, 31, 203, 3639, 7428, 18, 13615, 273, 629, 31, 203, 3639, 7428, 18, 2135, 951, 58, 352, 414, 273, 374, 31, 203, 540, 203, 3639, 3626, 1788, 691, 1133, 24899, 3384, 16, 389, 20367, 16, 389, 1132, 1769, 203, 565, 289, 203, 377, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.11; // <ORACLIZE_API> /* Copyright (c) 2015-2016 Oraclize SRL Copyright (c) 2016 Oraclize LTD 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 SOFTWARE. */ pragma solidity ^0.4.0;//please import oraclizeAPI_pre0.4.sol when solidity < 0.4.0 contract OraclizeI { address public cbAddress; function query(uint _timestamp, string _datasource, string _arg) payable returns (bytes32 _id); function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) payable returns (bytes32 _id); function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) payable returns (bytes32 _id); function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) payable returns (bytes32 _id); function queryN(uint _timestamp, string _datasource, bytes _argN) payable returns (bytes32 _id); function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) payable returns (bytes32 _id); function getPrice(string _datasource) returns (uint _dsprice); function getPrice(string _datasource, uint gaslimit) returns (uint _dsprice); function useCoupon(string _coupon); function setProofType(byte _proofType); function setConfig(bytes32 _config); function setCustomGasPrice(uint _gasPrice); function randomDS_getSessionPubKeyHash() returns(bytes32); } contract OraclizeAddrResolverI { function getAddress() returns (address _addr); } contract usingOraclize { uint constant day = 60*60*24; uint constant week = 60*60*24*7; uint constant month = 60*60*24*30; byte constant proofType_NONE = 0x00; byte constant proofType_TLSNotary = 0x10; byte constant proofType_Android = 0x20; byte constant proofType_Ledger = 0x30; byte constant proofType_Native = 0xF0; byte constant proofStorage_IPFS = 0x01; uint8 constant networkID_auto = 0; uint8 constant networkID_mainnet = 1; uint8 constant networkID_testnet = 2; uint8 constant networkID_morden = 2; uint8 constant networkID_consensys = 161; OraclizeAddrResolverI OAR; OraclizeI oraclize; modifier oraclizeAPI { if((address(OAR)==0)||(getCodeSize(address(OAR))==0)) oraclize_setNetwork(networkID_auto); if(address(oraclize) != OAR.getAddress()) oraclize = OraclizeI(OAR.getAddress()); _; } modifier coupon(string code){ oraclize = OraclizeI(OAR.getAddress()); oraclize.useCoupon(code); _; } function oraclize_setNetwork(uint8 networkID) internal returns(bool){ if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ //mainnet OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed); oraclize_setNetworkName("eth_mainnet"); return true; } if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1); oraclize_setNetworkName("eth_ropsten3"); return true; } if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e); oraclize_setNetworkName("eth_kovan"); return true; } if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ //rinkeby testnet OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48); oraclize_setNetworkName("eth_rinkeby"); return true; } if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ //ethereum-bridge OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475); return true; } if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ //ether.camp ide OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF); return true; } if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA); return true; } return false; } function __callback(bytes32 myid, string result) { __callback(myid, result, new bytes(0)); } function __callback(bytes32 myid, string result, bytes proof) { } function oraclize_useCoupon(string code) oraclizeAPI internal { oraclize.useCoupon(code); } function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource); } function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource, gaslimit); } function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(0, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(timestamp, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(0, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_cbAddress() oraclizeAPI internal returns (address){ return oraclize.cbAddress(); } function oraclize_setProof(byte proofP) oraclizeAPI internal { return oraclize.setProofType(proofP); } function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal { return oraclize.setCustomGasPrice(gasPrice); } function oraclize_setConfig(bytes32 config) oraclizeAPI internal { return oraclize.setConfig(config); } function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){ return oraclize.randomDS_getSessionPubKeyHash(); } function getCodeSize(address _addr) constant internal returns(uint _size) { assembly { _size := extcodesize(_addr) } } function parseAddr(string _a) internal returns (address){ bytes memory tmp = bytes(_a); uint160 iaddr = 0; uint160 b1; uint160 b2; for (uint i=2; i<2+2*20; i+=2){ iaddr *= 256; b1 = uint160(tmp[i]); b2 = uint160(tmp[i+1]); if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87; else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55; else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48; if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87; else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55; else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48; iaddr += (b1*16+b2); } return address(iaddr); } function strCompare(string _a, string _b) internal returns (int) { bytes memory a = bytes(_a); bytes memory b = bytes(_b); uint minLength = a.length; if (b.length < minLength) minLength = b.length; for (uint i = 0; i < minLength; i ++) if (a[i] < b[i]) return -1; else if (a[i] > b[i]) return 1; if (a.length < b.length) return -1; else if (a.length > b.length) return 1; else return 0; } function indexOf(string _haystack, string _needle) internal returns (int) { bytes memory h = bytes(_haystack); bytes memory n = bytes(_needle); if(h.length < 1 || n.length < 1 || (n.length > h.length)) return -1; else if(h.length > (2**128 -1)) return -1; else { uint subindex = 0; for (uint i = 0; i < h.length; i ++) { if (h[i] == n[0]) { subindex = 1; while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) { subindex++; } if(subindex == n.length) return int(i); } } return -1; } } function strConcat(string _a, string _b, string _c, string _d, string _e) internal returns (string) { 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); uint k = 0; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } function strConcat(string _a, string _b, string _c, string _d) internal returns (string) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string _a, string _b, string _c) internal returns (string) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string _a, string _b) internal returns (string) { return strConcat(_a, _b, "", "", ""); } // parseInt function parseInt(string _a) internal returns (uint) { return parseInt(_a, 0); } // parseInt(parseFloat*10^_b) function parseInt(string _a, uint _b) internal returns (uint) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i=0; i<bresult.length; i++){ if ((bresult[i] >= 48)&&(bresult[i] <= 57)){ if (decimals){ if (_b == 0) break; else _b--; } mint *= 10; mint += uint(bresult[i]) - 48; } else if (bresult[i] == 46) decimals = true; } if (_b > 0) mint *= 10**_b; return mint; } function uint2str(uint i) internal returns (string){ if (i == 0) return "0"; uint j = i; uint len; while (j != 0){ len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (i != 0){ bstr[k--] = byte(48 + i % 10); i /= 10; } return string(bstr); } function stra2cbor(string[] arr) internal returns (bytes) { uint arrlen = arr.length; // get correct cbor output length uint outputlen = 0; bytes[] memory elemArray = new bytes[](arrlen); for (uint i = 0; i < arrlen; i++) { elemArray[i] = (bytes(arr[i])); outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types } uint ctr = 0; uint cborlen = arrlen + 0x80; outputlen += byte(cborlen).length; bytes memory res = new bytes(outputlen); while (byte(cborlen).length > ctr) { res[ctr] = byte(cborlen)[ctr]; ctr++; } for (i = 0; i < arrlen; i++) { res[ctr] = 0x5F; ctr++; for (uint x = 0; x < elemArray[i].length; x++) { // if there's a bug with larger strings, this may be the culprit if (x % 23 == 0) { uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x; elemcborlen += 0x40; uint lctr = ctr; while (byte(elemcborlen).length > ctr - lctr) { res[ctr] = byte(elemcborlen)[ctr - lctr]; ctr++; } } res[ctr] = elemArray[i][x]; ctr++; } res[ctr] = 0xFF; ctr++; } return res; } function ba2cbor(bytes[] arr) internal returns (bytes) { uint arrlen = arr.length; // get correct cbor output length uint outputlen = 0; bytes[] memory elemArray = new bytes[](arrlen); for (uint i = 0; i < arrlen; i++) { elemArray[i] = (bytes(arr[i])); outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types } uint ctr = 0; uint cborlen = arrlen + 0x80; outputlen += byte(cborlen).length; bytes memory res = new bytes(outputlen); while (byte(cborlen).length > ctr) { res[ctr] = byte(cborlen)[ctr]; ctr++; } for (i = 0; i < arrlen; i++) { res[ctr] = 0x5F; ctr++; for (uint x = 0; x < elemArray[i].length; x++) { // if there's a bug with larger strings, this may be the culprit if (x % 23 == 0) { uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x; elemcborlen += 0x40; uint lctr = ctr; while (byte(elemcborlen).length > ctr - lctr) { res[ctr] = byte(elemcborlen)[ctr - lctr]; ctr++; } } res[ctr] = elemArray[i][x]; ctr++; } res[ctr] = 0xFF; ctr++; } return res; } string oraclize_network_name; function oraclize_setNetworkName(string _network_name) internal { oraclize_network_name = _network_name; } function oraclize_getNetworkName() internal returns (string) { return oraclize_network_name; } function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){ if ((_nbytes == 0)||(_nbytes > 32)) throw; bytes memory nbytes = new bytes(1); nbytes[0] = byte(_nbytes); bytes memory unonce = new bytes(32); bytes memory sessionKeyHash = new bytes(32); bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash(); assembly { mstore(unonce, 0x20) mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp))) mstore(sessionKeyHash, 0x20) mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32) } bytes[3] memory args = [unonce, nbytes, sessionKeyHash]; bytes32 queryId = oraclize_query(_delay, "random", args, _customGasLimit); oraclize_randomDS_setCommitment(queryId, sha3(bytes8(_delay), args[1], sha256(args[0]), args[2])); return queryId; } function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal { oraclize_randomDS_args[queryId] = commitment; } mapping(bytes32=>bytes32) oraclize_randomDS_args; mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified; function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){ bool sigok; address signer; bytes32 sigr; bytes32 sigs; bytes memory sigr_ = new bytes(32); uint offset = 4+(uint(dersig[3]) - 0x20); sigr_ = copyBytes(dersig, offset, 32, sigr_, 0); bytes memory sigs_ = new bytes(32); offset += 32 + 2; sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0); assembly { sigr := mload(add(sigr_, 32)) sigs := mload(add(sigs_, 32)) } (sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs); if (address(sha3(pubkey)) == signer) return true; else { (sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs); return (address(sha3(pubkey)) == signer); } } function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) { bool sigok; // Step 6: verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH) bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2); copyBytes(proof, sig2offset, sig2.length, sig2, 0); bytes memory appkey1_pubkey = new bytes(64); copyBytes(proof, 3+1, 64, appkey1_pubkey, 0); bytes memory tosign2 = new bytes(1+65+32); tosign2[0] = 1; //role copyBytes(proof, sig2offset-65, 65, tosign2, 1); bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c"; copyBytes(CODEHASH, 0, 32, tosign2, 1+65); sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey); if (sigok == false) return false; // Step 7: verify the APPKEY1 provenance (must be signed by Ledger) bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4"; bytes memory tosign3 = new bytes(1+65); tosign3[0] = 0xFE; copyBytes(proof, 3, 65, tosign3, 1); bytes memory sig3 = new bytes(uint(proof[3+65+1])+2); copyBytes(proof, 3+65, sig3.length, sig3, 0); sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY); return sigok; } modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) { // Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1) if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) throw; bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); if (proofVerified == false) throw; _; } function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){ // Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1) if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1; bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); if (proofVerified == false) return 2; return 0; } function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal returns (bool){ bool match_ = true; for (uint256 i=0; i< n_random_bytes; i++) { if (content[i] != prefix[i]) match_ = false; } return match_; } function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){ // Step 2: the unique keyhash has to match with the sha256 of (context name + queryId) uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32; bytes memory keyhash = new bytes(32); copyBytes(proof, ledgerProofLength, 32, keyhash, 0); if (!(sha3(keyhash) == sha3(sha256(context_name, queryId)))) return false; bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2); copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0); // Step 3: we assume sig1 is valid (it will be verified during step 5) and we verify if 'result' is the prefix of sha256(sig1) if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false; // Step 4: commitment match verification, sha3(delay, nbytes, unonce, sessionKeyHash) == commitment in storage. // This is to verify that the computed args match with the ones specified in the query. bytes memory commitmentSlice1 = new bytes(8+1+32); copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0); bytes memory sessionPubkey = new bytes(64); uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65; copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0); bytes32 sessionPubkeyHash = sha256(sessionPubkey); if (oraclize_randomDS_args[queryId] == sha3(commitmentSlice1, sessionPubkeyHash)){ //unonce, nbytes and sessionKeyHash match delete oraclize_randomDS_args[queryId]; } else return false; // Step 5: validity verification for sig1 (keyhash and args signed with the sessionKey) bytes memory tosign1 = new bytes(32+8+1+32); copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0); if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false; // verify if sessionPubkeyHash was verified already, if not.. let's do it! if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){ oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset); } return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash]; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal returns (bytes) { uint minLength = length + toOffset; if (to.length < minLength) { // Buffer too small throw; // Should be a better way? } // NOTE: the offset 32 is added to skip the `size` field of both bytes variables uint i = 32 + fromOffset; uint j = 32 + toOffset; while (i < (32 + fromOffset + length)) { assembly { let tmp := mload(add(from, i)) mstore(add(to, j), tmp) } i += 32; j += 32; } return to; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license // Duplicate Solidity's ecrecover, but catching the CALL return value function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) { // We do our own memory management here. Solidity uses memory offset // 0x40 to store the current end of memory. We write past it (as // writes are memory extensions), but don't update the offset so // Solidity will reuse it. The memory used here is only needed for // this context. // FIXME: inline assembly can't access return values bool ret; address addr; assembly { let size := mload(0x40) mstore(size, hash) mstore(add(size, 32), v) mstore(add(size, 64), r) mstore(add(size, 96), s) // NOTE: we can reuse the request memory because we deal with // the return code ret := call(3000, 1, 0, size, 128, size, 32) addr := mload(size) } return (ret, addr); } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) { bytes32 r; bytes32 s; uint8 v; if (sig.length != 65) return (false, 0); // The signature format is a compact form of: // {bytes32 r}{bytes32 s}{uint8 v} // Compact means, uint8 is not padded to 32 bytes. assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) // Here we are loading the last 32 bytes. We exploit the fact that // 'mload' will pad with zeroes if we overread. // There is no 'mload8' to do this, but that would be nicer. v := byte(0, mload(add(sig, 96))) // Alternative solution: // 'byte' is not working due to the Solidity parser, so lets // use the second best option, 'and' // v := and(mload(add(sig, 65)), 255) } // albeit non-transactional signatures are not specified by the YP, one would expect it // to match the YP range of [27, 28] // // geth uses [0, 1] and some clients have followed. This might change, see: // https://github.com/ethereum/go-ethereum/issues/2053 if (v < 27) v += 27; if (v != 27 && v != 28) return (false, 0); return safer_ecrecover(hash, v, r, s); } } // </ORACLIZE_API> contract LiverpoolvsRoma is usingOraclize { /* Declaration */ address public OWNERS = 0xC3eD2d481B9d75835EC04174b019A7eAF2Faf78A; uint public constant COMMISSION = 0; // Commission for the owner uint public constant MIN_BET = 0.01 ether; uint public EXPECTED_START = 1524595500; // When the bet's event is expected to start uint public EXPECTED_END = 1524609900; // When the bet's event is expected to end uint public constant BETTING_OPENS = 1523658667; uint public BETTING_CLOSES = EXPECTED_START - 60; // Betting closes a minute before the bet event starts uint public constant PING_ORACLE_INTERVAL = 60 * 60 * 24; // Ping oracle every 24 hours until completion (or cancelation) uint public ORACLIZE_GAS = 200000; uint public CANCELATION_DATE = EXPECTED_END + 60 * 60 * 24; // Cancelation date is 24 hours after the expected end uint public RETURN_DATE = EXPECTED_END + 60 * 60 * 24 * 30; // Any leftover money is returned to owners 1 month after bet ends bool public completed; bool public canceled; bool public ownersPayed; uint public ownerPayout; bool public returnedToOwners; uint public winnerDeterminedDate; uint public numCollected = 0; bytes32 public nextScheduledQuery; uint public oraclizeFees; uint public collectionFees; struct Better { uint betAmount; uint betOption; bool withdrawn; } mapping(address => Better) betterInfo; address[] public betters; uint[2] public totalAmountsBet; uint[2] public numberOfBets; uint public totalBetAmount; uint public winningOption = 2; /* Events */ event BetMade(); /* Modifiers */ // Modifier to only allow the // determination of the winner modifier canDetermineWinner() { require (winningOption == 2 && !completed && !canceled && now > BETTING_CLOSES && now >= EXPECTED_END); _; } // Modifier to only allow emptying // the remaining value of the contract // to owners. modifier canEmptyRemainings() { require(canceled || completed); uint numRequiredToCollect = canceled ? (numberOfBets[0] + numberOfBets[1]) : numberOfBets[winningOption]; require ((now >= RETURN_DATE && !canceled) || (numCollected == numRequiredToCollect)); _; } // Modifier to only allow the collection // of bet payouts when winner is determined, // (or withdrawals if the bet is canceled) modifier collectionsEnabled() { require (canceled || (winningOption != 2 && completed && now > BETTING_CLOSES)); _; } // Modifier to only allow the execution of // owner payout when winner is determined modifier canPayOwners() { require (!canceled && winningOption != 2 && completed && !ownersPayed && now > BETTING_CLOSES); _; } // Modifier to only allow the execution of // certain functions when betting is closed modifier bettingIsClosed() { require (now >= BETTING_CLOSES); _; } // Modifier to only allow the execution of // certain functions restricted to the owners modifier onlyOwnerLevel() { require( OWNERS == msg.sender ); _; } /* Functions */ // Constructor function LiverpoolvsRoma() public payable { oraclize_setCustomGasPrice(1000000000); callOracle(EXPECTED_END, ORACLIZE_GAS); // Kickoff Oracle checking for outcome } function changeGasLimitAndPrice(uint gas, uint price) public onlyOwnerLevel { ORACLIZE_GAS = gas; oraclize_setCustomGasPrice(price); } // Change bet expected times function setExpectedTimes(uint _EXPECTED_START, uint _EXPECTED_END) public onlyOwnerLevel { setExpectedStart(_EXPECTED_START); setExpectedEnd(_EXPECTED_END); } // Change bet expected start time function setExpectedStart(uint _EXPECTED_START) public onlyOwnerLevel { EXPECTED_START = _EXPECTED_START; BETTING_CLOSES = EXPECTED_START - 60; } // Change bet expected end time function setExpectedEnd(uint _EXPECTED_END) payable public onlyOwnerLevel { require(_EXPECTED_END > EXPECTED_START); EXPECTED_END = _EXPECTED_END; CANCELATION_DATE = EXPECTED_END + 60 * 60 * 24; RETURN_DATE = EXPECTED_END + 60 * 60 * 24 * 30; callOracle(EXPECTED_END, ORACLIZE_GAS); // Kickoff Oracle checking for winner } function callOracle(uint timeOrDelay, uint gas) private { require(canceled != true && completed != true); // Make a call to the oracle — // usually a script hosted on IPFS that // Oraclize deploys, after a given delay. We // leave nested query as default to maximize // optionality for queries. // To readers of the code (aka prospective betters) // if this is a computation query, you can view the // script we use to compute the winner, as it is hosted // on IPFS. The first argument in the computation query // is the IPFS hash (script would be located at // ipfs.io/ipfs/<HASH>). The file hosted at this hash // is actually a zipped folder that contains a Dockerfile and // the script. So, if you download the file at the hash provided, // ensure to convert it to a .zip, unzip it, and read the code. // Oraclize uses the Dockerfile to deploy this script. // Look over the Oraclize documentation to verify this // for yourself. nextScheduledQuery = makeOraclizeQuery(timeOrDelay, "nested", "[computation] ['QmZZ97jafZTCrw57jGDSeBBT9oAshyzniMvtfF8JKaZ991', '166840', '166837', '${[decrypt] BHhNyr5MXT/eXenbHi325s4azRWtxWuflqC/0Z4lXASt+Jvc/ExvytWG1NsCnSCeYwj792KIiLI5IadXl135DgdTCJMn5d2iHFPZjGoVtSoqXIjgUnJSzWWMabdNnzHtNOLlyxtPcPqyqrKWBUuya+I=}']", gas); } function makeOraclizeQuery(uint timeOrDelay, string datasource, string query, uint gas) private returns(bytes32) { oraclizeFees += oraclize_getPrice(datasource, gas); return oraclize_query(timeOrDelay, datasource, query, gas); } // Determine the outcome manually, // immediately function determineWinner(uint gas, uint gasPrice) payable public onlyOwnerLevel canDetermineWinner { ORACLIZE_GAS = gas; oraclize_setCustomGasPrice(gasPrice); callOracle(0, ORACLIZE_GAS); } // Callback from Oraclize function __callback(bytes32 queryId, string result, bytes proof) public canDetermineWinner { require(msg.sender == oraclize_cbAddress()); // The Oracle must always return // an integer (either 0 or 1, or if not then) // it should be 2 if (keccak256(result) != keccak256("0") && keccak256(result) != keccak256("1")) { // Reschedule winner determination, // unless we're past the point of // cancelation. If nextScheduledQuery is // not the current query, it means that // there's a scheduled future query, so // we can wait for that instead of scheduling // another one now (otherwise this would cause // dupe queries). if (now >= CANCELATION_DATE) { cancel(); } else if (nextScheduledQuery == queryId) { callOracle(PING_ORACLE_INTERVAL, ORACLIZE_GAS); } } else { setWinner(parseInt(result)); } } function setWinner(uint winner) private { completed = true; canceled = false; winningOption = winner; winnerDeterminedDate = now; payOwners(); } // Returns the total amounts betted // for the sender function getUserBet(address addr) public constant returns(uint[]) { uint[] memory bets = new uint[](2); bets[betterInfo[addr].betOption] = betterInfo[addr].betAmount; return bets; } // Returns whether a user has withdrawn // money or not. function userHasWithdrawn(address addr) public constant returns(bool) { return betterInfo[addr].withdrawn; } // Returns whether winning collections are // now available, or not. function collectionsAvailable() public constant returns(bool) { return (completed && winningOption != 2 && now >= (winnerDeterminedDate + 600)); // At least 10 mins has to pass between determining winner and enabling payout, so that we have time to revert the bet in case we detect suspicious betting activty (eg. a hacker bets a lot to steal the entire losing pot, and hacks the oracle) } // Returns true if we can bet (in betting window) function canBet() public constant returns(bool) { return (now >= BETTING_OPENS && now < BETTING_CLOSES && !canceled && !completed); } // Function for user to bet on launch // outcome function bet(uint option) public payable { require(canBet() == true); require(msg.value >= MIN_BET); require(betterInfo[msg.sender].betAmount == 0 || betterInfo[msg.sender].betOption == option); // Add better to better list if they // aren't already in it if (betterInfo[msg.sender].betAmount == 0) { betterInfo[msg.sender].betOption = option; numberOfBets[option]++; betters.push(msg.sender); } // Perform bet betterInfo[msg.sender].betAmount += msg.value; totalBetAmount += msg.value; totalAmountsBet[option] += msg.value; BetMade(); // Trigger event } // Empty remainder of the value in the // contract to the owners. function emptyRemainingsToOwners() private canEmptyRemainings { OWNERS.transfer(this.balance); returnedToOwners = true; } function returnToOwners() public onlyOwnerLevel canEmptyRemainings { emptyRemainingsToOwners(); } // Performs payout to owners function payOwners() private canPayOwners { if (COMMISSION == 0) { ownersPayed = true; ownerPayout = 0; if (numberOfBets[winningOption] > 0) { collectionFees = ((oraclizeFees != 0) ? (oraclizeFees / numberOfBets[winningOption] + 1) : 0); // We add 1 wei to act as a ceil for the integer div -- important because the contract cannot afford to lose that spare change, as it will gaurantee that the final payout collection will fail. } return; } // Calculate total pool of ETH // betted for the two outcomes. uint losingChunk = totalAmountsBet[1 - winningOption]; ownerPayout = (losingChunk - oraclizeFees) / COMMISSION; // Payout to the owner; commission of losing pot, minus the same % of the fees if (numberOfBets[winningOption] > 0) { collectionFees = ((oraclizeFees != 0) ? ((oraclizeFees - oraclizeFees / COMMISSION) / numberOfBets[winningOption] + 1) : 0); // The fees to be distributed to the collectors, after owner payout. See reasoning above for adding the 1 wei. } // Equal weight payout to the owners OWNERS.transfer(ownerPayout); ownersPayed = true; } function cancelBet() payable public onlyOwnerLevel { cancel(); } // Cancel bet and relase all the bets back to // the betters if, for any reason, payouts cannot be // completed. (For example Oracle fails.) Triggered by owners. function cancel() private { canceled = true; completed = false; } // Fallback function in case someone sends // ether to the contract so it doesn't get // lost. Could be used by us owners as buffer // value in case payouts fail. function() payable public { } // Function that lets betters collect their // money, either if the bet was canceled, // or if they won. function collect() public collectionsEnabled { address better = msg.sender; require(betterInfo[better].betAmount > 0); require(!betterInfo[better].withdrawn); require(canceled != completed); require(canceled || (completed && betterInfo[better].betOption == winningOption)); require(now >= (winnerDeterminedDate + 600)); uint payout = 0; if (!canceled) { // On top of their original bet, // add in profit, which is a weighted // proportion of the losing pot, relative // to their contribution to the winning pot, // minus owner commission. uint losingChunk = totalAmountsBet[1 - winningOption]; payout = betterInfo[better].betAmount + (betterInfo[better].betAmount * (losingChunk - ownerPayout) / totalAmountsBet[winningOption]) - collectionFees; } else { payout = betterInfo[better].betAmount; } if (payout > 0) { better.transfer(payout); betterInfo[better].withdrawn = true; numCollected++; } } }
When the bet's event is expected to start
uint public EXPECTED_START = 1524595500;
11,656,308
[ 1, 9434, 326, 2701, 1807, 871, 353, 2665, 358, 787, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 2254, 1071, 5675, 23615, 67, 7570, 273, 4711, 3247, 6162, 2539, 713, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.5.16; pragma experimental ABIEncoderV2; /* Error Codes 200 - ok 100 - fail 107 - Unauthorized Access */ contract Election { /*--------------------------------------------------------------------------- Super Admin Module -----------------------------------------------------------------------------*/ uint private numberOfSuperAdmins = 0; bool private isDefaultAdminAdded = false; struct superAdmin { string name; string emailId; string username; bytes32 encUsername; bytes32 password; bool occupied; bool canDelete; } struct superAdminDetails { string name; string emailId; string username; string encUsername; string password; } //store super admin details based on the hash value of encryptedUserName hash value mapping(bytes32 => superAdmin) private superAdminHashmap; mapping (uint=> bytes32) private superAdminsAccountDetails; mapping(bytes32 => string) private superAdminLoginLog; //get all details of Super admins /*function getAllSuperAdminDetails(string memory encUsername) public view returns(superAdmin[] memory) { if (isSuperAdminUsernameTaken(encUsername)) { superAdmin[] memory allDetails = new superAdmin[](numberOfSuperAdmins); for (uint i = 0; i < numberOfSuperAdmins; i++) { allDetails[i] = superAdminHashmap[superAdminsAccountDetails[i]]; } return allDetails; } else { superAdmin[] memory allDetails = new superAdmin[](0); return allDetails; } }*/ //add super admin credentials into table by hashing proper credentials function addSuperAdmin(superAdminDetails memory adminDetails, string memory adminHashCode) private{ if (isSuperAdminUsernameTaken(adminHashCode)) { bytes32 usernameHash = getStringHashedToBytes32(adminDetails.encUsername); bytes32 passwordHash = getStringHashedToBytes32(adminDetails.password); superAdmin memory admin = superAdmin(adminDetails.name, adminDetails.emailId, adminDetails.username, usernameHash, passwordHash, true, true); superAdminHashmap[usernameHash] = admin; superAdminsAccountDetails[numberOfSuperAdmins] = usernameHash; numberOfSuperAdmins += 1; } } /*function storeSuperAdminAtPosition(superAdmin memory adminData, string memory encUsername) private { bytes32 usernameHash = getStringHashedToBytes32(encUsername); superAdminHashmap[usernameHash] = adminData; }*/ //checks the hashmap, wheather admin details is present already function isSuperAdminPresent(superAdmin memory adminDetails, string memory encUsername) private view returns(bool) { bytes32 usernameHash = getStringHashedToBytes32(encUsername); superAdmin storage admin = superAdminHashmap[usernameHash]; if (isEqual(admin.name, adminDetails.name) && isEqual(admin.emailId, adminDetails.emailId) && isEqual(admin.username, adminDetails.username) && isEqualByBytes32(admin.encUsername, adminDetails.encUsername)) { return true; } return false; } //checks if the admin username is already taken function isSuperAdminUsernameTaken(string memory encUsername) public view returns(bool) { bytes32 usernameHash = getStringHashedToBytes32(encUsername); superAdmin storage admin = superAdminHashmap[usernameHash]; if (!admin.occupied) { return false; } return true; } //will add the details into hashmap once all the api calls are satisfied function finallyAddSuperAdmin(string memory name, string memory emailId, string memory username, string memory encUsername, string memory password, string memory adminUsername) public { superAdminDetails memory adminDetails = superAdminDetails(name, emailId, username, encUsername, password); if (isSuperAdminUsernameTaken(adminUsername)) { addSuperAdmin(adminDetails, adminUsername); } } //returns data by checking the hashmap if the admin is created function isSuperAdminAdded(string memory name, string memory emailId, string memory username, string memory encUsername, string memory password) public view returns(int) { bytes32 usernameHash = getStringHashedToBytes32(encUsername); bytes32 passwordHash = getStringHashedToBytes32(password); superAdmin memory adminDetails = superAdmin(name, emailId, username, usernameHash, passwordHash, true, true); bool isPresent = isSuperAdminPresent(adminDetails, encUsername); if (isPresent) { return 200; } return 100; } function authSuperAdminEnc(string memory username) public view returns(bool) { bytes32 usernameHash = getStringHashedToBytes32(username); superAdmin memory authAdmin = superAdminHashmap[usernameHash]; if (authAdmin.encUsername == usernameHash) { return true; } return false; } function authSuperAdmin(string memory username, string memory encUsername, string memory password) public view returns(bool) { bytes32 usernameHash = getStringHashedToBytes32(encUsername); bytes32 passwordHash = getStringHashedToBytes32(password); superAdmin memory authAdmin = superAdminHashmap[usernameHash]; bytes32 baseUsernameHash = getStringHashedToBytes32(authAdmin.username); bytes32 recievedUsernameHash = getStringHashedToBytes32(username); if (baseUsernameHash == recievedUsernameHash && authAdmin.encUsername == usernameHash && authAdmin.password == passwordHash) { return true; } return false; } //edit super admin details as a whole, which includes Name, Email id, Password /*function editSuperAdminAllDetails(string memory name, string memory emailId, string memory encUsername, string memory password) public { bytes32 usernameHash = getStringHashedToBytes32(encUsername); bytes32 passwordHash = getStringHashedToBytes32(password); superAdmin memory sAdmin = superAdminHashmap[usernameHash]; sAdmin.name = name; sAdmin.emailId = emailId; sAdmin.password = passwordHash; superAdminHashmap[usernameHash] = sAdmin; } //edit only Super Admin name function editSuperAdminName(string memory name, string memory encUsername) public { bytes32 usernameHash = getStringHashedToBytes32(encUsername); superAdmin memory sAdmin = superAdminHashmap[usernameHash]; sAdmin.name = name; storeSuperAdminAtPosition(sAdmin, encUsername); } //edit only Super Admin Email Id function editSuperAdminEmailId(string memory emailId, string memory encUsername) public { bytes32 usernameHash = getStringHashedToBytes32(encUsername); superAdmin memory sAdmin = superAdminHashmap[usernameHash]; sAdmin.emailId = emailId; storeSuperAdminAtPosition(sAdmin, encUsername); } //edit only Super Admin Password function editSuperAdminPassword(string memory password, string memory encUsername) public { bytes32 usernameHash = getStringHashedToBytes32(encUsername); bytes32 passwordHash = getStringHashedToBytes32(password); superAdmin memory sAdmin = superAdminHashmap[usernameHash]; sAdmin.password = passwordHash; storeSuperAdminAtPosition(sAdmin, encUsername); } //function to get the admin details function getSuperAdminDetails(string memory encUsername) public view returns(superAdmin memory) { bytes32 usernameHash = getStringHashedToBytes32(encUsername); return superAdminHashmap[usernameHash]; }*/ //function to create Default Super Admin function defaultSuperAdmin(string memory name, string memory emailId, string memory username, string memory encUsername, string memory password) public { if (!isDefaultAdminAdded) { bytes32 usernameHash = getStringHashedToBytes32(encUsername); bytes32 passwordHash = getStringHashedToBytes32(password); superAdmin memory admin = superAdmin(name, emailId, username, usernameHash, passwordHash, true, false); superAdminHashmap[usernameHash] = admin; isDefaultAdminAdded = true; } } function modifySuperAdminLoginLog(string memory encUsername, string memory dateTime) public { bytes32 encUsernameHash = getStringHashedToBytes32(encUsername); superAdminLoginLog[encUsernameHash] = dateTime; } function getSuperAdminLoginLog(string memory encUsername) public view returns(string memory) { bytes32 encUsernameHash = getStringHashedToBytes32(encUsername); return superAdminLoginLog[encUsernameHash]; } //---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- //---------------------------------------------------- Election Details ------------------------------------------------------------------------------------------------------------ /*struct electionDetails { string electionId; string electionAlias; string year; string date; uint numberOfConstituency; string typeOfConstituency; uint index; bool flag; //hash value to store constituency details mapping(uint => bytes32) constituencyStorageHash; } struct constituencyDetails { string district; string state; string constituencyNumber; uint numberOfVoters; string dateOfElection; string time; bool flag; //hash value to store voter's details } struct constituencyData { string district; string state; string constituencyNumber; uint numberOfVoters; string dateOfElection; string time; } struct electionData { string electionAlias; string year; string date; uint numberOfConsituency; string typeOfConstituency; uint indexSize; uint index; } struct superAdminForElection { uint index; mapping (uint => bytes32) electionStorageHash; } mapping (bytes32 => superAdminForElection) adminForElection; mapping (bytes32 => electionDetails) electionMap; mapping (bytes32 => constituencyDetails) constituencyMap; function createConstituencyUsingSuperAdmin(string memory username, string memory encUsername, string memory password, uint userElectionIndex, string memory constituencyId, string memory district, string memory stateName,string memory constituencyNumber, uint numberOfVoters, string memory date, string memory time) public { if (authSuperAdmin(username, encUsername, password)) { bytes32 adminHash = getStringHashedToBytes32(encUsername); bytes32 constituencyIndexHash = getStringHashedToBytes32(constituencyId); superAdminForElection storage adminElection = adminForElection[adminHash]; bytes32 electionAddress = adminElection.electionStorageHash[userElectionIndex]; electionDetails storage eDetails = electionMap[electionAddress]; uint cIndex = eDetails.index; constituencyDetails storage cDetails = constituencyMap[constituencyIndexHash]; cDetails.district = district; cDetails.state = stateName; cDetails.constituencyNumber = constituencyNumber; cDetails.numberOfVoters = numberOfVoters; cDetails.dateOfElection = date; cDetails.time = time; cDetails.flag = true; eDetails.constituencyStorageHash[cIndex] = constituencyIndexHash; eDetails.index += 1; } } function createElectionUsingSuperAdmin(string memory username, string memory encUsername, string memory password, string memory electionId ,string memory electionAlias, string memory year, string memory typeOfElection, string memory date, uint numberOfConstituencyT) public { if (authSuperAdmin(username, encUsername, password)) { bytes32 adminHashValue = getStringHashedToBytes32(encUsername); bytes32 electionIdHashValue = getStringHashedToBytes32(electionId); electionDetails storage eDetails = electionMap[electionIdHashValue]; eDetails.electionId = electionId; eDetails.electionAlias = electionAlias; eDetails.year = year; eDetails.date = date; eDetails.typeOfConstituency = typeOfElection; eDetails.numberOfConstituency = numberOfConstituencyT; eDetails.flag = true; superAdminForElection storage adminElection = adminForElection[adminHashValue]; uint electionIndex = adminElection.index; adminElection.electionStorageHash[electionIndex] = electionIdHashValue; adminElection.index += 1; } } /*function createConstituencyUsingSuperAdmin(string memory username, string memory encUsername, string memory password, string memory electionId, string memory constituencyId,string memory district, string memory state, string memory constituencyNumber, uint numberOfVoters, string memory date, string memory time) public { if (authSuperAdmin(username, encUsername, password)) { bytes32 electionIndexHash = getStringHashedToBytes32(electionId); bytes32 constituencyIndexHash = getStringHashedToBytes32(constituencyId); electionDetails storage eDetails = electionMap[electionIndexHash]; uint cIndex = eDetails.index; constituencyDetails storage cDetails = constituencyMap[constituencyIndexHash]; cDetails.district = district; cDetails.state = state; cDetails.constituencyNumber = constituencyNumber; cDetails.numberOfVoters = numberOfVoters; cDetails.dateOfElection = date; cDetails.time = time; cDetails.flag = true; eDetails.constituencyStorageHash[cIndex] = constituencyIndexHash; eDetails.index += 1; } }*/ /*function getAllElectionData(string memory username, string memory encUsername, string memory password) public view returns(electionData[] memory) { if (authSuperAdmin(username, encUsername, password)) { bytes32 usernameHash = getStringHashedToBytes32(encUsername); superAdminForElection storage adminElection = adminForElection[usernameHash]; uint adminIndex = adminElection.index; electionData[] memory eData = new electionData[](adminIndex); for (uint i = 0; i < adminIndex; i++) { bytes32 electionAddress = adminElection.electionStorageHash[i]; electionDetails storage eDetails = electionMap[electionAddress]; string memory electionAlias = eDetails.electionAlias; string memory year = eDetails.year; string memory date = eDetails.date; uint numberOfConsituency = eDetails.numberOfConstituency; string memory typeOfConstituency = eDetails.typeOfConstituency; uint size = eDetails.index; electionData memory data = electionData(electionAlias, year, date, numberOfConsituency, typeOfConstituency, size, i); eData[i] = data; } return eData; } else { electionData[] memory eData = new electionData[](0); return eData; } } function getConstituentDetails(string memory username, string memory encUsername, string memory password, uint electionIndex) public view returns(constituencyData[] memory) { if (authSuperAdmin(username, encUsername, password)) { bytes32 adminHashValue = getStringHashedToBytes32(encUsername); superAdminForElection storage adminElection = adminForElection[adminHashValue]; bytes32 electionAddress = adminElection.electionStorageHash[electionIndex]; electionDetails storage eDetails = electionMap[electionAddress]; uint size = eDetails.index; constituencyData[] memory cData = new constituencyData[](size); for (uint i = 0; i < size; i++) { bytes32 constituencyAddress = eDetails.constituencyStorageHash[i]; constituencyDetails storage cDetails = constituencyMap[constituencyAddress]; string memory district = cDetails.district; string memory stateName = cDetails.state; string memory constituencyNumber = cDetails.constituencyNumber; uint numberOfVoters = cDetails.numberOfVoters; string memory dateOfElection = cDetails.dateOfElection; string memory time = cDetails.time; constituencyData memory data = constituencyData(district, stateName, constituencyNumber, numberOfVoters, dateOfElection, time); cData[i] = data; } return cData; } else { constituencyData[] memory cData = new constituencyData[](0); return cData; } } function isElectionProvidedUnderAdmin(string memory encUsername, string memory electionId, uint electionIndex) private view returns(bool) { bytes32 usernameHash = getStringHashedToBytes32(encUsername); superAdminForElection storage adminElection = adminForElection[usernameHash]; bytes32 electionDataAddress = adminElection.electionStorageHash[electionIndex]; electionDetails storage adminElectionDetails = electionMap[electionDataAddress]; string memory adminElectionId = adminElectionDetails.electionId; if (isEqual(adminElectionId, electionId)) { return true; } return false; }*/ //---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- struct stateDetails { string constitutionId; string state; string district; string constitutionName; string taluk; bool occupied; } struct stateInfo { string stateName; uint index; } struct state { bool occupied; string stateName; uint statesCount; mapping (uint => string) details; } uint numberOfStates = 0; uint numberOfConstituency = 0; mapping (uint => string) stateLocationHash; mapping (string => state) stateList; mapping (string => stateDetails) constituencyTable; function addConstituencyData(string memory username, string memory encUsername, string memory password, string memory stateId, string memory stateName, string memory constituencyId, string memory district, string memory constitutionName, string memory taluk) public { if (authSuperAdmin(username, encUsername, password) && !constituencyTable[constituencyId].occupied) { state storage stateData = stateList[stateId]; if (!stateData.occupied) { stateLocationHash[numberOfStates] = stateId; stateData.occupied = true; numberOfStates += 1; } stateData.stateName = stateName; uint index = stateData.statesCount; stateDetails memory details = stateDetails(constituencyId, stateName, district, constitutionName, taluk, true); stateData.details[index] = constituencyId; constituencyTable[constituencyId] = details; stateData.statesCount += 1; numberOfConstituency += 1; } } function isConstituencyIdOccupied(string memory username, string memory encUsername, string memory password, string memory constituencyId) public view returns(bool) { if (authSuperAdmin(username, encUsername, password)) { stateDetails memory details = constituencyTable[constituencyId]; return details.occupied; } else { return false; } } function getStateList(string memory username, string memory encUsername, string memory password) public view returns(stateInfo[] memory) { if (authSuperAdmin(username, encUsername, password)) { stateInfo[] memory stateArray = new stateInfo[](numberOfStates); for (uint i = 0; i < numberOfStates; i++) { string memory stateLocationAddress = stateLocationHash[i]; state storage stateData = stateList[stateLocationAddress]; stateArray[i].stateName = stateData.stateName; stateArray[i].index = i; } return stateArray; } else { stateInfo[] memory data = new stateInfo[](0); return data; } } function getCorresspondingStateList(string memory username, string memory encUsername, string memory password, uint index) public view returns(stateDetails[] memory) { if (authSuperAdmin(username, encUsername, password)) { string memory stateAddress = stateLocationHash[index]; state storage stateData = stateList[stateAddress]; uint size = stateData.statesCount; stateDetails[] memory stateArray = new stateDetails[](size); for (uint i = 0; i < size; i++) { string memory id = stateData.details[i]; stateArray[i] = constituencyTable[id]; } return stateArray; } else { stateDetails[] memory data = new stateDetails[](0); return data; } } function getCorrespondingConstituencyDetail(string memory username, string memory encUsername, string memory password, string memory constituencyId) public view returns(stateDetails memory) { if (authSuperAdmin(username, encUsername, password)) { return constituencyTable[constituencyId]; } revert("Not Found"); } function getCorrespondingConstituencyDetails(string memory constituencyId) public view returns(stateDetails memory) { return constituencyTable[constituencyId]; } //---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- struct voter { string aadharNumber; string voterId; string name; string dateOfBirth; string constituencyId; string contactNumber; string emailAddress; string residentialAddress; bool occupied; } struct individualVoterData { string aadharNumber; string voterId; string name; string dateOfBirth; string state; string district; string taluk; string constituencyId; string residentialAddress; } struct constituencyVoters { uint numberOfVoters; mapping (uint => string) voter; } mapping(string => constituencyVoters) votersList; mapping(string => voter) votersTable; function addVoterDetails(string memory encUsername, string memory aadharNumber, string memory voterId, string memory name, string memory dateOfBirth, string memory constituencyId, string memory contactNumber, string memory emailAddress, string memory residentialAddress) public { if (authSuperAdminEnc(encUsername)) { voter memory voterData = voter(aadharNumber, voterId, name, dateOfBirth, constituencyId, contactNumber, emailAddress, residentialAddress, true); votersTable[voterId] = voterData; constituencyVoters storage list = votersList[constituencyId]; uint size = list.numberOfVoters; list.voter[size] = voterId; list.numberOfVoters += 1; } } function getIndividualVoterDetail(string memory username, string memory encUsername, string memory password, string memory voterId) public view returns(individualVoterData memory) { if (authSuperAdmin(username, encUsername, password) && votersTable[voterId].occupied) { voter memory voterData = votersTable[voterId]; string memory aadharNumber = voterData.aadharNumber; string memory name = voterData.name; string memory dateOfBirth = voterData.dateOfBirth; string memory constituencyId = voterData.constituencyId; stateDetails memory stateData = constituencyTable[constituencyId]; string memory stateName = stateData.state; string memory district = stateData.district; string memory taluk = stateData.taluk; string memory residentialAddress = voterData.residentialAddress; individualVoterData memory data = individualVoterData(aadharNumber, voterId, name, dateOfBirth, stateName, district, taluk, constituencyId, residentialAddress); return data; } revert("Not found"); } function getConstituencyVotersList(string memory username, string memory encUsername, string memory password, string memory constituencyId) public view returns(voter[] memory) { if (authSuperAdmin(username, encUsername, password)) { constituencyVoters storage list = votersList[constituencyId]; uint size = list.numberOfVoters; voter[] memory voters = new voter[](size); for (uint i = 0; i < size; i++) { string memory voterId = list.voter[i]; voter memory details = votersTable[voterId]; voters[i] = details; } return voters; } revert(); } function isVoterIdValid(string memory username, string memory encUsername, string memory password, string memory voterId) public view returns(uint) { if (authSuperAdmin(username, encUsername, password)) { if (votersTable[voterId].occupied) { return 500; //voter Id taken (Not available) } return 200; //available } else { return 400; //invalid user } } //---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- struct election { string electionAlias; string electionId; string year; string dateOfElection; bool occupied; uint numberOfConstituency; mapping (uint => string) constituencyAddress; } struct electionDetail { string electionAlias; string electionId; string year; string dateOfElection; uint numberOfConstituency; } struct adminAssociatedElection { uint numberOfElection; mapping (uint => string) electionId; } struct constituencyElection { uint numberOfElection; mapping (uint => string) electionList; } mapping (string => election) electionTable; mapping (bytes32 => adminAssociatedElection) adminElection; mapping (string => constituencyElection) electionConstituencyTable; function createElection(string memory username, string memory encUsername, string memory password, string memory electionAlias, string memory electionId, string memory year, string memory dateOfElection) public { if (authSuperAdmin(username, encUsername, password)) { bytes32 usernameHash = getStringHashedToBytes32(encUsername); adminAssociatedElection storage associatedElection = adminElection[usernameHash]; uint electionCount = associatedElection.numberOfElection; associatedElection.electionId[electionCount] = electionId; associatedElection.numberOfElection += 1; election storage electionData = electionTable[electionId]; electionData.electionAlias = electionAlias; electionData.electionId = electionId; electionData.year = year; electionData.dateOfElection = dateOfElection; electionData.occupied = true; } } function getElection(string memory username, string memory encUsername, string memory password) public view returns(electionDetail[] memory) { if (authSuperAdmin(username, encUsername, password)) { bytes32 usernameHash = getStringHashedToBytes32(encUsername); adminAssociatedElection storage associatedElection = adminElection[usernameHash]; uint numberOfElections = associatedElection.numberOfElection; electionDetail[] memory detail = new electionDetail[](numberOfElections); for (uint index = 0; index < numberOfElections; index++) { string memory electionIndex = associatedElection.electionId[index]; election storage electionData = electionTable[electionIndex]; electionDetail memory eDetail = electionDetail(electionData.electionAlias, electionData.electionId, electionData.year, electionData.dateOfElection, electionData.numberOfConstituency); detail[index] = eDetail; } return detail; } revert("invalid authentication"); } function addElectionConstitution(string memory username, string memory encUsername, string memory password, string memory electionId, string memory constituencyId) public { if (authSuperAdmin(username, encUsername, password)) { election storage electionData = electionTable[electionId]; uint indexOfConstituency = electionData.numberOfConstituency; electionData.constituencyAddress[indexOfConstituency] = constituencyId; electionData.numberOfConstituency += 1; constituencyElection storage cElection = electionConstituencyTable[constituencyId]; uint numberOfConstituencyElection = cElection.numberOfElection; cElection.electionList[numberOfConstituencyElection] = electionId; cElection.numberOfElection += 1; } } function getElectionConstituencyDetail(string memory username, string memory encUsername, string memory password, string memory electionId) public view returns(stateDetails[] memory) { if (authSuperAdmin(username, encUsername, password)) { election storage electionData = electionTable[electionId]; uint count = electionData.numberOfConstituency; stateDetails[] memory details = new stateDetails[](count); for (uint index = 0; index < count; index++) { string memory consituencyAddress = electionData.constituencyAddress[index]; details[index] = getCorrespondingConstituencyDetails(consituencyAddress); } return details; } revert("invalid authentication"); } //---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- function getStringHashedToBytes32(string memory toBeHashedString) private pure returns(bytes32) { return sha256(abi.encodePacked(toBeHashedString)); } function isEqual(string memory input1, string memory input2) private pure returns(bool) { return (getStringHashedToBytes32(input1) == getStringHashedToBytes32(input2)); } function isEqualByBytes32(bytes32 input1, bytes32 input2) private pure returns(bool) { return (input1 == input2); } }
will add the details into hashmap once all the api calls are satisfied
function finallyAddSuperAdmin(string memory name, string memory emailId, string memory username, string memory encUsername, string memory password, string memory adminUsername) public { superAdminDetails memory adminDetails = superAdminDetails(name, emailId, username, encUsername, password); if (isSuperAdminUsernameTaken(adminUsername)) { addSuperAdmin(adminDetails, adminUsername); } }
5,350,369
[ 1, 20194, 527, 326, 3189, 1368, 1651, 1458, 3647, 777, 326, 1536, 4097, 854, 18958, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 3095, 986, 8051, 4446, 12, 1080, 3778, 508, 16, 533, 3778, 2699, 548, 16, 533, 3778, 2718, 16, 533, 3778, 2446, 8575, 16, 533, 3778, 2201, 16, 533, 3778, 3981, 8575, 13, 1071, 288, 203, 3639, 2240, 4446, 3790, 3778, 3981, 3790, 273, 2240, 4446, 3790, 12, 529, 16, 2699, 548, 16, 2718, 16, 2446, 8575, 16, 2201, 1769, 203, 3639, 309, 261, 291, 8051, 4446, 8575, 27486, 12, 3666, 8575, 3719, 288, 203, 5411, 527, 8051, 4446, 12, 3666, 3790, 16, 3981, 8575, 1769, 203, 3639, 289, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; /** * @title ERC20 * @dev ERC20 Contract interface(s) */ contract ERC20 { function balanceOf (address _owner) public constant returns (uint256 balance); function transfer ( address _to, uint256 _value) public returns (bool success); function transferFrom (address _from, address _to, uint256 _value) public returns (bool success); function approve (address _spender, uint256 _value) public returns (bool success); function allowance (address _owner, address _spender) public constant returns (uint256 remaining); function totalSupply () public constant returns (uint); event Transfer (address indexed _from, address indexed _to, uint _value); event Approval (address indexed _owner, address indexed _spender, uint _value); } /** * @title TokenRecipient */ interface TokenRecipient { /* fundtion definitions */ function receiveApproval (address _from, uint256 _value, address _token, bytes _extraData) external; } /** * @title SafeMath math library * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev 'a + b', Adds two numbers, throws on overflow */ function add (uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require (c >= a); return c; } /** * @dev 'a - b', Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend) */ function sub (uint256 a, uint256 b) internal pure returns (uint256 c) { require (a >= b); c = a - b; return c; } /** * @dev 'a * b', multiplies two numbers, throws on overflow */ function mul (uint256 a, uint256 b) internal pure returns (uint256 c) { c = a * b; require (a == 0 || c / a == b); return c; } /** * @dev 'a / b', Integer division of two numbers, truncating the quotient */ function div (uint256 a, uint256 b) internal pure returns (uint256 c) { require (b > 0); c = a / b; return c; } } /** * @title ERC20Token * @dev Implementation of the ERC20 Token */ contract ERC20Token is ERC20 { using SafeMath for uint256; /* balance of each account */ mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; /** * @dev Creates a ERC20 Contract with its name, symbol, decimals, and total supply of token * @param _name name of token * @param _symbol name of symbol * @param _decimals decimals * @param _initSupply total supply of tokens */ constructor (string _name, string _symbol, uint8 _decimals, uint256 _initSupply) public { name = _name; // set the name for display purpose symbol = _symbol; // set the symbol for display purpose decimals = _decimals; // 18 decimals is the strongly suggested totalSupply = _initSupply * (10 ** uint256 (decimals)); // update total supply with the decimal amount balances[msg.sender] = totalSupply; // give the creator all initial tokens emit Transfer (address(0), msg.sender, totalSupply); } /** * @dev Get the token balance for account `_owner` */ function balanceOf (address _owner) public view returns (uint256 balance) { return balances[_owner]; } /* function to access name, symbol, decimals, total-supply of token. */ function name () public view returns (string _name ) { return name; } function symbol () public view returns (string _symbol ) { return symbol; } function decimals () public view returns (uint8 _decimals) { return decimals; } function totalSupply () public view returns (uint256 _supply ) { return totalSupply; } /** * @dev Internal transfer, only can be called by this contract */ function _transfer (address _from, address _to, uint256 _value) internal { require (_to != 0x0); // prevent transfer to 0x0 address require (balances[_from] >= _value); // check if the sender has enough require (balances[_to ] + _value > balances[_to]);// check for overflows uint256 previous = balances[_from] + balances[_to]; // save this for an assertion in the future balances[_from] = balances[_from].sub (_value); // subtract from the sender balances[_to ] = balances[_to ].add (_value); // add the same to the recipient emit Transfer (_from, _to, _value); /* Asserts are used to use static analysis to find bugs in your code. They should never fail */ assert (balances[_from] + balances[_to] == previous); } /** * @dev Transfer the balance from owner's account to another account "_to" * owner's account must have sufficient balance to transfer * 0 value transfers are allowed * @param _to The address of the recipient * @param _value The amount to send * @return true if the operation was successful. */ function transfer (address _to, uint256 _value) public returns (bool success) { _transfer (msg.sender, _to, _value); return true; } /** * @dev Send `_value` amount of tokens from `_from` account to `_to` account * The calling account must already have sufficient tokens approved for * spending from the `_from` account * @param _from The address of the sender * @param _to The address of the recipient * @param _value The amount to send * @return true if the operation was successful. */ function transferFrom (address _from, address _to, uint256 _value) public returns (bool success) { require (allowed[_from][msg.sender] >= _value); // check allowance allowed [_from][msg.sender] = allowed [_from][msg.sender].sub (_value); _transfer (_from, _to, _value); return true; } /** * @dev Get the amount of tokens approved by the owner that can be transferred * to the spender's account * @param _owner The address owner * @param _spender The address authorized to spend * @return The amount of tokens remained for the approved by the owner that can * be transferred */ function allowance (address _owner, address _spender) public constant returns (uint remaining) { return allowed[_owner][_spender]; } /** * @dev Set allowance for other address * Allow `_spender` to withdraw from your account, multiple times, * up to the `_value` amount. If this function is called again it * overwrites the current allowance with _value. * Token owner can approve for `spender` to transferFrom (...) `tokens` * from the token owner's account * @param _spender The address authorized to spend * @param _value the max amount they can spend * @return true if the operation was successful. */ function approve (address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; emit Approval (msg.sender, _spender, _value); return true; } /** * @dev Set allowance for other address and notify * Allows `_spender` to spend no more than `_value` tokens in your behalf, * and then ping the contract about it * @param _spender the address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract * @return true if the operation was successful. */ function approveAndCall (address _spender, uint256 _value, bytes _extraData) public returns (bool success) { TokenRecipient spender = TokenRecipient (_spender); if (approve (_spender, _value)) { spender.receiveApproval (msg.sender, _value, address (this), _extraData); return true; } } } /** * @title Ownable * @notice For user and inter-contract ownership and safe ownership transfers. * @dev The Ownable contract has an owner address, and provides basic * authorization control functions */ contract Ownable { address public owner; /* the address of the contract's owner */ /* logged on change & renounce of owner */ event OwnershipTransferred (address indexed _owner, address indexed _to); event OwnershipRenounced (address indexed _owner); /** * @dev Sets the original 'owner' of the contract to the sender account */ constructor () public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner */ modifier onlyOwner { require (msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a '_to' * @param _to The address to transfer ownership to */ function transferOwnership (address _to) public onlyOwner { require (_to != address(0)); emit OwnershipTransferred (owner, _to); owner = _to; } /** * @dev Allows the current owner to relinquish control of the contract. * This will remove all ownership of the contract, _safePhrase must * be equal to "This contract is to be disowned" * @param _safePhrase Input string to prevent one's mistake */ function renounceOwnership (bytes32 _safePhrase) public onlyOwner { require (_safePhrase == "This contract is to be disowned."); emit OwnershipRenounced (owner); owner = address(0); } } /** * @title ExpERC20Token */ contract ExpERC20Token is ERC20Token, Ownable { /** * @dev Creates a ERC20 Contract with its name, symbol, decimals, and total supply of token * @param _name name of token * @param _symbol name of symbol * @param _decimals decimals * @param _initSupply total supply of tokens */ constructor ( string _name, // name of token string _symbol, // name of symbol uint8 _decimals, // decimals uint256 _initSupply // total supply of tokens ) ERC20Token (_name, _symbol, _decimals, _initSupply) public {} /** * @notice Only the creator can alter the name & symbol * @param _name newer token name to be changed * @param _symbol newer token symbol to be changed */ function changeName (string _name, string _symbol) onlyOwner public { name = _name; symbol = _symbol; } /* ====================================================================== * Burnable functions */ /* This notifies clients about the amount burnt */ event Burn (address indexed from, uint256 value); /** * Internal burn, only can be called by this contract */ function _burn (address _from, uint256 _value) internal { require (balances[_from] >= _value); // check if the sender has enough balances[_from] = balances[_from].sub (_value); // subtract from the sender totalSupply = totalSupply.sub (_value); // updates totalSupply emit Burn (_from, _value); } /** * @dev remove `_value` tokens from the system irreversibly * @param _value the amount of money to burn * @return true if the operation was successful. */ function burn (uint256 _value) public returns (bool success) { _burn (msg.sender, _value); return true; } /** * @dev 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 * @return true if the operation was successful. */ function burnFrom (address _from, uint256 _value) public returns (bool success) { require (allowed [_from][msg.sender] >= _value); allowed [_from][msg.sender] = allowed [_from][msg.sender].sub (_value); _burn (_from, _value); return true; } /* ====================================================================== * Mintable functions */ /* event for mint's */ event Mint (address indexed _to, uint256 _amount); event MintFinished (); bool public mintingFinished = false; /* Throws if it is not mintable status */ modifier canMint () { require (!mintingFinished); _; } /* Throws if called by any account other than the owner */ modifier hasMintPermission () { require (msg.sender == owner); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint (address _to, uint256 _amount) hasMintPermission canMint public returns (bool) { totalSupply = totalSupply.add (_amount); balances[_to] = balances[_to].add (_amount); emit Mint (_to, _amount); emit Transfer (address (0), this, _amount); emit Transfer ( this, _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting () onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished (); return true; } /* ====================================================================== * Lockable Token */ bool public tokenLocked = false; /* event for Token's lock or unlock */ event Lock (address indexed _target, bool _locked); mapping (address => bool) public frozenAccount; /* This generates a public event on the blockchain that will notify clients */ event FrozenFunds (address target, bool frozen); /** * @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens * @param _target address to be frozen * @param _freeze either to freeze it or not */ function freezeAccount (address _target, bool _freeze) onlyOwner public { frozenAccount[_target] = _freeze; emit FrozenFunds (_target, _freeze); } /* Throws if it is not locked status */ modifier whenTokenUnlocked () { require (!tokenLocked); _; } /* Internal token-lock, only can be called by this contract */ function _lock (bool _value) internal { require (tokenLocked != _value); tokenLocked = _value; emit Lock (this, tokenLocked); } /** * @dev function to check token is lock or not */ function isTokenLocked () public view returns (bool success) { return tokenLocked; } /** * @dev function to lock/unlock this token * @param _value flag to be locked or not */ function lock (bool _value) onlyOwner public returns (bool) { _lock (_value); return true; } /** * @dev Transfer the balance from owner's account to another account "_to" * owner's account must have sufficient balance to transfer * 0 value transfers are allowed * @param _to The address of the recipient * @param _value The amount to send * @return true if the operation was successful. */ function transfer (address _to, uint256 _value) whenTokenUnlocked public returns (bool success) { require (!frozenAccount[msg.sender]); // check if sender is frozen require (!frozenAccount[_to ]); // check if recipient is frozen return super.transfer (_to, _value); } /** * @dev Send `_value` amount of tokens from `_from` account to `_to` account * The calling account must already have sufficient tokens approved for * spending from the `_from` account * @param _from The address of the sender * @param _to The address of the recipient * @param _value The amount to send * @return true if the operation was successful. */ function transferFrom (address _from, address _to, uint256 _value) whenTokenUnlocked public returns (bool success) { require (!frozenAccount[msg.sender]); // check if sender is frozen require (!frozenAccount[_from]); // check if token-owner is frozen require (!frozenAccount[_to ]); // check if recipient is frozen return super.transferFrom (_from, _to, _value); } /** * @dev Set allowance for other address * Allow `_spender` to withdraw from your account, multiple times, * up to the `_value` amount. If this function is called again it * overwrites the current allowance with _value. * Token owner can approve for `spender` to transferFrom (...) `tokens` * from the token owner's account * @param _spender The address authorized to spend * @param _value the max amount they can spend * @return true if the operation was successful. */ function approve (address _spender, uint256 _value) whenTokenUnlocked public returns (bool success) { require (!frozenAccount[msg.sender]); // check if sender is frozen require (!frozenAccount[_spender ]); // check if token-owner is frozen return super.approve (_spender, _value); } /** * @dev Set allowance for other address and notify * Allows `_spender` to spend no more than `_value` tokens in your behalf, * and then ping the contract about it * @param _spender the address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract * @return true if the operation was successful. */ function approveAndCall (address _spender, uint256 _value, bytes _extraData) whenTokenUnlocked public returns (bool success) { require (!frozenAccount[msg.sender]); // check if sender is frozen require (!frozenAccount[_spender ]); // check if token-owner is frozen return super.approveAndCall (_spender, _value, _extraData); } /* ====================================================================== * buy & sell functions */ uint256 public sellPrice; uint256 public buyPrice; /* Internal transfer, only can be called by this contract */ function _transfer (address _from, address _to, uint _value) internal { require (_to != 0x0); // prevent transfer to 0x0 address require (balances[_from] >= _value); // check if the sender has enough require (balances[_to ] + _value >= balances[_to]); // check for overflows require (!frozenAccount[_from]); // check if sender is frozen require (!frozenAccount[_to ]); // check if recipient is frozen balances[_from] = balances[_from].sub (_value); // Subtract from the sender balances[_to ] = balances[_to ].add (_value); // Add the same to the recipient emit Transfer (_from, _to, _value); } /** * @notice allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth * @param _sellPrice Price the users can sell to the contract * @param _buyPrice Price users can buy from the contract */ function setPrices (uint256 _sellPrice, uint256 _buyPrice) onlyOwner public { sellPrice = _sellPrice; buyPrice = _buyPrice ; } /** * @notice Buy tokens from contract by sending ether */ function buy () whenTokenUnlocked payable public { uint amount = msg.value / buyPrice; // calculates the amount _transfer (this, msg.sender, amount); // makes the transfers } /** * @notice sell `_amount` tokens to contract * @param _amount amount of tokens to be sold */ function sell (uint256 _amount) whenTokenUnlocked public { require (balances[this] >= _amount * sellPrice); // checks if the contract has enough ether to buy _transfer (msg.sender, this, _amount); // makes the transfers msg.sender.transfer (_amount * sellPrice); // sends ether to the seller. It's important to do this last to avoid recursion attacks } }
update total supply with the decimal amount
totalSupply = _initSupply * (10 ** uint256 (decimals));
5,376,230
[ 1, 2725, 2078, 14467, 598, 326, 6970, 3844, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2078, 3088, 1283, 273, 389, 2738, 3088, 1283, 380, 261, 2163, 2826, 2254, 5034, 261, 31734, 10019, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/7700/0xf160D4a4f60A1C901Ec894943Fb6d06413ce7E61/sources/src/contracts/Minter.sol
mint should revert on failure!
sCANTO.mint(_to, amountToMint);
4,659,518
[ 1, 81, 474, 1410, 15226, 603, 5166, 5, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 272, 39, 1258, 4296, 18, 81, 474, 24899, 869, 16, 3844, 774, 49, 474, 1769, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.5.6; /** * @title Metamorphic Contract Factory * @author 0age * @notice This contract creates metamorphic contracts, or contracts that can be * redeployed with new code to the same address. It does so by deploying a * contract with fixed, non-deterministic initialization code via the CREATE2 * opcode. This contract clones the implementation contract in its constructor. * Once a contract undergoes metamorphosis, all existing storage will be deleted * and any existing contract code will be replaced with the deployed contract * code of the new implementation contract. * @dev CREATE2 will not be available on mainnet until (at least) block * 7,280,000. This contract has not yet been fully tested or audited - proceed * with caution and please share any exploits or optimizations you discover. */ contract MetamorphicContractFactory { // fires when a metamorphic contract is deployed by cloning another contract. event Metamorphosed(address metamorphicContract, address newImplementation); // fires when a metamorphic contract is deployed through a transient contract. event MetamorphosedWithConstructor( address metamorphicContract, address transientContract ); // store the initialization code for metamorphic contracts. bytes private _metamorphicContractInitializationCode; // store hash of the initialization code for metamorphic contracts as well. bytes32 private _metamorphicContractInitializationCodeHash; // store init code for transient contracts that deploy metamorphic contracts. bytes private _transientContractInitializationCode; // store the hash of the initialization code for transient contracts as well. bytes32 private _transientContractInitializationCodeHash; // maintain a mapping of metamorphic contracts to metamorphic implementations. mapping(address => address) private _implementations; // maintain a mapping of transient contracts to metamorphic init codes. mapping(address => bytes) private _initCodes; /** * @dev In the constructor, set up the initialization code for metamorphic * contracts as well as the keccak256 hash of the given initialization code. * @param transientContractInitializationCode bytes The initialization code * that will be used to deploy any transient contracts, which will deploy any * metamorphic contracts that require the use of a constructor. * * Metamorphic contract initialization code (29 bytes): * * 0x5860208158601c335a63aaf10f428752fa158151803b80938091923cf3 * * Description: * * pc|op|name | [stack] | <memory> * * ** set the first stack item to zero - used later ** * 00 58 getpc [0] <> * * ** set second stack item to 32, length of word returned from staticcall ** * 01 60 push1 * 02 20 outsize [0, 32] <> * * ** set third stack item to 0, position of word returned from staticcall ** * 03 81 dup2 [0, 32, 0] <> * * ** set fourth stack item to 4, length of selector given to staticcall ** * 04 58 getpc [0, 32, 0, 4] <> * * ** set fifth stack item to 28, position of selector given to staticcall ** * 05 60 push1 * 06 1c inpos [0, 32, 0, 4, 28] <> * * ** set the sixth stack item to msg.sender, target address for staticcall ** * 07 33 caller [0, 32, 0, 4, 28, caller] <> * * ** set the seventh stack item to msg.gas, gas to forward for staticcall ** * 08 5a gas [0, 32, 0, 4, 28, caller, gas] <> * * ** set the eighth stack item to selector, "what" to store via mstore ** * 09 63 push4 * 10 aaf10f42 selector [0, 32, 0, 4, 28, caller, gas, 0xaaf10f42] <> * * ** set the ninth stack item to 0, "where" to store via mstore *** * 11 87 dup8 [0, 32, 0, 4, 28, caller, gas, 0xaaf10f42, 0] <> * * ** call mstore, consume 8 and 9 from the stack, place selector in memory ** * 12 52 mstore [0, 32, 0, 4, 0, caller, gas] <0xaaf10f42> * * ** call staticcall, consume items 2 through 7, place address in memory ** * 13 fa staticcall [0, 1 (if successful)] <address> * * ** flip success bit in second stack item to set to 0 ** * 14 15 iszero [0, 0] <address> * * ** push a third 0 to the stack, position of address in memory ** * 15 81 dup2 [0, 0, 0] <address> * * ** place address from position in memory onto third stack item ** * 16 51 mload [0, 0, address] <> * * ** place address to fourth stack item for extcodesize to consume ** * 17 80 dup1 [0, 0, address, address] <> * * ** get extcodesize on fourth stack item for extcodecopy ** * 18 3b extcodesize [0, 0, address, size] <> * * ** dup and swap size for use by return at end of init code ** * 19 80 dup1 [0, 0, address, size, size] <> * 20 93 swap4 [size, 0, address, size, 0] <> * * ** push code position 0 to stack and reorder stack items for extcodecopy ** * 21 80 dup1 [size, 0, address, size, 0, 0] <> * 22 91 swap2 [size, 0, address, 0, 0, size] <> * 23 92 swap3 [size, 0, size, 0, 0, address] <> * * ** call extcodecopy, consume four items, clone runtime code to memory ** * 24 3c extcodecopy [size, 0] <code> * * ** return to deploy final code in memory ** * 25 f3 return [] *deployed!* * * * Transient contract initialization code derived from TransientContract.sol. */ constructor(bytes memory transientContractInitializationCode) public { // assign the initialization code for the metamorphic contract. _metamorphicContractInitializationCode = ( hex"5860208158601c335a63aaf10f428752fa158151803b80938091923cf3" ); // calculate and assign keccak256 hash of metamorphic initialization code. _metamorphicContractInitializationCodeHash = keccak256( abi.encodePacked( _metamorphicContractInitializationCode ) ); // store the initialization code for the transient contract. _transientContractInitializationCode = transientContractInitializationCode; // calculate and assign keccak256 hash of transient initialization code. _transientContractInitializationCodeHash = keccak256( abi.encodePacked( _transientContractInitializationCode ) ); } /* solhint-disable function-max-lines */ /** * @dev Deploy a metamorphic contract by submitting a given salt or nonce * along with the initialization code for the metamorphic contract, and * optionally provide calldata for initializing the new metamorphic contract. * To replace the contract, first selfdestruct the current contract, then call * with the same salt value and new initialization code (be aware that all * existing state will be wiped from the existing contract). Also note that * the first 20 bytes of the salt must match the calling address, which * prevents contracts from being created by unintended parties. * @param salt bytes32 The nonce that will be passed into the CREATE2 call and * thus will determine the resulant address of the metamorphic contract. * @param implementationContractInitializationCode bytes The initialization * code for the implementation contract for the metamorphic contract. It will * be used to deploy a new contract that the metamorphic contract will then * clone in its constructor. * @param metamorphicContractInitializationCalldata bytes An optional data * parameter that can be used to atomically initialize the metamorphic * contract. * @return Address of the metamorphic contract that will be created. */ function deployMetamorphicContract( bytes32 salt, bytes calldata implementationContractInitializationCode, bytes calldata metamorphicContractInitializationCalldata ) external payable containsCaller(salt) returns ( address metamorphicContractAddress ) { // move implementation init code and initialization calldata to memory. bytes memory implInitCode = implementationContractInitializationCode; bytes memory data = metamorphicContractInitializationCalldata; // move the initialization code from storage to memory. bytes memory initCode = _metamorphicContractInitializationCode; // declare variable to verify successful metamorphic contract deployment. address deployedMetamorphicContract; // determine the address of the metamorphic contract. metamorphicContractAddress = _getMetamorphicContractAddress(salt); // declare a variable for the address of the implementation contract. address implementationContract; // load implementation init code and length, then deploy via CREATE. /* solhint-disable no-inline-assembly */ assembly { let encoded_data := add(0x20, implInitCode) // load initialization code. let encoded_size := mload(implInitCode) // load init code's length. implementationContract := create( // call CREATE with 3 arguments. 0, // do not forward any endowment. encoded_data, // pass in initialization code. encoded_size // pass in init code's length. ) } /* solhint-enable no-inline-assembly */ require( implementationContract != address(0), "Could not deploy implementation." ); // store the implementation to be retrieved by the metamorphic contract. _implementations[metamorphicContractAddress] = implementationContract; // load metamorphic contract data and length of data and deploy via CREATE2. /* solhint-disable no-inline-assembly */ assembly { let encoded_data := add(0x20, initCode) // load initialization code. let encoded_size := mload(initCode) // load the init code's length. deployedMetamorphicContract := create2( // call CREATE2 with 4 arguments. 0, // do not forward any endowment. encoded_data, // pass in initialization code. encoded_size, // pass in init code's length. salt // pass in the salt value. ) } /* solhint-enable no-inline-assembly */ // ensure that the contracts were successfully deployed. require( deployedMetamorphicContract == metamorphicContractAddress, "Failed to deploy the new metamorphic contract." ); // initialize the new metamorphic contract if any data or value is provided. if (data.length > 0 || msg.value > 0) { /* solhint-disable avoid-call-value */ (bool success,) = deployedMetamorphicContract.call.value(msg.value)(data); /* solhint-enable avoid-call-value */ require(success, "Failed to initialize the new metamorphic contract."); } emit Metamorphosed(deployedMetamorphicContract, implementationContract); } /* solhint-enable function-max-lines */ /** * @dev Deploy a metamorphic contract by submitting a given salt or nonce * along with the address of an existing implementation contract to clone, and * optionally provide calldata for initializing the new metamorphic contract. * To replace the contract, first selfdestruct the current contract, then call * with the same salt value and a new implementation address (be aware that * all existing state will be wiped from the existing contract). Also note * that the first 20 bytes of the salt must match the calling address, which * prevents contracts from being created by unintended parties. * @param salt bytes32 The nonce that will be passed into the CREATE2 call and * thus will determine the resulant address of the metamorphic contract. * @param implementationContract address The address of the existing * implementation contract to clone. * @param metamorphicContractInitializationCalldata bytes An optional data * parameter that can be used to atomically initialize the metamorphic * contract. * @return Address of the metamorphic contract that will be created. */ function deployMetamorphicContractFromExistingImplementation( bytes32 salt, address implementationContract, bytes calldata metamorphicContractInitializationCalldata ) external payable containsCaller(salt) returns ( address metamorphicContractAddress ) { // move initialization calldata to memory. bytes memory data = metamorphicContractInitializationCalldata; // move the initialization code from storage to memory. bytes memory initCode = _metamorphicContractInitializationCode; // declare variable to verify successful metamorphic contract deployment. address deployedMetamorphicContract; // determine the address of the metamorphic contract. metamorphicContractAddress = _getMetamorphicContractAddress(salt); // store the implementation to be retrieved by the metamorphic contract. _implementations[metamorphicContractAddress] = implementationContract; // using inline assembly: load data and length of data, then call CREATE2. /* solhint-disable no-inline-assembly */ assembly { let encoded_data := add(0x20, initCode) // load initialization code. let encoded_size := mload(initCode) // load the init code's length. deployedMetamorphicContract := create2( // call CREATE2 with 4 arguments. 0, // do not forward any endowment. encoded_data, // pass in initialization code. encoded_size, // pass in init code's length. salt // pass in the salt value. ) } /* solhint-enable no-inline-assembly */ // ensure that the contracts were successfully deployed. require( deployedMetamorphicContract == metamorphicContractAddress, "Failed to deploy the new metamorphic contract." ); // initialize the new metamorphic contract if any data or value is provided. if (data.length > 0 || msg.value > 0) { /* solhint-disable avoid-call-value */ (bool success,) = metamorphicContractAddress.call.value(msg.value)(data); /* solhint-enable avoid-call-value */ require(success, "Failed to initialize the new metamorphic contract."); } emit Metamorphosed(deployedMetamorphicContract, implementationContract); } /* solhint-disable function-max-lines */ /** * @dev Deploy a metamorphic contract by submitting a given salt or nonce * along with the initialization code to a transient contract which will then * deploy the metamorphic contract before immediately selfdestructing. To * replace the metamorphic contract, first selfdestruct the current contract, * then call with the same salt value and new initialization code (be aware * that all existing state will be wiped from the existing contract). Also * note that the first 20 bytes of the salt must match the calling address, * which prevents contracts from being created by unintended parties. * @param salt bytes32 The nonce that will be passed into the CREATE2 call and * thus will determine the resulant address of the metamorphic contract. * @param initializationCode bytes The initialization code for the metamorphic * contract that will be deployed by the transient contract. * @return Address of the metamorphic contract that will be created. */ function deployMetamorphicContractWithConstructor( bytes32 salt, bytes calldata initializationCode ) external payable containsCaller(salt) returns ( address metamorphicContractAddress ) { // move transient contract initialization code from storage to memory. bytes memory initCode = _transientContractInitializationCode; // declare variable to verify successful transient contract deployment. address deployedTransientContract; // determine the address of the transient contract. address transientContractAddress = _getTransientContractAddress(salt); // store the initialization code to be retrieved by the transient contract. _initCodes[transientContractAddress] = initializationCode; // load transient contract data and length of data, then deploy via CREATE2. /* solhint-disable no-inline-assembly */ assembly { let encoded_data := add(0x20, initCode) // load initialization code. let encoded_size := mload(initCode) // load the init code's length. deployedTransientContract := create2( // call CREATE2 with 4 arguments. callvalue, // forward any supplied endowment. encoded_data, // pass in initialization code. encoded_size, // pass in init code's length. salt // pass in the salt value. ) } /* solhint-enable no-inline-assembly */ // ensure that the contracts were successfully deployed. require( deployedTransientContract == transientContractAddress, "Failed to deploy metamorphic contract using given salt and init code." ); metamorphicContractAddress = _getMetamorphicContractAddressWithConstructor( transientContractAddress ); emit MetamorphosedWithConstructor( metamorphicContractAddress, transientContractAddress ); } /* solhint-enable function-max-lines */ /** * @dev View function for retrieving the address of the implementation * contract to clone. Called by the constructor of each metamorphic contract. */ function getImplementation() external view returns (address implementation) { return _implementations[msg.sender]; } /** * @dev View function for retrieving the initialization code for a given * metamorphic contract to deploy via a transient contract. Called by the * constructor of each transient contract. * @return The initialization code to use to deploy the metamorphic contract. */ function getInitializationCode() external view returns ( bytes memory initializationCode ) { return _initCodes[msg.sender]; } /** * @dev View function for retrieving the address of the current implementation * contract of a given metamorphic contract, where the address of the contract * is supplied as an argument. Be aware that the implementation contract has * an independent state and may have been altered or selfdestructed from when * it was last cloned by the metamorphic contract. * @param metamorphicContractAddress address The address of the metamorphic * contract. * @return Address of the corresponding implementation contract. */ function getImplementationContractAddress( address metamorphicContractAddress ) external view returns (address implementationContractAddress) { return _implementations[metamorphicContractAddress]; } /** * @dev View function for retrieving the initialization code for a given * metamorphic contract instance deployed via a transient contract, where the address * of the transient contract is supplied as an argument. * @param transientContractAddress address The address of the transient * contract that deployed the metamorphic contract. * @return The initialization code used to deploy the metamorphic contract. */ function getMetamorphicContractInstanceInitializationCode( address transientContractAddress ) external view returns (bytes memory initializationCode) { return _initCodes[transientContractAddress]; } /** * @dev Compute the address of the metamorphic contract that will be created * upon submitting a given salt to the contract. * @param salt bytes32 The nonce passed into CREATE2 by metamorphic contract. * @return Address of the corresponding metamorphic contract. */ function findMetamorphicContractAddress( bytes32 salt ) external view returns (address metamorphicContractAddress) { // determine the address where the metamorphic contract will be deployed. metamorphicContractAddress = _getMetamorphicContractAddress(salt); } /** * @dev Compute the address of the transient contract that will be created * upon submitting a given salt to the contract. * @param salt bytes32 The nonce passed into CREATE2 when deploying the * transient contract. * @return Address of the corresponding transient contract. */ function findTransientContractAddress( bytes32 salt ) external view returns (address transientContractAddress) { // determine the address where the transient contract will be deployed. transientContractAddress = _getTransientContractAddress(salt); } /** * @dev Compute the address of the metamorphic contract that will be created * by the transient contract upon submitting a given salt to the contract. * @param salt bytes32 The nonce passed into CREATE2 when deploying the * transient contract. * @return Address of the corresponding metamorphic contract. */ function findMetamorphicContractAddressWithConstructor( bytes32 salt ) external view returns (address metamorphicContractAddress) { // determine the address of the metamorphic contract. metamorphicContractAddress = _getMetamorphicContractAddressWithConstructor( _getTransientContractAddress(salt) ); } /** * @dev View function for retrieving the initialization code of metamorphic * contracts for purposes of verification. */ function getMetamorphicContractInitializationCode() external view returns ( bytes memory metamorphicContractInitializationCode ) { return _metamorphicContractInitializationCode; } /** * @dev View function for retrieving the keccak256 hash of the initialization * code of metamorphic contracts for purposes of verification. */ function getMetamorphicContractInitializationCodeHash() external view returns ( bytes32 metamorphicContractInitializationCodeHash ) { return _metamorphicContractInitializationCodeHash; } /** * @dev View function for retrieving the initialization code of transient * contracts for purposes of verification. */ function getTransientContractInitializationCode() external view returns ( bytes memory transientContractInitializationCode ) { return _transientContractInitializationCode; } /** * @dev View function for retrieving the keccak256 hash of the initialization * code of transient contracts for purposes of verification. */ function getTransientContractInitializationCodeHash() external view returns ( bytes32 transientContractInitializationCodeHash ) { return _transientContractInitializationCodeHash; } /** * @dev Internal view function for calculating a metamorphic contract address * given a particular salt. */ function _getMetamorphicContractAddress( bytes32 salt ) internal view returns (address) { // determine the address of the metamorphic contract. return address( uint160( // downcast to match the address type. uint256( // convert to uint to truncate upper digits. keccak256( // compute the CREATE2 hash using 4 inputs. abi.encodePacked( // pack all inputs to the hash together. hex"ff", // start with 0xff to distinguish from RLP. address(this), // this contract will be the caller. salt, // pass in the supplied salt value. _metamorphicContractInitializationCodeHash // the init code hash. ) ) ) ) ); } /** * @dev Internal view function for calculating a transient contract address * given a particular salt. */ function _getTransientContractAddress( bytes32 salt ) internal view returns (address) { // determine the address of the transient contract. return address( uint160( // downcast to match the address type. uint256( // convert to uint to truncate upper digits. keccak256( // compute the CREATE2 hash using 4 inputs. abi.encodePacked( // pack all inputs to the hash together. hex"ff", // start with 0xff to distinguish from RLP. address(this), // this contract will be the caller. salt, // pass in the supplied salt value. _transientContractInitializationCodeHash // supply init code hash. ) ) ) ) ); } /** * @dev Internal view function for calculating a metamorphic contract address * that has been deployed via a transient contract given the address of the * transient contract. */ function _getMetamorphicContractAddressWithConstructor( address transientContractAddress ) internal pure returns (address) { // determine the address of the metamorphic contract. return address( uint160( // downcast to match the address type. uint256( // set to uint to truncate upper digits. keccak256( // compute CREATE hash via RLP encoding. abi.encodePacked( // pack all inputs to the hash together. byte(0xd6), // first RLP byte. byte(0x94), // second RLP byte. transientContractAddress, // called by the transient contract. byte(0x01) // nonce begins at 1 for contracts. ) ) ) ) ); } /** * @dev Modifier to ensure that the first 20 bytes of a submitted salt match * those of the calling account. This provides protection against the salt * being stolen by frontrunners or other attackers. * @param salt bytes32 The salt value to check against the calling address. */ modifier containsCaller(bytes32 salt) { // prevent contract submissions from being stolen from tx.pool by requiring // that the first 20 bytes of the submitted salt match msg.sender. require( address(bytes20(salt)) == msg.sender, "Invalid salt - first 20 bytes of the salt must match calling address." ); _; } }
* @dev Internal view function for calculating a metamorphic contract address given a particular salt./ determine the address of the metamorphic contract.
function _getMetamorphicContractAddress( bytes32 salt ) internal view returns (address) { return address( ) ) ) ) ); }
12,604,746
[ 1, 3061, 1476, 445, 364, 21046, 279, 5100, 301, 18435, 6835, 1758, 864, 279, 6826, 4286, 18, 19, 4199, 326, 1758, 434, 326, 5100, 301, 18435, 6835, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 389, 588, 12244, 301, 18435, 8924, 1887, 12, 203, 565, 1731, 1578, 4286, 203, 225, 262, 2713, 1476, 1135, 261, 2867, 13, 288, 203, 565, 327, 1758, 12, 203, 5411, 262, 203, 1850, 262, 203, 3639, 262, 203, 1377, 262, 203, 565, 11272, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/42/0xA17716b2e0ec620B5BD7eb0b6fE1b8C2dCa57679/sources/CompoundNoFoldStrategyUSDTTestnet.sol
Comptroller: Enter the market comptroller.enterMarkets(cTokens);
suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. <one line to give the program's name and a brief idea of what it does.> Copyright (C) <year> <name of author> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: <program> Copyright (C) <year> <name of author> This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read pragma solidity ^0.5.0; } pragma solidity 0.5.16; ) public { comptroller = ComptrollerInterface(_comptroller); underlying = IERC20(_underlying); ctoken = CompleteCToken(_ctoken); address[] memory cTokens = new address[](1); cTokens[0] = _ctoken; }
3,383,171
[ 1, 799, 337, 1539, 30, 15439, 326, 13667, 3639, 532, 337, 1539, 18, 2328, 3882, 2413, 12, 71, 5157, 1769, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 87, 3809, 1812, 358, 3387, 716, 326, 17545, 5957, 445, 310, 434, 326, 4358, 733, 203, 710, 353, 316, 1158, 648, 5309, 329, 578, 1554, 586, 329, 598, 3704, 2357, 2724, 203, 31064, 711, 2118, 7165, 18, 203, 203, 225, 971, 1846, 6292, 402, 392, 733, 981, 1440, 3613, 333, 2442, 316, 16, 578, 598, 16, 578, 203, 12524, 1230, 364, 999, 316, 16, 279, 2177, 8094, 16, 471, 326, 6292, 402, 310, 9938, 487, 203, 2680, 434, 279, 2492, 316, 1492, 326, 2145, 434, 949, 3184, 471, 999, 434, 326, 203, 1299, 8094, 353, 906, 4193, 358, 326, 8027, 316, 1534, 6951, 89, 560, 578, 364, 279, 203, 12429, 2481, 261, 1574, 1060, 2656, 434, 3661, 326, 2492, 353, 3351, 1235, 3631, 326, 203, 6217, 17863, 310, 4998, 6292, 402, 329, 3613, 333, 2442, 1297, 506, 1721, 2919, 304, 2092, 203, 1637, 326, 10284, 367, 15353, 18, 225, 12484, 333, 12405, 1552, 486, 2230, 203, 430, 15826, 1846, 12517, 1281, 12126, 18285, 325, 4167, 326, 7123, 358, 3799, 203, 7342, 733, 981, 603, 326, 2177, 8094, 261, 1884, 3454, 16, 326, 1440, 711, 203, 2196, 275, 5876, 316, 534, 1872, 2934, 203, 203, 225, 1021, 12405, 358, 5615, 10284, 367, 15353, 1552, 486, 2341, 279, 203, 30848, 358, 1324, 358, 5615, 2865, 1156, 16, 341, 5399, 970, 93, 16, 578, 4533, 203, 1884, 279, 1440, 716, 711, 2118, 4358, 578, 5876, 635, 326, 8027, 16, 578, 364, 203, 5787, 2177, 8094, 316, 1492, 518, 711, 2118, 4358, 578, 5876, 18, 225, 5016, 358, 2 ]
// SPDX-License-Identifier: AGPLv3 pragma solidity 0.8.4; import "@openzeppelin/contracts/access/Ownable.sol"; interface IHodler { function totalBonus() external view returns (uint256); function correctionAmount() external view returns (uint256); } interface IVester { function vestingBalance(address _account) external view returns (uint256); function totalGroove() external view returns (uint256); function vest(address account, uint256 amount) external; } /// @notice GRP vesting bonus claims contract - Where all unvested GRO are returned if user exits vesting contract early contract GROHodler is Ownable { uint256 public constant DEFAULT_DECIMAL_FACTOR = 1E18; // The main vesting contract address public immutable vester; // Total amount of unvested GRO that has been tossed aside uint256 public totalBonus; // Estimation of total unvested GRO can become unreliable if there is a significant // amount of users who have vesting periods that exceed their vesting end date. // We use a manual correction variable to deal with this issue for now. uint256 public correctionAmount; // How long you have to wait between claims uint256 public claimDelay; // Contract that can help maintain the bonus contract by adjusting variables address public maintainer; // keep track of users last claim mapping(address => uint256) public userClaims; bool paused = true; event LogBonusAdded(uint256 amount); event LogBonusClaimed(address user, uint256 amount); event LogNewClaimDelay(uint256 delay); event LogNewCorrectionVariable(uint256 correction); event LogNewMaintainer(address newMaintainer); event LogNewStatus(bool status); constructor(address _vester, address oldHodler) { vester = _vester; // if we migrated to a new bonus contract, make sure to add the old bonus and correction if (oldHodler != address(0)) { totalBonus = IHodler(oldHodler).totalBonus(); correctionAmount = IHodler(oldHodler).correctionAmount(); } } /// @notice every time a users exits a vesting position, the penalty gets added to this contract /// @param amount user penealty amount function add(uint256 amount) external { require(msg.sender == vester); totalBonus += amount; emit LogBonusAdded(amount); } /// @notice Set a new maintainer /// @param newMaintainer address of new maintainer /// @dev Maintainer will mostly be used to be able to change the correctionValue /// on short notice, as this can change on short notice depending on if users interact with /// their position in the vesting contract function setMaintainer(address newMaintainer) external onlyOwner { maintainer = newMaintainer; emit LogNewMaintainer(newMaintainer); } /// @notice Start or stop the bonus contract /// @param pause Contract Pause state function setStatus(bool pause) external { require(msg.sender == maintainer || msg.sender == owner(), 'setCorrectionVariable: !authorized'); paused = pause; emit LogNewStatus(pause); } /// @notice maintainer can correct total amount of vested GRO to adjust for drift of central curve vs user curves /// @param newCorrection a positive number to deduct from the unvested GRO to correct for central drift function setCorrectionVariable(uint256 newCorrection) external { require(msg.sender == maintainer || msg.sender == owner(), 'setCorrectionVariable: !authorized'); require(newCorrection <= IVester(vester).totalGroove(), 'setCorrectionVariable: correctionAmount to large'); correctionAmount = newCorrection; emit LogNewCorrectionVariable(newCorrection); } /// @notice after every bonus claim, a user has to wait some time before they can claim again /// @param delay time delay until next claim is possible function setClaimDelay(uint256 delay) external onlyOwner { claimDelay = delay; emit LogNewClaimDelay(delay); } /// @notice Get the pending bonus a user can claim function getPendingBonus() public view returns (uint256) { uint256 userGroove = IVester(vester).vestingBalance(msg.sender); // if the user doesnt have a vesting position, they cannot claim if (userGroove == 0) { return 0; } // if for some reason the user has a larger vesting position than the // current vesting position - correctionAmount, then give them the whole bonus. // This should only happen if: theres only one vesting position, someone forgot to // update the correctionAmount; uint256 globalGroove = IVester(vester).totalGroove() - correctionAmount; if (userGroove >= globalGroove) { return totalBonus; } uint256 userAmount = userGroove * totalBonus / globalGroove; return userAmount; } /// @notice User claims available bonus function claim() external returns (uint256) { // user cannot claim if they have claimed recently or the contract is paused if (userClaims[msg.sender] + claimDelay >= block.timestamp || paused) { return 0; } uint256 userAmount = getPendingBonus(); if (userAmount > 0) { userClaims[msg.sender] = block.timestamp; totalBonus -= userAmount; IVester(vester).vest(msg.sender, userAmount); emit LogBonusClaimed(msg.sender, userAmount); } return userAmount; } function canClaim() external view returns (bool) { if (userClaims[msg.sender] + claimDelay >= block.timestamp || paused) { return false; } return true; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev 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; } }
@notice User claims available bonus user cannot claim if they have claimed recently or the contract is paused
function claim() external returns (uint256) { if (userClaims[msg.sender] + claimDelay >= block.timestamp || paused) { return 0; } uint256 userAmount = getPendingBonus(); if (userAmount > 0) { userClaims[msg.sender] = block.timestamp; totalBonus -= userAmount; IVester(vester).vest(msg.sender, userAmount); emit LogBonusClaimed(msg.sender, userAmount); } return userAmount; }
1,100,318
[ 1, 1299, 11955, 2319, 324, 22889, 729, 2780, 7516, 309, 2898, 1240, 7516, 329, 19907, 578, 326, 6835, 353, 17781, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7516, 1435, 3903, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 309, 261, 1355, 15925, 63, 3576, 18, 15330, 65, 397, 7516, 6763, 1545, 1203, 18, 5508, 747, 17781, 13, 288, 203, 5411, 327, 374, 31, 203, 3639, 289, 203, 3639, 2254, 5034, 729, 6275, 273, 1689, 2846, 38, 22889, 5621, 203, 3639, 309, 261, 1355, 6275, 405, 374, 13, 288, 203, 5411, 729, 15925, 63, 3576, 18, 15330, 65, 273, 1203, 18, 5508, 31, 203, 5411, 2078, 38, 22889, 3947, 729, 6275, 31, 203, 5411, 21602, 7654, 12, 3324, 387, 2934, 26923, 12, 3576, 18, 15330, 16, 729, 6275, 1769, 203, 5411, 3626, 1827, 38, 22889, 9762, 329, 12, 3576, 18, 15330, 16, 729, 6275, 1769, 203, 3639, 289, 203, 3639, 327, 729, 6275, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/42/0xe74EFb19BBC46DbE28b7BaB1F14af6eB7158B4BE/sources/L1_Bridge.sol
* @title MerkleUtils/
library MerkleUtils { function getMerkleRoot( bytes32[] memory _hashes ) internal pure returns ( bytes32 _root ) { require( _hashes.length > 0, "Must provide at least one leaf hash." ); if (_hashes.length == 1) { return _hashes[0]; } bytes32[] memory defaultHashes = _getDefaultHashes(_hashes.length); bytes32[] memory nodes = _hashes; if (_hashes.length % 2 == 1) { nodes = new bytes32[](_hashes.length + 1); for (uint256 i = 0; i < _hashes.length; i++) { nodes[i] = _hashes[i]; } } uint256 currentLevel = 0; uint256 nextLevelSize = _hashes.length; if (nextLevelSize % 2 == 1) { nodes[nextLevelSize] = defaultHashes[currentLevel]; nextLevelSize += 1; } while (nextLevelSize > 1) { currentLevel += 1; for (uint256 i = 0; i < nextLevelSize / 2; i++) { nodes[i] = _getParentHash( nodes[i*2], nodes[i*2 + 1] ); } nextLevelSize = nextLevelSize / 2; if (nextLevelSize % 2 == 1 && nextLevelSize != 1) { nodes[nextLevelSize] = defaultHashes[currentLevel]; nextLevelSize += 1; } } return nodes[0]; } { require( _hashes.length > 0, "Must provide at least one leaf hash." ); if (_hashes.length == 1) { return _hashes[0]; } bytes32[] memory defaultHashes = _getDefaultHashes(_hashes.length); bytes32[] memory nodes = _hashes; if (_hashes.length % 2 == 1) { nodes = new bytes32[](_hashes.length + 1); for (uint256 i = 0; i < _hashes.length; i++) { nodes[i] = _hashes[i]; } } uint256 currentLevel = 0; uint256 nextLevelSize = _hashes.length; if (nextLevelSize % 2 == 1) { nodes[nextLevelSize] = defaultHashes[currentLevel]; nextLevelSize += 1; } while (nextLevelSize > 1) { currentLevel += 1; for (uint256 i = 0; i < nextLevelSize / 2; i++) { nodes[i] = _getParentHash( nodes[i*2], nodes[i*2 + 1] ); } nextLevelSize = nextLevelSize / 2; if (nextLevelSize % 2 == 1 && nextLevelSize != 1) { nodes[nextLevelSize] = defaultHashes[currentLevel]; nextLevelSize += 1; } } return nodes[0]; } { require( _hashes.length > 0, "Must provide at least one leaf hash." ); if (_hashes.length == 1) { return _hashes[0]; } bytes32[] memory defaultHashes = _getDefaultHashes(_hashes.length); bytes32[] memory nodes = _hashes; if (_hashes.length % 2 == 1) { nodes = new bytes32[](_hashes.length + 1); for (uint256 i = 0; i < _hashes.length; i++) { nodes[i] = _hashes[i]; } } uint256 currentLevel = 0; uint256 nextLevelSize = _hashes.length; if (nextLevelSize % 2 == 1) { nodes[nextLevelSize] = defaultHashes[currentLevel]; nextLevelSize += 1; } while (nextLevelSize > 1) { currentLevel += 1; for (uint256 i = 0; i < nextLevelSize / 2; i++) { nodes[i] = _getParentHash( nodes[i*2], nodes[i*2 + 1] ); } nextLevelSize = nextLevelSize / 2; if (nextLevelSize % 2 == 1 && nextLevelSize != 1) { nodes[nextLevelSize] = defaultHashes[currentLevel]; nextLevelSize += 1; } } return nodes[0]; } { require( _hashes.length > 0, "Must provide at least one leaf hash." ); if (_hashes.length == 1) { return _hashes[0]; } bytes32[] memory defaultHashes = _getDefaultHashes(_hashes.length); bytes32[] memory nodes = _hashes; if (_hashes.length % 2 == 1) { nodes = new bytes32[](_hashes.length + 1); for (uint256 i = 0; i < _hashes.length; i++) { nodes[i] = _hashes[i]; } } uint256 currentLevel = 0; uint256 nextLevelSize = _hashes.length; if (nextLevelSize % 2 == 1) { nodes[nextLevelSize] = defaultHashes[currentLevel]; nextLevelSize += 1; } while (nextLevelSize > 1) { currentLevel += 1; for (uint256 i = 0; i < nextLevelSize / 2; i++) { nodes[i] = _getParentHash( nodes[i*2], nodes[i*2 + 1] ); } nextLevelSize = nextLevelSize / 2; if (nextLevelSize % 2 == 1 && nextLevelSize != 1) { nodes[nextLevelSize] = defaultHashes[currentLevel]; nextLevelSize += 1; } } return nodes[0]; } { require( _hashes.length > 0, "Must provide at least one leaf hash." ); if (_hashes.length == 1) { return _hashes[0]; } bytes32[] memory defaultHashes = _getDefaultHashes(_hashes.length); bytes32[] memory nodes = _hashes; if (_hashes.length % 2 == 1) { nodes = new bytes32[](_hashes.length + 1); for (uint256 i = 0; i < _hashes.length; i++) { nodes[i] = _hashes[i]; } } uint256 currentLevel = 0; uint256 nextLevelSize = _hashes.length; if (nextLevelSize % 2 == 1) { nodes[nextLevelSize] = defaultHashes[currentLevel]; nextLevelSize += 1; } while (nextLevelSize > 1) { currentLevel += 1; for (uint256 i = 0; i < nextLevelSize / 2; i++) { nodes[i] = _getParentHash( nodes[i*2], nodes[i*2 + 1] ); } nextLevelSize = nextLevelSize / 2; if (nextLevelSize % 2 == 1 && nextLevelSize != 1) { nodes[nextLevelSize] = defaultHashes[currentLevel]; nextLevelSize += 1; } } return nodes[0]; } { require( _hashes.length > 0, "Must provide at least one leaf hash." ); if (_hashes.length == 1) { return _hashes[0]; } bytes32[] memory defaultHashes = _getDefaultHashes(_hashes.length); bytes32[] memory nodes = _hashes; if (_hashes.length % 2 == 1) { nodes = new bytes32[](_hashes.length + 1); for (uint256 i = 0; i < _hashes.length; i++) { nodes[i] = _hashes[i]; } } uint256 currentLevel = 0; uint256 nextLevelSize = _hashes.length; if (nextLevelSize % 2 == 1) { nodes[nextLevelSize] = defaultHashes[currentLevel]; nextLevelSize += 1; } while (nextLevelSize > 1) { currentLevel += 1; for (uint256 i = 0; i < nextLevelSize / 2; i++) { nodes[i] = _getParentHash( nodes[i*2], nodes[i*2 + 1] ); } nextLevelSize = nextLevelSize / 2; if (nextLevelSize % 2 == 1 && nextLevelSize != 1) { nodes[nextLevelSize] = defaultHashes[currentLevel]; nextLevelSize += 1; } } return nodes[0]; } { require( _hashes.length > 0, "Must provide at least one leaf hash." ); if (_hashes.length == 1) { return _hashes[0]; } bytes32[] memory defaultHashes = _getDefaultHashes(_hashes.length); bytes32[] memory nodes = _hashes; if (_hashes.length % 2 == 1) { nodes = new bytes32[](_hashes.length + 1); for (uint256 i = 0; i < _hashes.length; i++) { nodes[i] = _hashes[i]; } } uint256 currentLevel = 0; uint256 nextLevelSize = _hashes.length; if (nextLevelSize % 2 == 1) { nodes[nextLevelSize] = defaultHashes[currentLevel]; nextLevelSize += 1; } while (nextLevelSize > 1) { currentLevel += 1; for (uint256 i = 0; i < nextLevelSize / 2; i++) { nodes[i] = _getParentHash( nodes[i*2], nodes[i*2 + 1] ); } nextLevelSize = nextLevelSize / 2; if (nextLevelSize % 2 == 1 && nextLevelSize != 1) { nodes[nextLevelSize] = defaultHashes[currentLevel]; nextLevelSize += 1; } } return nodes[0]; } { require( _hashes.length > 0, "Must provide at least one leaf hash." ); if (_hashes.length == 1) { return _hashes[0]; } bytes32[] memory defaultHashes = _getDefaultHashes(_hashes.length); bytes32[] memory nodes = _hashes; if (_hashes.length % 2 == 1) { nodes = new bytes32[](_hashes.length + 1); for (uint256 i = 0; i < _hashes.length; i++) { nodes[i] = _hashes[i]; } } uint256 currentLevel = 0; uint256 nextLevelSize = _hashes.length; if (nextLevelSize % 2 == 1) { nodes[nextLevelSize] = defaultHashes[currentLevel]; nextLevelSize += 1; } while (nextLevelSize > 1) { currentLevel += 1; for (uint256 i = 0; i < nextLevelSize / 2; i++) { nodes[i] = _getParentHash( nodes[i*2], nodes[i*2 + 1] ); } nextLevelSize = nextLevelSize / 2; if (nextLevelSize % 2 == 1 && nextLevelSize != 1) { nodes[nextLevelSize] = defaultHashes[currentLevel]; nextLevelSize += 1; } } return nodes[0]; } function getMerkleRoot( bytes[] memory _elements ) internal pure returns ( bytes32 _root ) { bytes32[] memory hashes = new bytes32[](_elements.length); for (uint256 i = 0; i < _elements.length; i++) { hashes[i] = keccak256(_elements[i]); } return getMerkleRoot(hashes); } function getMerkleRoot( bytes[] memory _elements ) internal pure returns ( bytes32 _root ) { bytes32[] memory hashes = new bytes32[](_elements.length); for (uint256 i = 0; i < _elements.length; i++) { hashes[i] = keccak256(_elements[i]); } return getMerkleRoot(hashes); } function verify( bytes32 _root, bytes32 _leaf, uint256 _path, bytes32[] memory _siblings ) internal pure returns ( bool _verified ) { bytes32 computedRoot = _leaf; for (uint256 i = 0; i < _siblings.length; i++) { bytes32 sibling = _siblings[i]; bool isRightSibling = uint8(_path >> i & 1) == 1; if (isRightSibling) { computedRoot = _getParentHash(computedRoot, sibling); computedRoot = _getParentHash(sibling, computedRoot); } } return computedRoot == _root; } function verify( bytes32 _root, bytes32 _leaf, uint256 _path, bytes32[] memory _siblings ) internal pure returns ( bool _verified ) { bytes32 computedRoot = _leaf; for (uint256 i = 0; i < _siblings.length; i++) { bytes32 sibling = _siblings[i]; bool isRightSibling = uint8(_path >> i & 1) == 1; if (isRightSibling) { computedRoot = _getParentHash(computedRoot, sibling); computedRoot = _getParentHash(sibling, computedRoot); } } return computedRoot == _root; } function verify( bytes32 _root, bytes32 _leaf, uint256 _path, bytes32[] memory _siblings ) internal pure returns ( bool _verified ) { bytes32 computedRoot = _leaf; for (uint256 i = 0; i < _siblings.length; i++) { bytes32 sibling = _siblings[i]; bool isRightSibling = uint8(_path >> i & 1) == 1; if (isRightSibling) { computedRoot = _getParentHash(computedRoot, sibling); computedRoot = _getParentHash(sibling, computedRoot); } } return computedRoot == _root; } } else { function verify( bytes32 _root, bytes memory _leaf, uint256 _path, bytes32[] memory _siblings ) internal pure returns ( bool _verified ) { return verify( _root, keccak256(_leaf), _path, _siblings ); } function _getDefaultHashes( uint256 _length ) private pure returns ( bytes32[] memory _defaultHashes ) { bytes32[] memory defaultHashes = new bytes32[](_length); defaultHashes[0] = keccak256(abi.encodePacked(uint256(0))); for (uint256 i = 1; i < defaultHashes.length; i++) { defaultHashes[i] = keccak256(abi.encodePacked(defaultHashes[i-1])); } return defaultHashes; } function _getDefaultHashes( uint256 _length ) private pure returns ( bytes32[] memory _defaultHashes ) { bytes32[] memory defaultHashes = new bytes32[](_length); defaultHashes[0] = keccak256(abi.encodePacked(uint256(0))); for (uint256 i = 1; i < defaultHashes.length; i++) { defaultHashes[i] = keccak256(abi.encodePacked(defaultHashes[i-1])); } return defaultHashes; } function _getParentHash( bytes32 _leftChildHash, bytes32 _rightChildHash ) private pure returns ( bytes32 _hash ) { return keccak256(abi.encodePacked(_leftChildHash, _rightChildHash)); } }
3,427,447
[ 1, 8478, 15609, 1989, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 12083, 31827, 1989, 288, 203, 565, 445, 30040, 15609, 2375, 12, 203, 3639, 1731, 1578, 8526, 3778, 389, 17612, 203, 565, 262, 203, 3639, 2713, 203, 3639, 16618, 203, 3639, 1135, 261, 203, 5411, 1731, 1578, 389, 3085, 203, 3639, 262, 203, 203, 203, 565, 288, 203, 3639, 2583, 12, 203, 5411, 389, 17612, 18, 2469, 405, 374, 16, 203, 5411, 315, 10136, 5615, 622, 4520, 1245, 7839, 1651, 1199, 203, 3639, 11272, 203, 203, 3639, 309, 261, 67, 17612, 18, 2469, 422, 404, 13, 288, 203, 5411, 327, 389, 17612, 63, 20, 15533, 203, 3639, 289, 203, 203, 3639, 1731, 1578, 8526, 3778, 805, 14455, 273, 389, 588, 1868, 14455, 24899, 17612, 18, 2469, 1769, 203, 203, 3639, 1731, 1578, 8526, 3778, 2199, 273, 389, 17612, 31, 203, 3639, 309, 261, 67, 17612, 18, 2469, 738, 576, 422, 404, 13, 288, 203, 5411, 2199, 273, 394, 1731, 1578, 8526, 24899, 17612, 18, 2469, 397, 404, 1769, 203, 5411, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 389, 17612, 18, 2469, 31, 277, 27245, 288, 203, 7734, 2199, 63, 77, 65, 273, 389, 17612, 63, 77, 15533, 203, 5411, 289, 203, 3639, 289, 203, 203, 3639, 2254, 5034, 783, 2355, 273, 374, 31, 203, 3639, 2254, 5034, 1024, 2355, 1225, 273, 389, 17612, 18, 2469, 31, 203, 540, 203, 3639, 309, 261, 4285, 2355, 1225, 738, 576, 422, 404, 13, 288, 203, 5411, 2199, 63, 4285, 2355, 1225, 65, 273, 805, 14455, 63, 2972, 2355, 15533, 203, 5411, 1024, 2355, 1225, 1011, 2 ]
./full_match/137/0x1689eF902B72068Ba1E18b3831fDeFf71aD2137D/sources/UniArtsSouvenirs.sol
* @dev Change the creator address for given token @param _to Address of the new creator @param _id Token IDs to change creator of/
function _setCreator(address _to, uint256 _id) internal creatorOnly(_id) { creators[_id] = _to; }
4,751,132
[ 1, 3043, 326, 11784, 1758, 364, 864, 1147, 225, 389, 869, 282, 5267, 434, 326, 394, 11784, 225, 389, 350, 225, 3155, 7115, 358, 2549, 11784, 434, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 542, 10636, 12, 2867, 389, 869, 16, 2254, 5034, 389, 350, 13, 2713, 11784, 3386, 24899, 350, 13, 203, 565, 288, 203, 3639, 1519, 3062, 63, 67, 350, 65, 273, 389, 869, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/137/0xe558726C468Ccc21cc09ca4B8B46131dC1002923/sources/project_/contracts/Exchange.sol
CLOB - mapping of order hash => filled quantity in pips
mapping(bytes32 => uint64) _partiallyFilledOrderQuantitiesInPips;
4,761,942
[ 1, 39, 6038, 300, 2874, 434, 1353, 1651, 516, 6300, 10457, 316, 293, 7146, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 2874, 12, 3890, 1578, 516, 2254, 1105, 13, 389, 2680, 6261, 29754, 2448, 19471, 1961, 382, 52, 7146, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./interfaces/ICStablePool.sol"; import "./interfaces/ICSTMinter.sol"; import "./interfaces/ICSTToken.sol"; import "./interfaces/ICSTFarmingProxy.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./lib/TransferHelper.sol"; /// @title Implement liquitidy farming. contract LiquidityFarmingProxy is Ownable, ICSTFarmingProxy { using SafeMath for uint256; struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. } /// @notice Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 accTokenPerShare; // Accumulated CSTs per share, times 1e12. See below. } string public name = "CStable Liquidity Farming Proxy"; string public symbol = "CLFP-V1"; ICSTToken public token; /// @notice Info of each pool. PoolInfo[] public poolInfo; /// @notice Save lp tokens whether exists. mapping(address => bool) public lpTokens; /// @notice Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; /// @notice For mint CST ICSTMinter public minter; modifier onlyMinter() { require(address(minter) == msg.sender, "caller is not the minter"); _; } event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); event SetMinter(address _minter); event AddPool(address _poolAddress); event SetPool(uint256 _pid); event UpdatePool( uint256 _pid, uint256 accTokenPerShare, uint256 _tokenReward ); event CalculatePending( uint256 _pid, uint256 _amount, uint256 rewardDebt, uint256 accTokenPerShare, uint256 pending ); event SetToken(address _token); event ZeroLPStaking( uint256 _pid, uint256 _lastRewardBlock, uint256 blockNumber ); constructor(address ownerAddress) { require(ownerAddress != address(0), "no 0 address"); transferOwnership(ownerAddress); } function setMinter(ICSTMinter _minter) public onlyOwner { require(address(_minter) != address(0), "no 0 address"); minter = _minter; emit SetMinter(address(_minter)); } function poolLength() external view returns (uint256) { return poolInfo.length; } /// @notice Add a new lp to the pool. Can only be called by the owner. function add( IERC20 _lpToken, uint256 _allocPoint, bool _withUpdate ) external onlyOwner { require(address(_lpToken) != address(0), "no 0 address"); require(!lpTokens[address(_lpToken)], "_lpToken already exist"); lpTokens[address(_lpToken)] = true; if (_withUpdate) { minter.massUpdateProxy(); } minter.add(_allocPoint, address(_lpToken)); poolInfo.push(PoolInfo({lpToken: _lpToken, accTokenPerShare: 0})); emit AddPool(address(_lpToken)); } /// @notice Update the given pool's CST allocation point. Can only be called by the owner. function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) external onlyOwner { require(_pid < poolInfo.length, "pid out of range."); if (_withUpdate) { minter.massUpdateProxy(); } minter.set(address(poolInfo[_pid].lpToken), _allocPoint); emit SetPool(_pid); } /// @notice View function to see pending CSTs on frontend. function pendingReward(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accTokenPerShare = pool.accTokenPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); (, uint256 _lastRewardBlock) = minter.getPoolInfo( address(this), address(pool.lpToken) ); if (block.number > _lastRewardBlock && lpSupply != 0) { uint256 tokenReward = minter.getReward( address(this), address(pool.lpToken) ); uint256 nAccTokenPerShare = tokenReward == 0 ? 0 : tokenReward.mul(1e12).div(lpSupply); accTokenPerShare = accTokenPerShare.add(nAccTokenPerShare); } return user.amount.mul(accTokenPerShare).div(1e12).sub(user.rewardDebt); } /// @dev Mass update pools. Only caller is minter's massUpdateProxy. function massUpdate() public override onlyMinter { _massUpdatePools(); } /// @notice Update reward vairables for all pools. Be careful of gas spending! function _massUpdatePools() internal { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { _updatePool(pid); } } /// @notice Update reward variables of the given pool to be up-to-date. /// @param _pid pool's index. function _updatePool(uint256 _pid) internal { require( _pid < poolInfo.length, "LiqudityFarmingProxy: pid out of range." ); PoolInfo storage pool = poolInfo[_pid]; (, uint256 _lastRewardBlock) = minter.getPoolInfo( address(this), address(pool.lpToken) ); if (block.number <= _lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { minter.updateLastRewardBlock(address(pool.lpToken)); emit ZeroLPStaking(_pid, _lastRewardBlock, block.number); return; } uint256 tokenReward = minter.mint(address(pool.lpToken)); pool.accTokenPerShare = pool.accTokenPerShare.add( tokenReward.mul(1e12).div(lpSupply) ); emit UpdatePool(_pid, pool.accTokenPerShare, tokenReward); } /// @notice Deposit LP tokens to BStableProxyV2 for CST allocation. function deposit(uint256 _pid, uint256 _amount) public { require( _pid < poolInfo.length, "LiqudityFarmingProxy: pid out of range." ); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; _updatePool(_pid); if (user.amount > 0) { uint256 pending = user .amount .mul(pool.accTokenPerShare) .div(1e12) .sub(user.rewardDebt); emit CalculatePending( _pid, user.amount, user.rewardDebt, pool.accTokenPerShare, pending ); safeTokenTransfer(msg.sender, pending); } user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accTokenPerShare).div(1e12); if (_amount > 0) { TransferHelper.safeTransferFrom( address(pool.lpToken), address(msg.sender), address(this), _amount ); } emit Deposit(msg.sender, _pid, _amount); } /// @notice Withdraw LP tokens . function withdraw(uint256 _pid, uint256 _amount) public { require( _pid < poolInfo.length, "LiqudityFarmingProxy: pid out of range." ); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); _updatePool(_pid); uint256 pending = user.amount.mul(pool.accTokenPerShare).div(1e12).sub( user.rewardDebt ); emit CalculatePending( _pid, user.amount, user.rewardDebt, pool.accTokenPerShare, pending ); if (pending > 0) { safeTokenTransfer(msg.sender, pending); } user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accTokenPerShare).div(1e12); if (_amount > 0) { TransferHelper.safeTransfer( address(pool.lpToken), address(msg.sender), _amount ); } emit Withdraw(msg.sender, _pid, _amount); } /// @notice Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { require( _pid < poolInfo.length, "LiqudityFarmingProxy: pid out of range." ); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 amount_ = user.amount; user.amount = 0; user.rewardDebt = 0; TransferHelper.safeTransfer( address(pool.lpToken), address(msg.sender), amount_ ); emit EmergencyWithdraw(msg.sender, _pid, amount_); } /// @notice Safe token transfer function, just in case if rounding error causes pool to not have enough CSTs. function safeTokenTransfer(address _to, uint256 _amount) internal { require(_to != address(0), "LiquidityFarmingProxy: no 0 address"); uint256 tokenBal = token.balanceOf(address(this)); if (_amount > tokenBal) { token.transfer(_to, tokenBal); } else { token.transfer(_to, _amount); } } function setToken(ICSTToken _token) external onlyOwner { require( address(_token) != address(0), "LiquidityFarmingProxy: no 0 address" ); token = _token; emit SetToken(address(_token)); } function getTokenAddress() external view returns (address) { return address(token); } }
@notice Update the given pool's CST allocation point. Can only be called by the owner.
function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) external onlyOwner { require(_pid < poolInfo.length, "pid out of range."); if (_withUpdate) { minter.massUpdateProxy(); } minter.set(address(poolInfo[_pid].lpToken), _allocPoint); emit SetPool(_pid); }
12,687,949
[ 1, 1891, 326, 864, 2845, 1807, 385, 882, 13481, 1634, 18, 4480, 1338, 506, 2566, 635, 326, 3410, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 444, 12, 203, 3639, 2254, 5034, 389, 6610, 16, 203, 3639, 2254, 5034, 389, 9853, 2148, 16, 203, 3639, 1426, 389, 1918, 1891, 203, 565, 262, 3903, 1338, 5541, 288, 203, 3639, 2583, 24899, 6610, 411, 2845, 966, 18, 2469, 16, 315, 6610, 596, 434, 1048, 1199, 1769, 203, 3639, 309, 261, 67, 1918, 1891, 13, 288, 203, 5411, 1131, 387, 18, 10424, 1891, 3886, 5621, 203, 3639, 289, 203, 3639, 1131, 387, 18, 542, 12, 2867, 12, 6011, 966, 63, 67, 6610, 8009, 9953, 1345, 3631, 389, 9853, 2148, 1769, 203, 3639, 3626, 1000, 2864, 24899, 6610, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]